csm-cli 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.
csm_cli/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """csm_cli — Claude Code 会话管理器(csm 命令)。
2
+
3
+ TUI / Web / 表格三种前端,详见 README。版本号单一来源在本文件,
4
+ pyproject.toml 通过 hatch dynamic version 读取。
5
+ """
6
+
7
+ __version__ = "0.1.0"
csm_cli/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """python -m csm_cli 支持(serve daemon 也用它派生子进程)。"""
2
+
3
+ import sys
4
+
5
+ from csm_cli.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
csm_cli/cli.py ADDED
@@ -0,0 +1,306 @@
1
+ #!/usr/bin/env python3
2
+ """csm — Claude Code 会话管理器。
3
+
4
+ 列出/搜索全部项目的 Claude 会话,回车直接 resume。
5
+
6
+ 用法:
7
+ csm 交互式 TUI(默认)
8
+ csm --list 非交互表格
9
+ csm --list --json JSON 输出
10
+ csm --project voicemouse 按项目路径过滤
11
+ csm --new [PATH] 在 PATH(默认当前目录)起新会话
12
+ csm --no-cd resume 时不切到原项目目录
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ import shutil
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ from csm_cli import scanner
25
+
26
+ from csm_cli import __version__ as VERSION
27
+
28
+ LIGHT_TOP = 40 # 初始轻扫条数(mtime 序),其余交互时懒扫
29
+
30
+
31
+ def _time_text(mtime: float) -> str:
32
+ """优先用 csm_fmt.rel_time(用户贡献的格式);未实现时降级 strftime。"""
33
+ try:
34
+ from csm_cli import fmt as csm_fmt
35
+
36
+ return csm_fmt.rel_time(mtime)
37
+ except NotImplementedError:
38
+ import time
39
+
40
+ return time.strftime("%m-%d %H:%M", time.localtime(mtime))
41
+
42
+
43
+ def _sid_text(sid: str, width: int) -> str:
44
+ from csm_cli import fmt as csm_fmt
45
+
46
+ return csm_fmt.truncate_cjk(sid, width) if width < 36 else sid
47
+
48
+
49
+ def cmd_list(args, entries: list[scanner.SessionEntry]) -> int:
50
+ if args.full_scan:
51
+ for e in entries:
52
+ scanner.full_scan(e)
53
+ scanner.worktree_scan(e) # full 兜底出 cwd 的条目在此补 worktree 归属
54
+ missing = [e for e in entries if e.first_input is None]
55
+ if missing:
56
+ history = scanner.load_history_index()
57
+ for e in missing:
58
+ e.first_input = scanner.first_input_from_history(e.session_id, history)
59
+
60
+ if args.json:
61
+ payload = [
62
+ {
63
+ "session_id": e.session_id,
64
+ "title": e.title,
65
+ "first_input": e.first_input,
66
+ "project_path": e.project_path,
67
+ "mtime": e.mtime,
68
+ "msg_count": e.msg_count,
69
+ "assistant_count": e.assistant_count,
70
+ "running_status": e.running_status,
71
+ "session_name": e.session_name,
72
+ "entrypoint": e.entrypoint,
73
+ "tty": e.tty,
74
+ "is_current": e.is_current,
75
+ "star": e.star,
76
+ "tags": e.tags,
77
+ "wt_name": e.wt_name,
78
+ "wt_repo": e.wt_repo,
79
+ "wt_branch": e.wt_branch,
80
+ "wt_ahead": e.wt_ahead,
81
+ "size": e.size,
82
+ }
83
+ for e in entries
84
+ ]
85
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
86
+ return 0
87
+
88
+ from csm_cli import fmt as csm_fmt
89
+ from rich.console import Console
90
+ from rich.markup import escape
91
+ from rich.table import Table
92
+
93
+ console = Console(no_color=args.no_color or os.environ.get("NO_COLOR"))
94
+ width = console.width
95
+ sid_w = 36
96
+ fixed_w = 5 + 2 + 5 + 2 + 3 + 2 + sid_w # 活跃/状态/轮/分隔/ID
97
+ rest = max(width - fixed_w - 2, 20)
98
+ title_w = int(rest * 0.6)
99
+ proj_w = rest - title_w
100
+
101
+ table = Table(box=None, show_header=True, header_style="bold dim", pad_edge=False)
102
+ table.add_column("活跃", justify="right", no_wrap=True)
103
+ table.add_column("状态", no_wrap=True)
104
+ table.add_column("标题 / 首条输入", no_wrap=True)
105
+ table.add_column("项目", no_wrap=True)
106
+ table.add_column("轮", justify="right", no_wrap=True)
107
+ table.add_column("Session ID", no_wrap=True)
108
+
109
+ for e in entries:
110
+ if e.running_status == "busy":
111
+ status = "[green]●busy[/green]"
112
+ elif e.running_status:
113
+ status = "[yellow]●idle[/yellow]"
114
+ else:
115
+ status = " "
116
+ turns = str(e.msg_count) if e.msg_count is not None else "·"
117
+ if e.title:
118
+ title = csm_fmt.truncate_cjk(escape(e.title), title_w)
119
+ else:
120
+ fi = e.first_input or "(无用户输入)"
121
+ title = f"[dim]{csm_fmt.truncate_cjk(escape(fi), title_w)}[/dim]"
122
+ prefix = "[yellow]★ [/yellow]" if e.star == 2 else "[yellow]⭐ [/yellow]" if e.star == 1 else ""
123
+ title = prefix + title
124
+ if e.wt_name:
125
+ proj = f"{e.wt_repo or '?'}/{e.wt_name}" # worktree 会话:主仓库/worktree 名
126
+ if e.wt_branch:
127
+ proj += f" ⎇{e.wt_branch}"
128
+ else:
129
+ proj = csm_fmt.shorten_path(e.project_path or "?", proj_w)
130
+ table.add_row(
131
+ _time_text(e.mtime),
132
+ status,
133
+ title,
134
+ escape(proj),
135
+ turns,
136
+ e.session_id,
137
+ )
138
+
139
+ console.print(table)
140
+ return 0
141
+
142
+
143
+ def _resume_conflict(entry: scanner.SessionEntry,
144
+ registry: dict[str, scanner.RunningInfo],
145
+ current_tty: str | None) -> str | None:
146
+ """目标会话活在本终端之外 → 返回警告文案;安全返回 None。
147
+
148
+ registry 里的记录已过 pid 存活 + command + procStart 三重判活,存在即真活。
149
+ tty 未知也警告(无法证明在本终端,宁可误拦不可交叉写入);registry 的
150
+ ps 表为空(快照失败)时同样拿不到 tty,走同一分支。
151
+ """
152
+ info = registry.get(entry.session_id)
153
+ if info is None:
154
+ return None
155
+ if current_tty and info.tty and info.tty == current_tty:
156
+ return None # 本终端在跑(csm 自身被嵌套调用的场景),不拦
157
+ where = f"终端 {info.tty}" if info.tty else "另一终端(tty 未知)"
158
+ state = info.status or "运行中"
159
+ return (f"该会话正在{where}运行({state},pid {info.pid})。"
160
+ "两处同时恢复同一会话会导致会话文件交叉写入,内容可能错乱。")
161
+
162
+
163
+ def resume(entry: scanner.SessionEntry, no_cd: bool = False) -> None:
164
+ """接管当前进程去跑 claude --resume。不返回。"""
165
+ if shutil.which("claude") is None:
166
+ print("错误: claude CLI 不在 PATH 中", file=sys.stderr)
167
+ sys.exit(2)
168
+ warn = _resume_conflict(entry, scanner.load_running_registry(),
169
+ scanner.current_terminal_tty())
170
+ if warn:
171
+ print(f"\n⚠ {warn}")
172
+ try:
173
+ ans = input("仍要在此终端恢复? [y/N] ")
174
+ except EOFError:
175
+ ans = ""
176
+ if ans.strip().lower() not in ("y", "yes"):
177
+ sys.exit(130) # 与取消一致
178
+ if not no_cd and entry.project_path:
179
+ try:
180
+ os.chdir(entry.project_path)
181
+ except OSError:
182
+ print(
183
+ f"提示: 原项目目录已不存在: {entry.project_path},在当前目录恢复",
184
+ file=sys.stderr,
185
+ )
186
+ os.execvp("claude", ["claude", "--resume", entry.session_id])
187
+
188
+
189
+ def resolve_new_target(path: str) -> Path | None:
190
+ """--new 的目标目录解析:展开 ~;不存在或不是目录返回 None(可测纯函数)。"""
191
+ target = Path(path).expanduser()
192
+ return target if target.is_dir() else None
193
+
194
+
195
+ def cmd_new(path: str) -> int:
196
+ """cd 到目标目录起新会话;execvp 接管进程(失败返回 2)。"""
197
+ target = resolve_new_target(path)
198
+ if target is None:
199
+ print(f"错误: 目录不存在: {path}", file=sys.stderr)
200
+ return 2
201
+ if shutil.which("claude") is None:
202
+ print("错误: claude CLI 不在 PATH 中", file=sys.stderr)
203
+ return 2
204
+ os.chdir(target)
205
+ os.execvp("claude", ["claude"])
206
+ return 0 # 仅 execvp 失败时到达
207
+
208
+
209
+ def build_argparser() -> argparse.ArgumentParser:
210
+ p = argparse.ArgumentParser(
211
+ prog="csm", description="Claude Code 会话管理器", formatter_class=argparse.RawDescriptionHelpFormatter
212
+ )
213
+ p.add_argument("--limit", type=int, default=0, metavar="N", help="最多列出 N 条(0=全部)")
214
+ p.add_argument("--new", nargs="?", const=".", metavar="PATH",
215
+ help="在 PATH(默认当前目录)启动新 Claude 会话,不进列表界面")
216
+ p.add_argument("--project", metavar="PATTERN", help="项目路径子串过滤(大小写不敏感)")
217
+ p.add_argument("--list", action="store_true", help="非交互表格输出")
218
+ p.add_argument("--json", action="store_true", help="JSON 输出(隐含 --list 语义)")
219
+ p.add_argument("--full-scan", action="store_true", help="--list 时同步全扫(消息数完整)")
220
+ p.add_argument("--web", action="store_true", help="启动本地 Web 界面(127.0.0.1,浏览器自动打开)")
221
+ p.add_argument("--port", type=int, default=8737, metavar="N", help="Web 端口(默认 8737,占用则顺延)")
222
+ p.add_argument("--no-open", action="store_true", help="--web 时不自动打开浏览器")
223
+ p.add_argument("--head-bytes", type=int, default=scanner.DEFAULT_HEAD_BYTES, help=argparse.SUPPRESS)
224
+ p.add_argument("--tail-bytes", type=int, default=scanner.DEFAULT_TAIL_BYTES, help=argparse.SUPPRESS)
225
+ p.add_argument("--no-cd", action="store_true", help="resume 时不切换到原项目目录")
226
+ p.add_argument("--no-color", action="store_true", help="禁用颜色")
227
+ p.add_argument("--version", action="version", version=f"csm {VERSION}")
228
+
229
+ sp = p.add_subparsers(dest="serve_cmd", metavar="serve")
230
+ srv = sp.add_parser("serve", help="Web 服务:前台运行或 daemon 启停",
231
+ description="`csm serve` 前台运行;start/stop/status/restart 守护管理;"
232
+ "install-launchd 开机自启(macOS)")
233
+ srv.add_argument("action", nargs="?", default="foreground",
234
+ choices=["foreground", "start", "stop", "status", "restart",
235
+ "install-launchd", "uninstall-launchd"],
236
+ help="start=后台启动 stop=停止 status=状态 restart=重启 "
237
+ "install-launchd/uninstall-launchd=开机自启管理(默认前台运行)")
238
+ srv.add_argument("--port", type=int, default=8737, metavar="N",
239
+ help="端口(默认 8737;daemon 模式固定不顺延)")
240
+ srv.add_argument("--open", action="store_true", help="start 成功后打开浏览器")
241
+ srv.add_argument("--no-open", action="store_true", help=argparse.SUPPRESS) # daemon 子进程透传
242
+ srv.add_argument("--project", metavar="PATTERN", help="项目路径子串过滤")
243
+ srv.add_argument("--limit", type=int, default=0, metavar="N", help="最多展示 N 条")
244
+ # 内部参数(daemon 派生/launchd 用,help 隐藏)
245
+ srv.add_argument("--foreground", action="store_true", help=argparse.SUPPRESS)
246
+ srv.add_argument("--fixed-port", action="store_true", help=argparse.SUPPRESS)
247
+ srv.add_argument("--no-pidfile", action="store_true", help=argparse.SUPPRESS)
248
+ return p
249
+
250
+
251
+ def main(argv: list[str] | None = None) -> int:
252
+ args = build_argparser().parse_args(argv)
253
+
254
+ if args.serve_cmd == "serve": # serve 分支:仅前台需要扫描存量
255
+ if args.action == "foreground":
256
+ args.web = True # 与 `csm --web` 走同一路径(下方处理)
257
+ else:
258
+ from csm_cli import serve as serve_mod
259
+
260
+ return {
261
+ "start": lambda: serve_mod.cmd_start(args.port, args.open, args.project, args.limit),
262
+ "stop": serve_mod.cmd_stop,
263
+ "status": serve_mod.cmd_status,
264
+ "restart": lambda: serve_mod.cmd_restart(args.port, args.open, args.project, args.limit),
265
+ "install-launchd": lambda: serve_mod.cmd_install_launchd(args.port),
266
+ "uninstall-launchd": serve_mod.cmd_uninstall_launchd,
267
+ }[args.action]()
268
+
269
+ if args.new: # 发射新会话:不需要扫描存量,最先处理
270
+ return cmd_new(args.new)
271
+
272
+ entries = scanner.discover_sessions(limit=args.limit, project_filter=args.project)
273
+ if not entries:
274
+ root = scanner.CONFIG_ROOT / "projects"
275
+ print(f"未发现任何 Claude 会话(查找目录: {root})", file=sys.stderr)
276
+ return 2
277
+
278
+ scanner.apply_registry(entries, scanner.load_running_registry(),
279
+ current_tty=scanner.current_terminal_tty())
280
+ scanner.apply_favorites(entries, scanner.load_favorites())
281
+ scanner.sort_pinned(entries)
282
+ for e in entries[:LIGHT_TOP]:
283
+ scanner.light_scan(e)
284
+ scanner.worktree_scan(e) # light 拿到 cwd 即可判定(纯文件读,两次小 read)
285
+
286
+ if args.web: # --web 优先于 --list/管道降级:管道里跑 csm --web 也应起服务
287
+ from csm_cli import web as csm_web # 惰性 import:非 web 路径零开销
288
+
289
+ return csm_web.serve(args, entries)
290
+
291
+ if args.list or args.json or not sys.stdout.isatty():
292
+ # 非 TTY(管道)自动降级为 --list,便于 csm | grep
293
+ return cmd_list(args, entries)
294
+
295
+ # ---- 交互模式 ----
296
+ from csm_cli import ui as csm_ui # 惰性 import:--list 路径不加载 prompt_toolkit 界面
297
+
298
+ picked = csm_ui.run(entries, args)
299
+ if picked is None:
300
+ return 130 # 用户取消
301
+ resume(picked, no_cd=args.no_cd)
302
+ return 0 # 仅在 execvp 失败时到达(execvp 成功不返回)
303
+
304
+
305
+ if __name__ == "__main__":
306
+ sys.exit(main())
csm_cli/fmt.py ADDED
@@ -0,0 +1,115 @@
1
+ """csm_fmt — 纯函数小工具:相对时间、路径缩写、CJK 宽度感知的截断/填充、模糊匹配评分。
2
+
3
+ 本模块不含 I/O,所有函数均为纯函数,便于单测。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import re
10
+ import time
11
+
12
+ from prompt_toolkit.utils import get_cwidth
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # CJK 宽度感知的截断与填充
16
+ # ---------------------------------------------------------------------------
17
+
18
+
19
+ def display_width(text: str) -> int:
20
+ """字符串在终端里的显示宽度(中文/全角=2,ASCII=1)。"""
21
+ return sum(get_cwidth(ch) for ch in text)
22
+
23
+
24
+ def truncate_cjk(text: str, max_width: int, placeholder: str = "…") -> str:
25
+ """按显示宽度截断字符串,超宽时以 placeholder 结尾。
26
+
27
+ max_width 是显示宽度而非字符数:一个中文字符占 2 列。
28
+ placeholder 默认 "…"(宽度 1)。
29
+ """
30
+ if display_width(text) <= max_width:
31
+ return text
32
+ keep = max_width - display_width(placeholder)
33
+ out: list[str] = []
34
+ used = 0
35
+ for ch in text:
36
+ w = get_cwidth(ch)
37
+ if used + w > keep:
38
+ break
39
+ out.append(ch)
40
+ used += w
41
+ return "".join(out) + placeholder
42
+
43
+
44
+ def pad_to_width(text: str, width: int) -> str:
45
+ """将文本用空格填充到指定显示宽度(宽度感知,中文按 2 列计)。"""
46
+ gap = width - display_width(text)
47
+ return text + " " * max(gap, 0)
48
+
49
+
50
+ def shorten_path(path: str, max_width: int) -> str:
51
+ """把 $HOME 前缀替换为 ~,仍超宽则从中间截断保留首尾(保尾部更利于区分项目)。"""
52
+ home = os.path.expanduser("~")
53
+ if path.startswith(home):
54
+ path = "~" + path[len(home):]
55
+ if display_width(path) <= max_width:
56
+ return path
57
+ if max_width <= 1:
58
+ return truncate_cjk(path, max_width, placeholder="")
59
+ # 保留尾部(项目名往往在末段),头部用 … 代替
60
+ tail = path
61
+ for _ in range(len(path)):
62
+ if display_width("…" + tail) <= max_width:
63
+ break
64
+ tail = tail[1:]
65
+ return "…" + tail
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # 相对时间
70
+ # ---------------------------------------------------------------------------
71
+
72
+
73
+ def rel_time(mtime: float, now: float | None = None) -> str:
74
+ """把时间戳转为适合一列宽 ~5 字符的相对时间文本。
75
+
76
+ 用于会话列表的「最后活跃」列。
77
+ """
78
+ # TODO(user): 在此实现相对时间格式化规则(见下方说明)
79
+ raise NotImplementedError("rel_time: 等待实现")
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # 模糊匹配评分
84
+ # ---------------------------------------------------------------------------
85
+
86
+
87
+ def fuzzy_score(query: str, target: str) -> float | None:
88
+ """对单个字段做模糊匹配打分;不匹配返回 None(不是 0!)。
89
+
90
+ 约定:query 与 target 均已 lowercase 后传入。
91
+ 返回值越大越相关。调用方(csm_ui)会对多个字段加权取最大值。
92
+ """
93
+ # TODO(user): 在此实现打分策略(见下方说明)
94
+ raise NotImplementedError("fuzzy_score: 等待实现")
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # 搜索词解析(#tag 语法,TUI 与 Web 共用)
99
+ # ---------------------------------------------------------------------------
100
+
101
+
102
+ def parse_query(text: str) -> tuple[list[str], list[str]]:
103
+ """把搜索串拆成 (plain_tokens, tag_tokens)。
104
+
105
+ 以 # 开头的 token 视为标签(去掉 #、转小写,多 tag 为 AND);
106
+ 单独的 "#" 归 plain。例:'#工作 claude' → (['claude'], ['工作'])。
107
+ """
108
+ plain: list[str] = []
109
+ tags: list[str] = []
110
+ for tok in text.split():
111
+ if tok.startswith("#") and len(tok) > 1:
112
+ tags.append(tok[1:].lower())
113
+ else:
114
+ plain.append(tok)
115
+ return plain, tags