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.
- cc_ghostty/__init__.py +1 -0
- cc_ghostty/__main__.py +3 -0
- cc_ghostty/claude.py +215 -0
- cc_ghostty/cli.py +253 -0
- cc_ghostty/commands/__init__.py +0 -0
- cc_ghostty/commands/_pick.py +39 -0
- cc_ghostty/commands/_selection.py +70 -0
- cc_ghostty/commands/auto_name.py +38 -0
- cc_ghostty/commands/close.py +38 -0
- cc_ghostty/commands/doctor.py +163 -0
- cc_ghostty/commands/exec_run.py +104 -0
- cc_ghostty/commands/focus.py +18 -0
- cc_ghostty/commands/hook.py +33 -0
- cc_ghostty/commands/interrupted.py +37 -0
- cc_ghostty/commands/open_tab.py +221 -0
- cc_ghostty/commands/open_tabs.py +147 -0
- cc_ghostty/commands/ps.py +53 -0
- cc_ghostty/commands/restore.py +71 -0
- cc_ghostty/commands/route.py +10 -0
- cc_ghostty/commands/settle.py +12 -0
- cc_ghostty/commands/setup.py +20 -0
- cc_ghostty/commands/snapshot.py +18 -0
- cc_ghostty/commands/split.py +24 -0
- cc_ghostty/delegate.py +68 -0
- cc_ghostty/ghostty/__init__.py +72 -0
- cc_ghostty/ghostty/atspi.py +54 -0
- cc_ghostty/ghostty/linux.py +348 -0
- cc_ghostty/ghostty/macos.py +277 -0
- cc_ghostty/layout.py +177 -0
- cc_ghostty/procs.py +169 -0
- cc_ghostty/registry.py +239 -0
- cc_ghostty/repos.py +37 -0
- cc_ghostty/restore.py +197 -0
- cc_ghostty/runs.py +216 -0
- cc_ghostty/selfcmd.py +15 -0
- cc_ghostty/sessions.py +62 -0
- cc_ghostty-0.1.0.dist-info/METADATA +167 -0
- cc_ghostty-0.1.0.dist-info/RECORD +41 -0
- cc_ghostty-0.1.0.dist-info/WHEEL +4 -0
- cc_ghostty-0.1.0.dist-info/entry_points.txt +2 -0
- cc_ghostty-0.1.0.dist-info/licenses/LICENSE +21 -0
cc_ghostty/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
cc_ghostty/__main__.py
ADDED
cc_ghostty/claude.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Read-only access to Claude Code's own files.
|
|
2
|
+
|
|
3
|
+
Config dirs, accounts, live sessions and transcripts.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shlex
|
|
9
|
+
import shutil
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from functools import cache
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from cc_ghostty import procs
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def executable() -> str:
|
|
20
|
+
"""The `claude` this process would run.
|
|
21
|
+
|
|
22
|
+
A new tab gets Ghostty's environment and a login shell's PATH, which may find
|
|
23
|
+
another `claude` (e.g. not claude-switch's wrapper, which picks the account from
|
|
24
|
+
the directory): tabs run this one by its path.
|
|
25
|
+
"""
|
|
26
|
+
return shutil.which("claude") or "claude"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def account_env(config_dir: str | None) -> str:
|
|
30
|
+
"""Shell commands pinning the next `claude` to the account of `config_dir`, the
|
|
31
|
+
default one (~/.claude) when None."""
|
|
32
|
+
if config_dir:
|
|
33
|
+
return f"export CLAUDE_CONFIG_DIR={shlex.quote(config_dir)}"
|
|
34
|
+
# CLAUDE_ACC_RUN_DEFAULT stops claude-switch's wrapper from picking an account
|
|
35
|
+
# from the cwd.
|
|
36
|
+
return "unset CLAUDE_CONFIG_DIR; export CLAUDE_ACC_RUN_DEFAULT=1"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def default_config_dir() -> Path:
|
|
40
|
+
return Path.home() / ".claude"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def resolve_config_dir(config_dir: str | None) -> Path:
|
|
44
|
+
return Path(config_dir) if config_dir else default_config_dir()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@cache
|
|
48
|
+
def account_email(config_dir: str | None) -> str | None:
|
|
49
|
+
# Without CLAUDE_CONFIG_DIR, Claude keeps its global state in ~/.claude.json,
|
|
50
|
+
# outside the config dir.
|
|
51
|
+
state_file = (
|
|
52
|
+
Path(config_dir) / ".claude.json"
|
|
53
|
+
if config_dir
|
|
54
|
+
else Path.home() / ".claude.json"
|
|
55
|
+
)
|
|
56
|
+
try:
|
|
57
|
+
data = json.loads(state_file.read_text())
|
|
58
|
+
except (OSError, ValueError):
|
|
59
|
+
return None
|
|
60
|
+
return (data.get("oauthAccount") or {}).get("emailAddress")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class LiveSession:
|
|
65
|
+
session_id: str
|
|
66
|
+
pid: int
|
|
67
|
+
cwd: str
|
|
68
|
+
config_dir: str | None
|
|
69
|
+
kind: str | None
|
|
70
|
+
name: str | None = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def live_sessions(config_dirs: Iterable[str | None]) -> list[LiveSession]:
|
|
74
|
+
"""Sessions held by a running Claude process, per Claude's own registry."""
|
|
75
|
+
live = []
|
|
76
|
+
for config_dir in dict.fromkeys(config_dirs):
|
|
77
|
+
for entry in (resolve_config_dir(config_dir) / "sessions").glob("*.json"):
|
|
78
|
+
try:
|
|
79
|
+
data = json.loads(entry.read_text())
|
|
80
|
+
except (OSError, ValueError):
|
|
81
|
+
continue
|
|
82
|
+
pid, session_id = data.get("pid"), data.get("sessionId")
|
|
83
|
+
start = data.get("procStart")
|
|
84
|
+
if pid and session_id and procs.is_alive_per_claude(pid, start):
|
|
85
|
+
live.append(
|
|
86
|
+
LiveSession(
|
|
87
|
+
session_id=session_id,
|
|
88
|
+
pid=pid,
|
|
89
|
+
cwd=data.get("cwd") or "",
|
|
90
|
+
config_dir=config_dir,
|
|
91
|
+
kind=data.get("kind"),
|
|
92
|
+
name=data.get("name"),
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
return live
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def live_session_ids(config_dirs: Iterable[str | None]) -> set[str]:
|
|
99
|
+
return {s.session_id for s in live_sessions(config_dirs)}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass
|
|
103
|
+
class TranscriptInfo:
|
|
104
|
+
session_id: str
|
|
105
|
+
path: Path
|
|
106
|
+
mtime: float
|
|
107
|
+
cwd: str | None
|
|
108
|
+
title: str | None
|
|
109
|
+
interactive: bool
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def read_transcript(path: Path) -> TranscriptInfo:
|
|
113
|
+
cwd = custom_title = ai_title = None
|
|
114
|
+
entrypoint = None
|
|
115
|
+
with path.open(errors="replace") as lines:
|
|
116
|
+
for line in lines:
|
|
117
|
+
try:
|
|
118
|
+
entry = json.loads(line)
|
|
119
|
+
except ValueError:
|
|
120
|
+
continue
|
|
121
|
+
cwd = entry.get("cwd") or cwd
|
|
122
|
+
entrypoint = entry.get("entrypoint") or entrypoint
|
|
123
|
+
if entry.get("type") == "custom-title":
|
|
124
|
+
custom_title = entry.get("customTitle") or custom_title
|
|
125
|
+
elif entry.get("type") == "ai-title":
|
|
126
|
+
ai_title = entry.get("aiTitle") or ai_title
|
|
127
|
+
return TranscriptInfo(
|
|
128
|
+
session_id=path.stem,
|
|
129
|
+
path=path,
|
|
130
|
+
mtime=path.stat().st_mtime,
|
|
131
|
+
cwd=cwd,
|
|
132
|
+
title=custom_title or ai_title,
|
|
133
|
+
interactive=entrypoint is None or not entrypoint.startswith("sdk"),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass
|
|
138
|
+
class Activity:
|
|
139
|
+
"""When a session last worked, the user's last prompt and Claude's last text."""
|
|
140
|
+
|
|
141
|
+
last_active: float | None
|
|
142
|
+
last_prompt: str | None
|
|
143
|
+
last_reply: str | None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _text(content: object) -> str | None:
|
|
147
|
+
if isinstance(content, str):
|
|
148
|
+
return content
|
|
149
|
+
if isinstance(content, list):
|
|
150
|
+
texts = [
|
|
151
|
+
b.get("text", "")
|
|
152
|
+
for b in content
|
|
153
|
+
if isinstance(b, dict) and b.get("type") == "text"
|
|
154
|
+
]
|
|
155
|
+
return "\n".join(texts) if texts else None
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _timestamp(value: object) -> float | None:
|
|
160
|
+
try:
|
|
161
|
+
return datetime.fromisoformat(str(value)).timestamp()
|
|
162
|
+
except ValueError:
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def read_activity(path: Path) -> Activity:
|
|
167
|
+
"""Commands, their output and notifications are not prompts: Claude Code writes
|
|
168
|
+
them as user entries wrapped in tags."""
|
|
169
|
+
last_active = last_prompt = last_reply = None
|
|
170
|
+
with path.open(errors="replace") as lines:
|
|
171
|
+
for line in lines:
|
|
172
|
+
try:
|
|
173
|
+
entry = json.loads(line)
|
|
174
|
+
except ValueError:
|
|
175
|
+
continue
|
|
176
|
+
kind = entry.get("type")
|
|
177
|
+
if kind not in ("user", "assistant") or entry.get("isSidechain"):
|
|
178
|
+
continue
|
|
179
|
+
last_active = _timestamp(entry.get("timestamp")) or last_active
|
|
180
|
+
text = _text((entry.get("message") or {}).get("content"))
|
|
181
|
+
if not text or not text.strip():
|
|
182
|
+
continue
|
|
183
|
+
if kind == "assistant":
|
|
184
|
+
last_reply = text
|
|
185
|
+
elif not entry.get("isMeta") and not text.lstrip().startswith("<"):
|
|
186
|
+
last_prompt = text
|
|
187
|
+
return Activity(last_active, last_prompt, last_reply)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def find_transcript(config_dir: str | None, session_id: str) -> Path | None:
|
|
191
|
+
matches = list(
|
|
192
|
+
(resolve_config_dir(config_dir) / "projects").glob(f"*/{session_id}.jsonl")
|
|
193
|
+
)
|
|
194
|
+
return max(matches, key=lambda p: p.stat().st_mtime) if matches else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def recent_transcripts(config_dir: str | None, since: float) -> list[Path]:
|
|
198
|
+
projects = resolve_config_dir(config_dir) / "projects"
|
|
199
|
+
return [p for p in projects.glob("*/*.jsonl") if p.stat().st_mtime >= since]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
CLAUDE_SWITCH_ACCOUNTS = Path(".claude-switch") / "accounts"
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def extra_config_dirs() -> list[str]:
|
|
206
|
+
"""Config dirs besides ~/.claude: CC_GHOSTTY_CONFIG_DIRS, the current
|
|
207
|
+
CLAUDE_CONFIG_DIR and claude-switch's accounts."""
|
|
208
|
+
raw = os.environ.get("CC_GHOSTTY_CONFIG_DIRS", "")
|
|
209
|
+
dirs = [d for d in raw.split(os.pathsep) if d]
|
|
210
|
+
if current := os.environ.get("CLAUDE_CONFIG_DIR"):
|
|
211
|
+
dirs.append(current)
|
|
212
|
+
accounts = Path.home() / CLAUDE_SWITCH_ACCOUNTS
|
|
213
|
+
if accounts.is_dir():
|
|
214
|
+
dirs += sorted(str(d) for d in accounts.iterdir() if d.is_dir())
|
|
215
|
+
return list(dict.fromkeys(dirs))
|
cc_ghostty/cli.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""`cc-ghostty` command line.
|
|
2
|
+
|
|
3
|
+
Every command and its options are declared here, which is cheap; the module that runs
|
|
4
|
+
a command (`cc_ghostty.commands.<name>`) is imported only when that command runs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import importlib
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
10
|
+
from typing import cast
|
|
11
|
+
|
|
12
|
+
from cc_ghostty import __version__
|
|
13
|
+
|
|
14
|
+
Handler = Callable[[argparse.Namespace], int]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _add_command(
|
|
18
|
+
sub: "argparse._SubParsersAction[argparse.ArgumentParser]",
|
|
19
|
+
name: str,
|
|
20
|
+
help: str,
|
|
21
|
+
module: str | None = None,
|
|
22
|
+
) -> argparse.ArgumentParser:
|
|
23
|
+
parser = sub.add_parser(name, help=help, description=help)
|
|
24
|
+
parser.set_defaults(handler=f"cc_ghostty.commands.{module or name}:run")
|
|
25
|
+
return parser
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _add_session_argument(parser: argparse.ArgumentParser) -> None:
|
|
29
|
+
parser.add_argument("session", help="session name, id or id prefix")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _add_selection_arguments(parser: argparse.ArgumentParser) -> None:
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--account", help="only sessions whose account email contains this text"
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"--all",
|
|
38
|
+
action="store_true",
|
|
39
|
+
help="every interrupted session, not only the last batch interrupted together",
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"--since",
|
|
43
|
+
type=float,
|
|
44
|
+
default=24.0,
|
|
45
|
+
metavar="HOURS",
|
|
46
|
+
help="look back window (default 24)",
|
|
47
|
+
)
|
|
48
|
+
source = parser.add_mutually_exclusive_group()
|
|
49
|
+
source.add_argument(
|
|
50
|
+
"--scan",
|
|
51
|
+
action="store_true",
|
|
52
|
+
help="find sessions from recently written transcripts instead of hook records",
|
|
53
|
+
)
|
|
54
|
+
source.add_argument(
|
|
55
|
+
"--closed",
|
|
56
|
+
action="store_true",
|
|
57
|
+
help="the tabs and windows closed on purpose instead (the last ones, or --all)",
|
|
58
|
+
)
|
|
59
|
+
parser.add_argument(
|
|
60
|
+
"--summary",
|
|
61
|
+
action=argparse.BooleanOptionalAction,
|
|
62
|
+
help="where each session stopped: last activity, prompt and reply (default: "
|
|
63
|
+
"on when even the latest stopped working over an hour ago)",
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--config-dir",
|
|
67
|
+
action="append",
|
|
68
|
+
default=[],
|
|
69
|
+
help="extra Claude config dir to scan (repeatable, with --scan)",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _add_tab_content_arguments(parser: argparse.ArgumentParser) -> None:
|
|
74
|
+
what = parser.add_mutually_exclusive_group()
|
|
75
|
+
what.add_argument("--prompt", help="first prompt of the new Claude session")
|
|
76
|
+
what.add_argument(
|
|
77
|
+
"--run",
|
|
78
|
+
metavar="COMMAND",
|
|
79
|
+
help="run this shell command instead of Claude (a dev server, logs…)",
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument(
|
|
82
|
+
"--name",
|
|
83
|
+
help="session or tab name (default: the repository's name, numbered if "
|
|
84
|
+
"taken; with --run, the command)",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class _PaneOption(argparse.Action):
|
|
89
|
+
"""Keeps the --pane-* options in command-line order, in `args.pane_options`,
|
|
90
|
+
for each to go with the --pane-run before it."""
|
|
91
|
+
|
|
92
|
+
def __call__(
|
|
93
|
+
self,
|
|
94
|
+
parser: argparse.ArgumentParser,
|
|
95
|
+
namespace: argparse.Namespace,
|
|
96
|
+
values: object,
|
|
97
|
+
option_string: str | None = None,
|
|
98
|
+
) -> None:
|
|
99
|
+
options = getattr(namespace, "pane_options", None) or []
|
|
100
|
+
namespace.pane_options = [*options, (self.dest, values)]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
104
|
+
parser = argparse.ArgumentParser(
|
|
105
|
+
prog="cc-ghostty", description="Claude Code integration for Ghostty."
|
|
106
|
+
)
|
|
107
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
108
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="<command>")
|
|
109
|
+
|
|
110
|
+
ps = _add_command(sub, "ps", "list running Claude sessions, with their tab")
|
|
111
|
+
ps.add_argument("--repo", metavar="PATH", help="only sessions in this repository")
|
|
112
|
+
ps.add_argument(
|
|
113
|
+
"--account", help="only sessions whose account email contains this text"
|
|
114
|
+
)
|
|
115
|
+
ps.add_argument("--json", action="store_true")
|
|
116
|
+
|
|
117
|
+
focus = _add_command(sub, "focus", "bring a session's Ghostty tab to the front")
|
|
118
|
+
_add_session_argument(focus)
|
|
119
|
+
|
|
120
|
+
close = _add_command(sub, "close", "close a session's Ghostty tab")
|
|
121
|
+
_add_session_argument(close)
|
|
122
|
+
close.add_argument(
|
|
123
|
+
"--keep-shell",
|
|
124
|
+
action="store_true",
|
|
125
|
+
help="stop Claude only, leaving the tab and its shell open",
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
open_tab = _add_command(
|
|
129
|
+
sub, "open-tab", "open a Ghostty tab running a new session", "open_tab"
|
|
130
|
+
)
|
|
131
|
+
open_tab.add_argument(
|
|
132
|
+
"directory", nargs="?", default=".", help="where the session runs (default: .)"
|
|
133
|
+
)
|
|
134
|
+
_add_tab_content_arguments(open_tab)
|
|
135
|
+
open_tab.add_argument(
|
|
136
|
+
"--window", action="store_true", help="open it in a new Ghostty window"
|
|
137
|
+
)
|
|
138
|
+
open_tab.set_defaults(pane_options=[])
|
|
139
|
+
panes = open_tab.add_argument_group(
|
|
140
|
+
"panes",
|
|
141
|
+
"Each --pane-run opens one more pane in the new tab, in turn, before the "
|
|
142
|
+
"command returns. The --pane-* options after a --pane-run are that pane's; a "
|
|
143
|
+
"pane without one takes the previous pane's value.",
|
|
144
|
+
)
|
|
145
|
+
panes.add_argument(
|
|
146
|
+
"--pane-run",
|
|
147
|
+
metavar="COMMAND",
|
|
148
|
+
action=_PaneOption,
|
|
149
|
+
help="a pane running this shell command",
|
|
150
|
+
)
|
|
151
|
+
panes.add_argument(
|
|
152
|
+
"--pane-name", action=_PaneOption, help="its name (default: the command)"
|
|
153
|
+
)
|
|
154
|
+
panes.add_argument(
|
|
155
|
+
"--pane-direction",
|
|
156
|
+
choices=["right", "down", "left", "up"],
|
|
157
|
+
action=_PaneOption,
|
|
158
|
+
help="where it opens (default: right)",
|
|
159
|
+
)
|
|
160
|
+
panes.add_argument(
|
|
161
|
+
"--pane-beside",
|
|
162
|
+
metavar="tab|previous|NAME",
|
|
163
|
+
action=_PaneOption,
|
|
164
|
+
help="the terminal it splits: the tab's own (tab), the pane opened before it "
|
|
165
|
+
"(previous) or an earlier pane by name (default: previous)",
|
|
166
|
+
)
|
|
167
|
+
open_tab.add_argument(
|
|
168
|
+
"--dry-run", action="store_true", help="print the command only"
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
open_tabs = _add_command(
|
|
172
|
+
sub,
|
|
173
|
+
"open-tabs",
|
|
174
|
+
"open the tabs of a JSON plan, each with its panes, one after another",
|
|
175
|
+
"open_tabs",
|
|
176
|
+
)
|
|
177
|
+
open_tabs.add_argument("plan", help="the plan's JSON file, or - for stdin")
|
|
178
|
+
open_tabs.add_argument(
|
|
179
|
+
"--dry-run", action="store_true", help="print the commands only"
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
split = _add_command(
|
|
183
|
+
sub, "split", "split this session's Ghostty pane, running a new session"
|
|
184
|
+
)
|
|
185
|
+
split.add_argument("direction", choices=["right", "down", "left", "up"])
|
|
186
|
+
split.add_argument(
|
|
187
|
+
"directory", nargs="?", default=".", help="where the session runs (default: .)"
|
|
188
|
+
)
|
|
189
|
+
_add_tab_content_arguments(split)
|
|
190
|
+
split.add_argument("--dry-run", action="store_true", help="print the command only")
|
|
191
|
+
|
|
192
|
+
listing = _add_command(sub, "list", "list interrupted sessions", "interrupted")
|
|
193
|
+
_add_selection_arguments(listing)
|
|
194
|
+
listing.add_argument("--json", action="store_true")
|
|
195
|
+
|
|
196
|
+
restore = _add_command(
|
|
197
|
+
sub, "restore", "reopen interrupted sessions as Ghostty tabs"
|
|
198
|
+
)
|
|
199
|
+
_add_selection_arguments(restore)
|
|
200
|
+
restore.add_argument(
|
|
201
|
+
"--target",
|
|
202
|
+
choices=["new-window", "current-window", "print"],
|
|
203
|
+
default="new-window",
|
|
204
|
+
)
|
|
205
|
+
restore.add_argument(
|
|
206
|
+
"--dry-run",
|
|
207
|
+
action="store_true",
|
|
208
|
+
help="print the commands without opening anything",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
_add_command(sub, "doctor", "check the setup cc-ghostty relies on")
|
|
212
|
+
_add_command(sub, "setup", "one-time Ghostty setup (Linux: lets split open panes)")
|
|
213
|
+
|
|
214
|
+
route = _add_command(sub, "route", "JSON: a path's repository and its sessions")
|
|
215
|
+
route.add_argument("path")
|
|
216
|
+
|
|
217
|
+
hook = _add_command(sub, "hook", "entry point for Claude Code hooks")
|
|
218
|
+
hook.add_argument("event", choices=["session-start", "session-end", "stop"])
|
|
219
|
+
|
|
220
|
+
auto_name = _add_command(
|
|
221
|
+
sub,
|
|
222
|
+
"auto-name",
|
|
223
|
+
"the name this session gets (its repository's), empty if it has one",
|
|
224
|
+
"auto_name",
|
|
225
|
+
)
|
|
226
|
+
auto_name.add_argument("--directory", help="the session's directory")
|
|
227
|
+
|
|
228
|
+
exec_run = _add_command(
|
|
229
|
+
sub, "exec-run", "run a tab's recorded command (what tabs run)", "exec_run"
|
|
230
|
+
)
|
|
231
|
+
exec_run.add_argument("run_id")
|
|
232
|
+
|
|
233
|
+
_add_command(
|
|
234
|
+
sub,
|
|
235
|
+
"settle",
|
|
236
|
+
"record the tabs closed in a running Ghostty, after a short delay (run when "
|
|
237
|
+
"a tab ends)",
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
snapshot = _add_command(
|
|
241
|
+
sub, "snapshot", "JSON: record where each session's tab is (run by the hooks)"
|
|
242
|
+
)
|
|
243
|
+
snapshot.add_argument(
|
|
244
|
+
"--show", action="store_true", help="print the last snapshot, take none"
|
|
245
|
+
)
|
|
246
|
+
return parser
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
250
|
+
args = build_parser().parse_args(argv)
|
|
251
|
+
module, _, function = args.handler.partition(":")
|
|
252
|
+
handler = cast("Handler", getattr(importlib.import_module(module), function))
|
|
253
|
+
return handler(args)
|
|
File without changes
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Resolve a session or a command tab given on the command line by name or id."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from cc_ghostty import repos, runs, sessions
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def as_session(record: runs.RunRecord) -> sessions.Session:
|
|
9
|
+
"""A command tab, seen as a session by the Ghostty backends."""
|
|
10
|
+
root = repos.repo_root(record.cwd)
|
|
11
|
+
return sessions.Session(
|
|
12
|
+
session_id=record.key,
|
|
13
|
+
pid=record.pid or 0,
|
|
14
|
+
cwd=record.cwd,
|
|
15
|
+
name=f"{runs.TITLE_PREFIX.strip()} {record.name}",
|
|
16
|
+
account=None,
|
|
17
|
+
config_dir=None,
|
|
18
|
+
repo=str(root) if root else None,
|
|
19
|
+
ghostty_surface_id=record.ghostty_surface_id,
|
|
20
|
+
in_ghostty=True,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def one_session(query: str) -> sessions.Session | None:
|
|
25
|
+
matches = sessions.find(query)
|
|
26
|
+
if not matches:
|
|
27
|
+
matches = [as_session(r) for r in runs.find(query)]
|
|
28
|
+
if len(matches) == 1:
|
|
29
|
+
return matches[0]
|
|
30
|
+
if not matches:
|
|
31
|
+
print(
|
|
32
|
+
f"cc-ghostty: no running session or tab named or with id '{query}'",
|
|
33
|
+
file=sys.stderr,
|
|
34
|
+
)
|
|
35
|
+
else:
|
|
36
|
+
print(f"cc-ghostty: '{query}' matches several sessions:", file=sys.stderr)
|
|
37
|
+
for s in matches:
|
|
38
|
+
print(f" {s.session_id} {s.name or '-'} {s.cwd}", file=sys.stderr)
|
|
39
|
+
return None
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Interrupted (or closed) sessions and tabs picked by the options `list` and
|
|
2
|
+
`restore` share."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import time
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
from cc_ghostty import restore, runs
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def candidates(args: argparse.Namespace) -> list[restore.Candidate]:
|
|
12
|
+
since = restore.default_since(args.since)
|
|
13
|
+
# No shutdown race left to wait out: Ghostty outlived whatever ended before now.
|
|
14
|
+
runs.settle_closed_tabs(min_age=0)
|
|
15
|
+
if args.closed:
|
|
16
|
+
found = restore.merge(
|
|
17
|
+
restore.from_runs(since, closed=True),
|
|
18
|
+
restore.from_registry(since, closed=True),
|
|
19
|
+
)
|
|
20
|
+
elif args.scan:
|
|
21
|
+
found = restore.merge(
|
|
22
|
+
restore.from_runs(since),
|
|
23
|
+
restore.from_transcripts(since, restore.scan_config_dirs(args.config_dir)),
|
|
24
|
+
)
|
|
25
|
+
else:
|
|
26
|
+
found = restore.merge(restore.from_runs(since), restore.from_registry(since))
|
|
27
|
+
found = restore.filter_account(found, args.account)
|
|
28
|
+
if not args.all:
|
|
29
|
+
found = restore.last_batch(found)
|
|
30
|
+
return sorted(found, key=lambda c: c.interrupted_at)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def summaries(
|
|
34
|
+
args: argparse.Namespace, candidates: list[restore.Candidate]
|
|
35
|
+
) -> dict[str, restore.Summary] | None:
|
|
36
|
+
"""Per session id, as `--summary` asks, else when they stopped long ago."""
|
|
37
|
+
if args.summary is False or not candidates:
|
|
38
|
+
return None
|
|
39
|
+
found = {c.session_id: restore.summary(c) for c in candidates}
|
|
40
|
+
return found if args.summary or restore.long_idle(found.values()) else None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def format_time(timestamp: float) -> str:
|
|
44
|
+
moment = datetime.fromtimestamp(timestamp)
|
|
45
|
+
fmt = "%H:%M" if moment.date() == datetime.now().date() else "%Y-%m-%d %H:%M"
|
|
46
|
+
return moment.strftime(fmt)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _ago(timestamp: float) -> str:
|
|
50
|
+
minutes = max(0, int(time.time() - timestamp) // 60)
|
|
51
|
+
if minutes < 60:
|
|
52
|
+
return f"{minutes} min ago"
|
|
53
|
+
hours = minutes // 60
|
|
54
|
+
return f"{hours} h ago" if hours < 48 else f"{hours // 24} days ago"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _excerpt(text: str, limit: int = 240) -> str:
|
|
58
|
+
flat = " ".join(text.split())
|
|
59
|
+
return flat if len(flat) <= limit else flat[: limit - 1] + "…"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def summary_lines(summary: restore.Summary) -> list[str]:
|
|
63
|
+
lines = [
|
|
64
|
+
f"last active: {format_time(summary.last_active)} ({_ago(summary.last_active)})"
|
|
65
|
+
]
|
|
66
|
+
if summary.last_prompt:
|
|
67
|
+
lines.append(f"asked: {_excerpt(summary.last_prompt)}")
|
|
68
|
+
if summary.last_reply:
|
|
69
|
+
lines.append(f"replied: {_excerpt(summary.last_reply)}")
|
|
70
|
+
return lines
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from cc_ghostty import delegate, procs, repos, sessions
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def is_default_name(name: str, cwd: str) -> bool:
|
|
10
|
+
"""Whether `name` is the one Claude Code gives a session by itself: its
|
|
11
|
+
directory's name and a short hex suffix (`myapp-03`, `myapp-4c`)."""
|
|
12
|
+
return re.fullmatch(rf"{re.escape(Path(cwd).name)}-[0-9a-f]+", name) is not None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def suggested_name(cwd: str | None = None) -> str | None:
|
|
16
|
+
"""The name for this Claude session: its repository's (else its directory's),
|
|
17
|
+
numbered when taken; None when it already has a name of its own (not Claude
|
|
18
|
+
Code's default one)."""
|
|
19
|
+
if os.environ.get("CC_GHOSTTY_AUTO_NAME") == "0":
|
|
20
|
+
return None
|
|
21
|
+
own_pid = procs.find_claude_pid()
|
|
22
|
+
live = sessions.live()
|
|
23
|
+
own = next((s for s in live if s.pid == own_pid), None)
|
|
24
|
+
if own is not None and own.name and not is_default_name(own.name, own.cwd):
|
|
25
|
+
return None
|
|
26
|
+
directory = Path(cwd or (own.cwd if own else "") or os.getcwd())
|
|
27
|
+
root = repos.repo_root(directory) or directory.resolve()
|
|
28
|
+
if not root.name:
|
|
29
|
+
return None
|
|
30
|
+
taken = (s.name for s in live if s.pid != own_pid)
|
|
31
|
+
return delegate.unique_session_name(root.name, taken)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run(args: argparse.Namespace) -> int:
|
|
35
|
+
name = suggested_name(args.directory)
|
|
36
|
+
if name:
|
|
37
|
+
print(name)
|
|
38
|
+
return 0
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import signal
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from cc_ghostty import ghostty, procs, registry, runs
|
|
7
|
+
from cc_ghostty.commands._pick import one_session
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _mark_closed(session_id: str, cwd: str, config_dir: str | None, pid: int) -> None:
|
|
11
|
+
"""Record a deliberate end, so restore leaves it closed: in the hooks' registry
|
|
12
|
+
and in the record of the tab cc-ghostty opened for it."""
|
|
13
|
+
for record in runs.all_records():
|
|
14
|
+
if record.key == session_id and record.running:
|
|
15
|
+
runs.mark_closed(record)
|
|
16
|
+
if not session_id.startswith("run:"):
|
|
17
|
+
registry.mark_closed(session_id, cwd, config_dir, pid)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def run(args: argparse.Namespace) -> int:
|
|
21
|
+
session = one_session(args.session)
|
|
22
|
+
if session is None:
|
|
23
|
+
return 1
|
|
24
|
+
if session.pid == procs.find_claude_pid():
|
|
25
|
+
print("cc-ghostty: refusing to close the session running this command.")
|
|
26
|
+
return 1
|
|
27
|
+
|
|
28
|
+
_mark_closed(session.session_id, session.cwd, session.config_dir, session.pid)
|
|
29
|
+
label = session.name or session.session_id
|
|
30
|
+
if not args.keep_shell and ghostty.backend().close(session):
|
|
31
|
+
print(f"Closed the Ghostty terminal of '{label}'.")
|
|
32
|
+
return 0
|
|
33
|
+
os.kill(session.pid, signal.SIGTERM)
|
|
34
|
+
if args.keep_shell:
|
|
35
|
+
print(f"Stopped '{label}'; its terminal stays open.")
|
|
36
|
+
else:
|
|
37
|
+
print(f"Stopped '{label}' (no Ghostty terminal found).", file=sys.stderr)
|
|
38
|
+
return 0
|