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 +7 -0
- csm_cli/__main__.py +8 -0
- csm_cli/cli.py +306 -0
- csm_cli/fmt.py +115 -0
- csm_cli/scanner.py +999 -0
- csm_cli/serve.py +305 -0
- csm_cli/ui.py +727 -0
- csm_cli/web.html +955 -0
- csm_cli/web.py +396 -0
- csm_cli-0.1.0.dist-info/METADATA +211 -0
- csm_cli-0.1.0.dist-info/RECORD +14 -0
- csm_cli-0.1.0.dist-info/WHEEL +4 -0
- csm_cli-0.1.0.dist-info/entry_points.txt +2 -0
- csm_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
csm_cli/web.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""csm_web — 本地 Web 界面:ThreadingHTTPServer + 单文件前端。
|
|
2
|
+
|
|
3
|
+
只在 127.0.0.1 监听;会话列表走增量刷新(stat 级 diff,mtime/size 未变的
|
|
4
|
+
条目复用已扫描成果,零重复 IO);消息预览复用 csm_scanner.read_session_messages
|
|
5
|
+
的模块级缓存。线程模型:
|
|
6
|
+
- 每个 HTTP 请求一个线程(ThreadingHTTPServer)
|
|
7
|
+
- SessionStore 后台 daemon 线程持续补 full_scan
|
|
8
|
+
- 共享状态:SessionStore._lock(entries/registry)与 scanner._MSG_CACHE_LOCK
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import webbrowser
|
|
20
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
21
|
+
from importlib.resources import files
|
|
22
|
+
from urllib.parse import parse_qs, urlparse
|
|
23
|
+
|
|
24
|
+
from csm_cli import scanner
|
|
25
|
+
from csm_cli.scanner import SessionEntry
|
|
26
|
+
|
|
27
|
+
VERBOSE = False # True 时打印每请求日志(调试用)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
# 会话存储:增量刷新 + registry 节流 + 后台全扫
|
|
32
|
+
# ---------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SessionStore:
|
|
36
|
+
"""entries 缓存;所有字段一把锁保护。"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, entries: list[SessionEntry], limit: int = 0, project: str | None = None,
|
|
39
|
+
current_tty: str | None = None) -> None:
|
|
40
|
+
self._lock = threading.Lock()
|
|
41
|
+
self._by_sid: dict[str, SessionEntry] = {e.session_id: e for e in entries}
|
|
42
|
+
self._limit = limit
|
|
43
|
+
self._project = project
|
|
44
|
+
self._current_tty = current_tty # serve() 启动时算一次
|
|
45
|
+
self._reg: dict[str, scanner.RunningInfo] = {}
|
|
46
|
+
self._reg_ts = 0.0
|
|
47
|
+
threading.Thread(target=self._fullscan_loop, daemon=True).start()
|
|
48
|
+
|
|
49
|
+
def refresh(self) -> list[SessionEntry]:
|
|
50
|
+
"""discover(仅 stat)+ diff 合并;每次 GET /api/sessions 调用,毫秒级。"""
|
|
51
|
+
fresh = scanner.discover_sessions(limit=self._limit, project_filter=self._project)
|
|
52
|
+
now = time.time()
|
|
53
|
+
if now - self._reg_ts > 3.0: # registry 读几十个小 json,3s 节流
|
|
54
|
+
self._reg = scanner.load_running_registry()
|
|
55
|
+
self._reg_ts = now
|
|
56
|
+
with self._lock:
|
|
57
|
+
for ne in fresh:
|
|
58
|
+
oe = self._by_sid.get(ne.session_id)
|
|
59
|
+
if oe is not None and (ne.mtime, ne.size) == (oe.mtime, ne.size):
|
|
60
|
+
# 文件没变:新 stat 身份 + 旧扫描成果(保留 full_scan 结果)
|
|
61
|
+
ne.__dict__.update(oe.__dict__)
|
|
62
|
+
else:
|
|
63
|
+
scanner.light_scan(ne) # 新文件或文件变了 → 重轻扫
|
|
64
|
+
scanner.worktree_scan(ne)
|
|
65
|
+
self._by_sid[ne.session_id] = ne
|
|
66
|
+
scanner.apply_registry(fresh, self._reg, current_tty=self._current_tty)
|
|
67
|
+
scanner.apply_favorites(fresh, scanner.load_favorites())
|
|
68
|
+
scanner.sort_pinned(fresh) # 响应数组即置顶序(前端 reconcileOrder 依赖)
|
|
69
|
+
return fresh
|
|
70
|
+
|
|
71
|
+
def get(self, sid: str) -> SessionEntry | None:
|
|
72
|
+
with self._lock:
|
|
73
|
+
return self._by_sid.get(sid)
|
|
74
|
+
|
|
75
|
+
def _fullscan_loop(self) -> None:
|
|
76
|
+
"""daemon:持续找 not full_scanned 的条目补 msg_count,全扫完 sleep 等新会话。"""
|
|
77
|
+
while True:
|
|
78
|
+
with self._lock:
|
|
79
|
+
todo = next((e for e in self._by_sid.values() if not e.full_scanned), None)
|
|
80
|
+
if todo is None:
|
|
81
|
+
# full 之外还欠 worktree ahead(subprocess)的,一次最多挑一个
|
|
82
|
+
todo = next((e for e in self._by_sid.values()
|
|
83
|
+
if e.wt_branch and not e.wt_deep_scanned), None)
|
|
84
|
+
todo_is_ahead = todo is not None
|
|
85
|
+
else:
|
|
86
|
+
todo_is_ahead = False
|
|
87
|
+
if todo is None:
|
|
88
|
+
time.sleep(5.0)
|
|
89
|
+
elif todo_is_ahead:
|
|
90
|
+
scanner.worktree_ahead(todo) # 结果经 rev(wt_ahead)推给前端
|
|
91
|
+
else:
|
|
92
|
+
scanner.full_scan(todo)
|
|
93
|
+
scanner.worktree_scan(todo) # full 兜底出 cwd 的条目补检(wt_branch 供下轮 ahead)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---------------------------------------------------------------------------
|
|
97
|
+
# 序列化
|
|
98
|
+
# ---------------------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def entry_payload(e: SessionEntry) -> dict:
|
|
102
|
+
"""与 csm.py --json 字段一致,额外加 rev(前端 diff 的每行版本号)。
|
|
103
|
+
|
|
104
|
+
rev 纳入 star/tags/wt_ahead:星标或 ahead 补全(后台 subprocess)但
|
|
105
|
+
mtime 未变的行也触发前端 updateRow。
|
|
106
|
+
"""
|
|
107
|
+
return {
|
|
108
|
+
"session_id": e.session_id,
|
|
109
|
+
"title": e.title,
|
|
110
|
+
"first_input": e.first_input,
|
|
111
|
+
"project_path": e.project_path,
|
|
112
|
+
"mtime": e.mtime,
|
|
113
|
+
"size": e.size,
|
|
114
|
+
"msg_count": e.msg_count,
|
|
115
|
+
"assistant_count": e.assistant_count,
|
|
116
|
+
"last_timestamp": e.last_timestamp,
|
|
117
|
+
"running_status": e.running_status,
|
|
118
|
+
"session_name": e.session_name,
|
|
119
|
+
"entrypoint": e.entrypoint,
|
|
120
|
+
"tty": e.tty,
|
|
121
|
+
"is_current": e.is_current,
|
|
122
|
+
"star": e.star,
|
|
123
|
+
"tags": list(e.tags),
|
|
124
|
+
"wt_name": e.wt_name,
|
|
125
|
+
"wt_repo": e.wt_repo,
|
|
126
|
+
"wt_branch": e.wt_branch,
|
|
127
|
+
"wt_ahead": e.wt_ahead,
|
|
128
|
+
"rev": f"{e.mtime}:{e.size}:{e.star}:{','.join(e.tags)}:{e.wt_ahead}",
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# diff 工具 input 的序列化白名单(其余键不透传;字符串截断对齐 scanner.INPUT_TEXT_CAP)
|
|
133
|
+
_TOOL_INPUT_KEYS = ("old_string", "new_string", "content", "edits",
|
|
134
|
+
"file_path", "notebook_path")
|
|
135
|
+
_TOOL_INPUT_STR_CAP = 20_000
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _tool_input_payload(inp: dict) -> dict:
|
|
139
|
+
out: dict = {}
|
|
140
|
+
for k in _TOOL_INPUT_KEYS:
|
|
141
|
+
v = inp.get(k)
|
|
142
|
+
if isinstance(v, str):
|
|
143
|
+
out[k] = v[:_TOOL_INPUT_STR_CAP]
|
|
144
|
+
elif isinstance(v, list): # MultiEdit 的 edits: [{old_string,new_string},...]
|
|
145
|
+
out[k] = [
|
|
146
|
+
{kk: (vv[:_TOOL_INPUT_STR_CAP] if isinstance(vv, str) else vv)
|
|
147
|
+
for kk, vv in item.items() if isinstance(item, dict)}
|
|
148
|
+
for item in v
|
|
149
|
+
]
|
|
150
|
+
return out
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def message_payload(m: scanner.Message, level: str) -> dict:
|
|
154
|
+
d: dict = {
|
|
155
|
+
"order": m.order,
|
|
156
|
+
"role": m.role,
|
|
157
|
+
"kind": m.kind,
|
|
158
|
+
"ts": m.ts,
|
|
159
|
+
}
|
|
160
|
+
if m.kind in ("input", "text"):
|
|
161
|
+
text = m.text or ""
|
|
162
|
+
if level == "summary" and len(text) > 300:
|
|
163
|
+
d["text"], d["text_truncated"] = text[:300], True
|
|
164
|
+
else:
|
|
165
|
+
d["text"], d["text_truncated"] = text, False
|
|
166
|
+
else:
|
|
167
|
+
d["tool_name"] = scanner.short_tool_name(m.tool_name or "?")
|
|
168
|
+
d["tool_brief"] = m.tool_brief
|
|
169
|
+
d["tool_result_brief"] = m.tool_result_brief
|
|
170
|
+
d["tool_error"] = m.tool_error
|
|
171
|
+
# full 级别附 diff 工具的原始 input(白名单键 + 截断),前端渲染行级 diff
|
|
172
|
+
if level == "full" and m.tool_input:
|
|
173
|
+
d["tool_input"] = _tool_input_payload(m.tool_input)
|
|
174
|
+
return d
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ---------------------------------------------------------------------------
|
|
178
|
+
# HTTP Handler
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
_FAV_POST_RE = re.compile(r"^/api/favorites/([0-9a-zA-Fa-f-]+)$")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class CsmRequestHandler(BaseHTTPRequestHandler):
|
|
185
|
+
server_version = "csm-web/0.1"
|
|
186
|
+
# store / html 由 serve() 通过动态子类注入为类属性
|
|
187
|
+
store: SessionStore
|
|
188
|
+
html_bytes: bytes
|
|
189
|
+
|
|
190
|
+
def log_message(self, fmt: str, *args) -> None: # 默认每请求打 stderr,轮询会刷屏
|
|
191
|
+
if VERBOSE:
|
|
192
|
+
super().log_message(fmt, *args)
|
|
193
|
+
|
|
194
|
+
# ---- 工具 ----
|
|
195
|
+
|
|
196
|
+
def _send(self, code: int, content_type: str, body: bytes) -> None:
|
|
197
|
+
self.send_response(code)
|
|
198
|
+
self.send_header("Content-Type", content_type)
|
|
199
|
+
self.send_header("Content-Length", str(len(body)))
|
|
200
|
+
self.send_header("Cache-Control", "no-store")
|
|
201
|
+
self.end_headers()
|
|
202
|
+
self.wfile.write(body)
|
|
203
|
+
|
|
204
|
+
def _json(self, code: int, obj: dict) -> None:
|
|
205
|
+
self._send(code, "application/json; charset=utf-8",
|
|
206
|
+
json.dumps(obj, ensure_ascii=False).encode("utf-8"))
|
|
207
|
+
|
|
208
|
+
# ---- 路由 ----
|
|
209
|
+
|
|
210
|
+
def do_GET(self) -> None: # noqa: N802(BaseHTTPRequestHandler 约定)
|
|
211
|
+
try:
|
|
212
|
+
parsed = urlparse(self.path)
|
|
213
|
+
path = parsed.path
|
|
214
|
+
|
|
215
|
+
if path == "/" or path == "/index.html":
|
|
216
|
+
self._send(200, "text/html; charset=utf-8", self.html_bytes)
|
|
217
|
+
elif path == "/favicon.ico":
|
|
218
|
+
self.send_response(204)
|
|
219
|
+
self.end_headers()
|
|
220
|
+
elif path == "/api/sessions":
|
|
221
|
+
entries = self.store.refresh()
|
|
222
|
+
self._json(200, {
|
|
223
|
+
"server_time": time.time(),
|
|
224
|
+
"count": len(entries),
|
|
225
|
+
"current_tty_available": self.store._current_tty is not None,
|
|
226
|
+
"sessions": [entry_payload(e) for e in entries],
|
|
227
|
+
})
|
|
228
|
+
elif path.startswith("/api/sessions/") and path.endswith("/messages"):
|
|
229
|
+
sid = path[len("/api/sessions/"):-len("/messages")]
|
|
230
|
+
self._handle_messages(sid, parse_qs(parsed.query))
|
|
231
|
+
else:
|
|
232
|
+
self._json(404, {"error": "not found"})
|
|
233
|
+
except BrokenPipeError:
|
|
234
|
+
pass # 客户端断开(页面刷新),静默
|
|
235
|
+
except Exception as exc: # noqa: BLE001 — handler 兜底
|
|
236
|
+
self._json(500, {"error": f"internal: {exc}"})
|
|
237
|
+
|
|
238
|
+
def _handle_messages(self, sid: str, qs: dict[str, list[str]]) -> None:
|
|
239
|
+
entry = self.store.get(sid)
|
|
240
|
+
if entry is None:
|
|
241
|
+
self._json(404, {"error": "session not found"})
|
|
242
|
+
return
|
|
243
|
+
level = (qs.get("level", ["summary"])[0] or "summary").lower()
|
|
244
|
+
if level not in ("summary", "full"):
|
|
245
|
+
self._json(400, {"error": "level must be summary|full"})
|
|
246
|
+
return
|
|
247
|
+
try:
|
|
248
|
+
limit = int(qs.get("limit", ["50"])[0])
|
|
249
|
+
except ValueError:
|
|
250
|
+
limit = 50
|
|
251
|
+
limit = max(1, min(limit, 200))
|
|
252
|
+
try:
|
|
253
|
+
before_order = int(qs.get("before_order", ["-1"])[0])
|
|
254
|
+
except ValueError:
|
|
255
|
+
before_order = -1
|
|
256
|
+
|
|
257
|
+
msgs = scanner.read_session_messages(entry.file_path)
|
|
258
|
+
if msgs is None:
|
|
259
|
+
self._json(404, {"error": "会话文件不可读或已删除"})
|
|
260
|
+
return
|
|
261
|
+
|
|
262
|
+
window = [m for m in msgs if before_order < 0 or m.order < before_order]
|
|
263
|
+
has_more = len(window) > limit
|
|
264
|
+
page = window[-limit:] if has_more else window
|
|
265
|
+
self._json(200, {
|
|
266
|
+
"session_id": sid,
|
|
267
|
+
"level": level,
|
|
268
|
+
"total": len(msgs),
|
|
269
|
+
"has_more": has_more,
|
|
270
|
+
"first_order": page[0].order if page else None,
|
|
271
|
+
"messages": [message_payload(m, level) for m in page],
|
|
272
|
+
})
|
|
273
|
+
|
|
274
|
+
def do_POST(self) -> None: # noqa: N802
|
|
275
|
+
"""POST /api/favorites/<sid> body {"star": 0|1|2, "tags": [str]}(均可选,至少一项)。"""
|
|
276
|
+
try:
|
|
277
|
+
m = _FAV_POST_RE.match(urlparse(self.path).path)
|
|
278
|
+
if m is None:
|
|
279
|
+
self._json(404, {"error": "not found"})
|
|
280
|
+
return
|
|
281
|
+
sid = m.group(1)
|
|
282
|
+
try:
|
|
283
|
+
length = int(self.headers.get("Content-Length", "0"))
|
|
284
|
+
body = json.loads(self.rfile.read(length)) if length > 0 else {}
|
|
285
|
+
except (ValueError, json.JSONDecodeError):
|
|
286
|
+
self._json(400, {"error": "bad request body"})
|
|
287
|
+
return
|
|
288
|
+
if not isinstance(body, dict):
|
|
289
|
+
self._json(400, {"error": "body must be object"})
|
|
290
|
+
return
|
|
291
|
+
star, tags = body.get("star"), body.get("tags")
|
|
292
|
+
if star is None and tags is None:
|
|
293
|
+
self._json(400, {"error": "star or tags required"})
|
|
294
|
+
return
|
|
295
|
+
if star is not None and (not isinstance(star, int) or isinstance(star, bool)
|
|
296
|
+
or star not in (0, 1, 2)):
|
|
297
|
+
self._json(400, {"error": "star must be 0|1|2"})
|
|
298
|
+
return
|
|
299
|
+
if tags is not None and (not isinstance(tags, list)
|
|
300
|
+
or not all(isinstance(t, str) for t in tags)):
|
|
301
|
+
self._json(400, {"error": "tags must be list[str]"})
|
|
302
|
+
return
|
|
303
|
+
try:
|
|
304
|
+
rec = scanner.update_favorite(sid, star=star, tags=tags)
|
|
305
|
+
except ValueError as exc:
|
|
306
|
+
self._json(400, {"error": str(exc)})
|
|
307
|
+
return
|
|
308
|
+
except OSError as exc:
|
|
309
|
+
self._json(500, {"error": f"write failed: {exc}"})
|
|
310
|
+
return
|
|
311
|
+
# 立即回写 store 内条目(不等下一次 poll),保持 rev/置顶即时生效
|
|
312
|
+
with self.store._lock:
|
|
313
|
+
ent = self.store._by_sid.get(sid)
|
|
314
|
+
if ent is not None:
|
|
315
|
+
ent.star, ent.tags = rec.get("star", 0), list(rec.get("tags", []))
|
|
316
|
+
self._json(200, {"session_id": sid, **rec})
|
|
317
|
+
except BrokenPipeError:
|
|
318
|
+
pass
|
|
319
|
+
except Exception as exc: # noqa: BLE001 — handler 兜底
|
|
320
|
+
self._json(500, {"error": f"internal: {exc}"})
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
# ---------------------------------------------------------------------------
|
|
324
|
+
# 启动
|
|
325
|
+
# ---------------------------------------------------------------------------
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def serve(args, entries: list[scanner.SessionEntry]) -> int:
|
|
329
|
+
"""绑定 127.0.0.1 并阻塞服务。
|
|
330
|
+
|
|
331
|
+
默认端口占用则 +1 顺延(最多试 10 个,交互调试友好);
|
|
332
|
+
args.fixed_port(daemon 模式)固定不顺延——用户找得到服务,占用即报错。
|
|
333
|
+
非 --no-pidfile 时写 pidfile 供 `csm serve stop/status` 使用;
|
|
334
|
+
SIGTERM 触发优雅退出(serve.stop 的正常路径)。
|
|
335
|
+
"""
|
|
336
|
+
try:
|
|
337
|
+
html_bytes = (files("csm_cli") / "web.html").read_bytes()
|
|
338
|
+
except (OSError, FileNotFoundError):
|
|
339
|
+
print("错误: 包数据缺失(web.html),安装可能不完整", file=sys.stderr)
|
|
340
|
+
return 2
|
|
341
|
+
store = SessionStore(entries, limit=args.limit, project=args.project,
|
|
342
|
+
current_tty=scanner.current_terminal_tty())
|
|
343
|
+
|
|
344
|
+
# 通过动态子类把 store/html 注入 handler(partial 对 BaseHTTPRequestHandler 不生效)
|
|
345
|
+
bound = type("BoundHandler", (CsmRequestHandler,), {"store": store, "html_bytes": html_bytes})
|
|
346
|
+
|
|
347
|
+
fixed = getattr(args, "fixed_port", False)
|
|
348
|
+
httpd = None
|
|
349
|
+
for port in range(args.port, args.port + 10):
|
|
350
|
+
try:
|
|
351
|
+
httpd = ThreadingHTTPServer(("127.0.0.1", port), bound)
|
|
352
|
+
break
|
|
353
|
+
except OSError:
|
|
354
|
+
if fixed:
|
|
355
|
+
print(f"错误: 端口 {args.port} 已被占用(daemon 模式固定端口,"
|
|
356
|
+
f"请用 --port 换端口或先 csm serve stop)", file=sys.stderr)
|
|
357
|
+
return 2
|
|
358
|
+
continue
|
|
359
|
+
if httpd is None:
|
|
360
|
+
print(f"错误: 端口 {args.port}-{args.port + 9} 均被占用", file=sys.stderr)
|
|
361
|
+
return 2
|
|
362
|
+
httpd.daemon_threads = True
|
|
363
|
+
|
|
364
|
+
# pidfile(daemon/launchd 生命周期管理用;--no-pidfile 时禁用)
|
|
365
|
+
pidfile = None
|
|
366
|
+
if not getattr(args, "no_pidfile", False):
|
|
367
|
+
from csm_cli import serve as serve_mod
|
|
368
|
+
|
|
369
|
+
pidfile = serve_mod._pid_path()
|
|
370
|
+
pidfile.parent.mkdir(parents=True, exist_ok=True)
|
|
371
|
+
pidfile.write_text(f"{os.getpid()}\n")
|
|
372
|
+
|
|
373
|
+
# SIGTERM → 优雅退出(signal handler 里不能直接调 shutdown,起线程代调)
|
|
374
|
+
import signal
|
|
375
|
+
|
|
376
|
+
def _term(signum, frame) -> None:
|
|
377
|
+
threading.Thread(target=httpd.shutdown, daemon=True).start()
|
|
378
|
+
|
|
379
|
+
signal.signal(signal.SIGTERM, _term)
|
|
380
|
+
|
|
381
|
+
url = f"http://127.0.0.1:{httpd.server_address[1]}/"
|
|
382
|
+
print(f"csm web 已启动: {url}(Ctrl-C 停止)")
|
|
383
|
+
if not args.no_open:
|
|
384
|
+
threading.Timer(0.3, webbrowser.open, args=(url,)).start()
|
|
385
|
+
try:
|
|
386
|
+
httpd.serve_forever()
|
|
387
|
+
except KeyboardInterrupt:
|
|
388
|
+
pass
|
|
389
|
+
finally:
|
|
390
|
+
if pidfile is not None:
|
|
391
|
+
try:
|
|
392
|
+
if pidfile.read_text().strip() == str(os.getpid()):
|
|
393
|
+
pidfile.unlink(missing_ok=True) # 只清自己的 pidfile
|
|
394
|
+
except OSError:
|
|
395
|
+
pass
|
|
396
|
+
return 0
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: csm-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Claude Code 会话管理器:一屏浏览/过滤/收藏全部会话,回车 resume;TUI + 本地 Web 界面
|
|
5
|
+
Project-URL: Homepage, https://github.com/cainli/csm
|
|
6
|
+
Project-URL: Issues, https://github.com/cainli/csm/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/cainli/csm/blob/main/CHANGELOG.md
|
|
8
|
+
Author: cainli
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: claude,claude-code,cli,manager,session,tui
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Environment :: Web Environment
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: MacOS
|
|
17
|
+
Classifier: Operating System :: POSIX
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Software Development
|
|
25
|
+
Classifier: Topic :: Utilities
|
|
26
|
+
Requires-Python: >=3.10
|
|
27
|
+
Requires-Dist: prompt-toolkit>=3.0
|
|
28
|
+
Requires-Dist: rich>=13
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# csm — Claude Code 会话管理器
|
|
32
|
+
|
|
33
|
+
终端里开了一堆 Claude 会话分不清哪个是哪个?`csm` 一屏列出**全局所有项目**的 Claude 会话——AI 生成的标题、首条输入、运行状态、所属项目、消息轮数、worktree 归属、Session ID——输入即过滤,回车直接 resume。
|
|
34
|
+
|
|
35
|
+
- **只读**:对 `~/.claude` 严格只读,绝不写入或清理用户数据(唯一可写的是 csm 自有的收藏文件)
|
|
36
|
+
- **轻量**:Python ≥ 3.10;`prompt_toolkit`/`rich` 随包安装,开箱即用
|
|
37
|
+
- **发射后不管**:resume 用 `execvp` 接管进程,csm 不持有、不托管任何会话(Web 后台服务除外,见 `serve`)
|
|
38
|
+
|
|
39
|
+
三种前端:**TUI**(默认,fzf 式体验)、**Web 界面**(`csm serve`,含对话流预览与 diff,可后台守护/开机自启)、**表格/JSON**(`--list`,管道友好)。
|
|
40
|
+
|
|
41
|
+
## 功能速览
|
|
42
|
+
|
|
43
|
+
| 能力 | TUI | Web | `--list/--json` |
|
|
44
|
+
|---|:-:|:-:|:-:|
|
|
45
|
+
| 全局会话列表 + 即时过滤(多词 AND、`#标签`) | ✅ | ✅ | ✅(管道 grep/jq) |
|
|
46
|
+
| 运行状态(●busy/idle/waiting,pid 三重判活防复用) | ✅ | ✅ | ✅ |
|
|
47
|
+
| ◉本终端标记(tmux 下精确到 pane) | ✅ | ✅ | ✅ |
|
|
48
|
+
| 收藏两档(⭐/★)置顶 + 标签 | ✅ `s` 键 | ✅ 点星/编辑标签 | ✅ 字段输出 |
|
|
49
|
+
| 六档分类过滤(全部/运行中/本终端/收藏/已关闭/单轮) | ✅ `1`-`6` | ✅ chips | — |
|
|
50
|
+
| **worktree 感知**(`repo/wt ⎇分支 +未合并数`) | ✅ | ✅ | ✅ |
|
|
51
|
+
| 对话流预览(Markdown 渲染 + 工具调用折叠) | ✅ Tab 最近 50 条 | ✅ 完整分页 | — |
|
|
52
|
+
| **Edit/Write/MultiEdit 行级 diff**(红删绿增) | — | ✅ 完整级别 | — |
|
|
53
|
+
| **双开保护**(活会话在他终端 → 确认拦截) | ✅ | — | — |
|
|
54
|
+
| 复制 resume 命令(终端/tmux/headless 三变体) | — | ✅ | — |
|
|
55
|
+
| SDK 子进程会话标记(`sdk-cli` → SDK) | ✅ | ✅ | ✅ |
|
|
56
|
+
| **Web 后台守护**(`csm serve start/stop/status`,launchd 开机自启) | — | ✅ | — |
|
|
57
|
+
|
|
58
|
+
## 安装
|
|
59
|
+
|
|
60
|
+
PyPI 正式分发(包名 `csm-cli`,安装后命令为 `csm`):
|
|
61
|
+
|
|
62
|
+
```zsh
|
|
63
|
+
pipx install csm-cli # 或:uv tool install csm-cli
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
升级 / 卸载:`pipx upgrade csm-cli` / `pipx uninstall csm-cli`(uv 同理 `uv tool upgrade` / `uv tool uninstall`)。
|
|
67
|
+
|
|
68
|
+
需要 Python ≥ 3.10;`prompt_toolkit`/`rich` 随包自动安装。
|
|
69
|
+
|
|
70
|
+
<details><summary>从源码运行(开发/旧 alias)</summary>
|
|
71
|
+
|
|
72
|
+
```zsh
|
|
73
|
+
git clone https://github.com/cainli/csm.git && cd csm
|
|
74
|
+
python3 -m pytest # 跑测试
|
|
75
|
+
alias csm="$PWD/csm.py" # 仓库自带的兼容 shim
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
</details>
|
|
79
|
+
|
|
80
|
+
## 快速开始
|
|
81
|
+
|
|
82
|
+
```zsh
|
|
83
|
+
csm # TUI:打字过滤,回车 resume
|
|
84
|
+
csm serve start # 后台起 Web 界面(127.0.0.1:8737,打印 URL)
|
|
85
|
+
csm --list # 终端表格;csm --list --json | jq '.[] | .title'
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## 命令行参数
|
|
89
|
+
|
|
90
|
+
```zsh
|
|
91
|
+
csm # 交互式 TUI(默认;stdout 非 tty 时自动降级 --list)
|
|
92
|
+
csm --list # 非交互表格
|
|
93
|
+
csm --list --json # JSON 输出,可配 jq
|
|
94
|
+
csm --list --full-scan # 表格带完整消息数(较慢 ~0.6s)
|
|
95
|
+
csm --project voicemouse # 按项目路径过滤(大小写不敏感)
|
|
96
|
+
csm --new [PATH] # 在 PATH(默认当前目录)起新会话,不进列表
|
|
97
|
+
csm --no-cd # resume 时停留在当前目录(默认切到原项目目录)
|
|
98
|
+
csm --limit 50 # 最多列出 50 条(默认全部)
|
|
99
|
+
csm --no-color / --version
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Web 服务:`csm serve`
|
|
103
|
+
|
|
104
|
+
```zsh
|
|
105
|
+
csm serve # 前台运行(调试用,端口占用自动顺延,Ctrl-C 停)
|
|
106
|
+
csm serve start # 后台启动(固定 8737,打印 URL;日志 ~/.claude/csm/serve.log)
|
|
107
|
+
csm serve start --port 9000 --open
|
|
108
|
+
csm serve status # running/stopped(pid + 探活)
|
|
109
|
+
csm serve restart
|
|
110
|
+
csm serve stop # SIGTERM 优雅停(5s 超时强杀兜底)
|
|
111
|
+
csm serve install-launchd # macOS 开机自启 + 崩溃自动拉起(launchd KeepAlive)
|
|
112
|
+
csm serve uninstall-launchd
|
|
113
|
+
csm --web # 兼容别名 = csm serve(前台)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
launchd 模式日志在 `~/.claude/csm/launchd.{out,err}.log`;停 launchd 管理的服务请用 `uninstall-launchd`(手动 `stop` 会提示)。
|
|
117
|
+
|
|
118
|
+
## TUI
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
csm — 77 会话 (22 运行中) ★3 ⭐7 过滤:全部 68/77 1-6过滤 s星标 Tab预览 ^L清空 ^R重扫 esc退出
|
|
122
|
+
◉★ 11:20 ●busy 修复登录超时问题 #线上 claude-tools/fleet-features 12 757f8670-…
|
|
123
|
+
10:29 ●idle Orca 多 Agent 开发环境 swain 8 892a5d70-…
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### 键位
|
|
127
|
+
|
|
128
|
+
| 键 | 列表视图 | 预览视图 |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `↑` `↓` / `j` `k`(输入为空时) | 选择 | 滚动消息 |
|
|
131
|
+
| `PgUp` `PgDn` `Home` `End` | 翻页/跳转 | 翻页/顶底 |
|
|
132
|
+
| 直接打字 | 过滤(标题/首输入/项目路径/SID,多词 AND;`#标签` 精确筛) | 同左 |
|
|
133
|
+
| `1`-`6` | **分类过滤**:全部/运行中/本终端/收藏/已关闭/单轮 | — |
|
|
134
|
+
| `s` | **星标循环**:无 → ⭐ → ★ → 无(收藏永久置顶) | — |
|
|
135
|
+
| `Tab` | **进入会话预览**(最近 50 条消息流) | 返回列表(保持原选择) |
|
|
136
|
+
| `Enter` | resume 选中会话(先 cd 到原项目目录;见他终端运行会触发双开确认) | resume 该会话 |
|
|
137
|
+
| `Ctrl-L` / `Ctrl-R` | 清空过滤 / 重新扫描 | 清空 / 刷新预览 |
|
|
138
|
+
| `Esc` / `Ctrl-C` | 退出(码 130) | 返回列表 / 退出 |
|
|
139
|
+
|
|
140
|
+
列表列:`◉本终端+★收藏 · 活跃时间 · ●运行状态 · 标题(或首条输入)#标签 · 项目 · 轮数 · Session ID`。闭会话若是 SDK 启动显示 `sdk` 标记;worktree 会话项目列显示 `主仓库/worktree名`。
|
|
141
|
+
|
|
142
|
+
每 30s 静默重扫:新会话自动出现在列表顶部,不打断当前选择与滚动(sid 桥接恢复状态);正在输入过滤词时跳过当轮重扫。
|
|
143
|
+
|
|
144
|
+
## Web 界面(`csm serve`)
|
|
145
|
+
|
|
146
|
+
后台常驻(`csm serve start`,关终端不影响;`install-launchd` 开机自启)或前台调试(`csm serve` / 兼容别名 `--web`)。
|
|
147
|
+
|
|
148
|
+
- 左侧列表(搜索 + 分类 chips、NEW/◉本终端/SDK/worktree 徽章、星形按钮、收藏置顶浅色段)+ 右侧对话流
|
|
149
|
+
- **预览两级深度**:摘要(默认)/ 完整;消息按 **Markdown 渲染**(代码块/粗斜体/标题/列表/引用/链接/表格;先转义再白名单转换,免疫 XSS,离线自实现无 CDN)
|
|
150
|
+
- **行级 diff**:完整级别下点击 🔧 Edit/Write/MultiEdit 行展开——红删/绿增/无色上下文,LCS 对齐;MultiEdit 逐段标注
|
|
151
|
+
- **复制命令三变体**:`claude --resume`(终端)/ `tmux new-window -c`(并行恢复,落到原项目目录)/ `claude -p --resume`(headless 续跑)
|
|
152
|
+
- 每 5s 自动轮询(页面隐藏时暂停);深浅色跟随系统;窄窗口(≤860px)自动单栏
|
|
153
|
+
- 消息解析缓存(mtime/size 失效):14MB 会话首次解析 ~几十 ms,二次 <15ms
|
|
154
|
+
|
|
155
|
+
## 会话生命周期
|
|
156
|
+
|
|
157
|
+
### 双开保护
|
|
158
|
+
|
|
159
|
+
resume 一个正在**其他终端**运行的会话时,csm 警告并要求确认——两处同时写入同一会话文件(jsonl)可能导致内容交叉错乱。本终端运行的会话不拦;tty 无法识别时宁可误拦。
|
|
160
|
+
|
|
161
|
+
### `--new`:快速发射
|
|
162
|
+
|
|
163
|
+
`csm --new ~/dev/workspace/swain` 直接在该目录起新会话。与 resume 同为 `execvp` 接管——csm 始终不持有会话进程。
|
|
164
|
+
|
|
165
|
+
### worktree 感知
|
|
166
|
+
|
|
167
|
+
会话工作目录是 git worktree 时(EnterWorktree / `git worktree add` 后),读 `.git` 的 gitdir **指针**反解归属(不猜目录名,submodule 不误判),显示 `主仓库/worktree名 ⎇分支 +未合并提交数`:
|
|
168
|
+
|
|
169
|
+
- jsonl 的 `cwd` 逐行随 cd 变化——检测用**最后一条 cwd**(会话当前所在);`project_path`(第一条 cwd,出生地)语义不变
|
|
170
|
+
- 未合并数由后台线程跑 `git rev-list --count` 补齐(超时 2s 静默降级)
|
|
171
|
+
- 全程只读:不创建、不清理任何 worktree
|
|
172
|
+
|
|
173
|
+
## 收藏与标签
|
|
174
|
+
|
|
175
|
+
- 存储在 `~/.claude/csm/favorites.json`(csm 自有命名空间,唯一可写文件;原子写 + 跨进程锁)
|
|
176
|
+
- 星标两档:⭐ 普通收藏 / ★ 重要;永久置顶(★ 段前于 ⭐ 段,段内按活跃时间)
|
|
177
|
+
- 标签在 Web 详情栏添加;搜索 `#标签名` 精确筛(多标签 AND);TUI 与 Web 双向同步(≤30s)
|
|
178
|
+
|
|
179
|
+
## 分类口径(诚实声明)
|
|
180
|
+
|
|
181
|
+
- **运行状态**:busy/idle/waiting 来自 Claude 活跃注册表,pid 三重判活(存活 + 进程名含 claude + 启动时间容差比对)防 pid 复用;已关闭 = jsonl 在而注册表无活记录
|
|
182
|
+
- **本终端**:会话进程 tty == csm 进程 tty(tmux 下精确到 pane);被 GUI 嵌套调用时可能无法识别,过滤器自动降级
|
|
183
|
+
- **单轮**:恰 1 条用户输入的会话。`claude -p` 无法从官方数据可靠识别(`entrypoint` 对交互与 `-p` 同为 `cli`),「单轮」是最接近的客观特征;SDK 子进程(`sdk-cli`)可识别并标记 SDK
|
|
184
|
+
|
|
185
|
+
## 数据来源(只读)
|
|
186
|
+
|
|
187
|
+
| 路径 | 用途 |
|
|
188
|
+
|---|---|
|
|
189
|
+
| `~/.claude/projects/*/*.jsonl` | 会话转录;文件名即 Session ID;标题取最后一条 `ai-title`;行内 `cwd`/`entrypoint` |
|
|
190
|
+
| `~/.claude/sessions/*.json` | 运行中会话注册表 → 状态 + tty 关联 |
|
|
191
|
+
| `~/.claude/history.jsonl` | 无标题会话的首条输入回退 |
|
|
192
|
+
| `~/.claude/csm/favorites.json` | **csm 自有**:收藏与标签(唯一可写) |
|
|
193
|
+
|
|
194
|
+
进程信息:单次 `ps -axo pid,ppid,tty,lstart,command` 快照三用(会话 tty / 进程名校验防 pid 回绕 / PPID 链上溯识别本终端)。
|
|
195
|
+
支持 `CLAUDE_CONFIG_DIR` 重定向配置目录(测试注入用)。
|
|
196
|
+
|
|
197
|
+
## 性能
|
|
198
|
+
|
|
199
|
+
三级渐进扫描:启动只 stat + 头尾各 64KB 轻扫(<0.2s);消息轮数/worktree 未合并数由后台线程补齐;全文件解析仅在预览时发生且有 LRU 缓存,14MB 会话二次读取 <15ms。
|
|
200
|
+
|
|
201
|
+
## 开发
|
|
202
|
+
|
|
203
|
+
```zsh
|
|
204
|
+
python3 -m pytest # 全部单测:离线假数据 + 真 git worktree 集成,不碰真实 ~/.claude
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
- 包布局 `src/csm_cli/`:`cli.py` 入口/CLI/resume/双开保护 · `scanner.py` 数据层+消息解析(唯一文件 I/O)·
|
|
208
|
+
`ui.py` TUI · `web.py` Web 服务端 · `web.html` Web 前端(单文件,无构建,importlib.resources 读取)·
|
|
209
|
+
`serve.py` 守护进程 · `fmt.py` 纯函数格式化;仓库根 `csm.py` 为兼容 shim
|
|
210
|
+
- `fmt.py` 中 `rel_time()` / `fuzzy_score()` 为故意留空的降级实现(学习场景),实装后 `test_fmt.py` 的 `skipif` 自动生效
|
|
211
|
+
- `web.html` 顶部 CSS 变量可整体换肤;打包见 `pyproject.toml`(hatchling,`csm-cli`)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
csm_cli/__init__.py,sha256=UTDaOtuFR_GYN4NI4ZJn7B8rbDuSpd0uv6GHxPajIOY,230
|
|
2
|
+
csm_cli/__main__.py,sha256=87TPdja8sbMsRygwJwGdFdfR5W4H6Z6XR2TXRIHlS5g,168
|
|
3
|
+
csm_cli/cli.py,sha256=hYRfR2z6DJXjJd2SdEOumJx_e-_bAInV_7YzXqWbfWw,13230
|
|
4
|
+
csm_cli/fmt.py,sha256=Y8oJDcUE9tBXsCypwpeei0C7VvmGIawnpdfuRaYCwQM,4022
|
|
5
|
+
csm_cli/scanner.py,sha256=v_Lxk7bWxXoJxx4YRoUOKbzTCxerDawYO46uo5eKUFE,41111
|
|
6
|
+
csm_cli/serve.py,sha256=oEwcn3K_Q7mJ3MbZ6717qSoV4CJyfsMn1oQkSim0TQY,10513
|
|
7
|
+
csm_cli/ui.py,sha256=C0nX36e6QL9a4-DonFTrBhpT1BM9WAINzIhJ4FZfZw8,30857
|
|
8
|
+
csm_cli/web.html,sha256=12k8J6t-7yFv1vNqI8-isqJnbcY8ZCWRJ3_mfj5shzs,37270
|
|
9
|
+
csm_cli/web.py,sha256=iDPSA64QGV4WkIWsiD6wA7aIwWgcJab7EfDQylddy4c,16280
|
|
10
|
+
csm_cli-0.1.0.dist-info/METADATA,sha256=5pnzlpzcOqPbmT9ltrbVSLRvB2ht_d8BueTlpZ9aPqg,11901
|
|
11
|
+
csm_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
csm_cli-0.1.0.dist-info/entry_points.txt,sha256=WR11np-e53lDNX5iTGQiJnaE_wQOOqV4LS6qvwghv9M,41
|
|
13
|
+
csm_cli-0.1.0.dist-info/licenses/LICENSE,sha256=dIoKhfi8LSJnw4bhSUQpzwEA7I5bPL8821ZRCXpBMeI,1063
|
|
14
|
+
csm_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 cainli
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|