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/serve.py ADDED
@@ -0,0 +1,305 @@
1
+ """csm serve — Web 服务的守护进程管理(start/stop/status/restart + launchd)。
2
+
3
+ - `csm serve` 前台运行(调试用,端口顺延,Ctrl-C 停)
4
+ - `csm serve start` 后台 daemon:子进程 `python -m csm_cli serve --foreground`
5
+ 脱离会话(start_new_session=True),pidfile + 日志落 ~/.claude/csm/;
6
+ daemon 端口固定默认 8737 不顺延(用户找得到;占用则报错提示 --port)
7
+ - `stop`:SIGTERM 优雅停(web 端信号处理器触发 httpd.shutdown)→ 5s 超时
8
+ SIGKILL 兜底 → 清 pidfile;pid 复用防护(ps 校验 command 含 csm)
9
+ - launchd 模式:plist 由 launchd 管理(KeepAlive 崩溃自拉),不写 pidfile;
10
+ 手动 stop 检测到 launchd 时提示改用 uninstall-launchd
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import signal
17
+ import subprocess
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+
22
+ DEFAULT_PORT = 8737
23
+ LAUNCHD_LABEL = "com.csm.serve"
24
+ _START_TIMEOUT = 8.0 # start 后等 pidfile + HTTP 探活的总预算
25
+
26
+
27
+ def _state_dir() -> Path:
28
+ """守护状态目录(与 favorites 同一 csm 自有命名空间)。"""
29
+ root = Path(os.environ.get("CLAUDE_CONFIG_DIR", "~/.claude")).expanduser()
30
+ d = root / "csm"
31
+ d.mkdir(parents=True, exist_ok=True)
32
+ return d
33
+
34
+
35
+ def _pid_path() -> Path:
36
+ return _state_dir() / "serve.pid"
37
+
38
+
39
+ def _log_path() -> Path:
40
+ return _state_dir() / "serve.log"
41
+
42
+
43
+ def _launchd_plist() -> Path:
44
+ return Path.home() / "Library" / "LaunchAgents" / f"{LAUNCHD_LABEL}.plist"
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # pidfile 与探活
49
+ # ---------------------------------------------------------------------------
50
+
51
+
52
+ def _read_pid() -> int | None:
53
+ try:
54
+ return int(_pid_path().read_text().strip())
55
+ except (OSError, ValueError):
56
+ return None
57
+
58
+
59
+ def _pid_is_csm(pid: int) -> bool:
60
+ """pid 存活且 command 含 csm(防 pid 复用误杀无关进程)。"""
61
+ import shutil
62
+
63
+ if not shutil.which("ps"):
64
+ return True # 无法校验,保守放行
65
+ try:
66
+ out = subprocess.run(["ps", "-o", "command=", "-p", str(pid)],
67
+ capture_output=True, text=True, timeout=3)
68
+ except (OSError, subprocess.TimeoutExpired):
69
+ return False
70
+ cmd = out.stdout.strip()
71
+ return bool(cmd) and ("csm" in cmd)
72
+
73
+
74
+ def _http_alive(port: int, timeout: float = 3.0) -> bool:
75
+ """探活本地服务。必须显式禁代理:系统代理会劫持对 127.0.0.1 的请求。"""
76
+ import urllib.request
77
+
78
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
79
+ try:
80
+ with opener.open(f"http://127.0.0.1:{port}/api/sessions", timeout=timeout) as resp:
81
+ return resp.status == 200
82
+ except OSError:
83
+ return False
84
+
85
+
86
+ def _is_launchd_managed() -> bool:
87
+ return _launchd_plist().is_file()
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # start / stop / status
92
+ # ---------------------------------------------------------------------------
93
+
94
+
95
+ def _truncate_log_if_huge(max_bytes: int = 1_000_000) -> None:
96
+ p = _log_path()
97
+ try:
98
+ if p.stat().st_size > max_bytes:
99
+ tail = p.read_bytes()[-max_bytes // 2:]
100
+ p.write_bytes(tail)
101
+ except OSError:
102
+ pass
103
+
104
+
105
+ def cmd_start(port: int, open_browser: bool, project: str | None, limit: int) -> int:
106
+ if _is_launchd_managed():
107
+ print(f"已由 launchd 管理({_launchd_plist()}),请用 launchctl 或 "
108
+ f"`csm serve uninstall-launchd` 停止", file=sys.stderr)
109
+ return 2
110
+ if (pid := _read_pid()) is not None and _pid_is_csm(pid):
111
+ print(f"已在运行: pid={pid} url=http://127.0.0.1:{_port_of(pid) or port}/")
112
+ return 0
113
+ _pid_path().unlink(missing_ok=True) # 残留 pidfile(进程已死)清掉
114
+ _truncate_log_if_huge()
115
+
116
+ # -u 关闭 stdout 缓冲:启动行需及时落日志(_read_port_hint 解析端口)
117
+ cmd = [sys.executable, "-u", "-m", "csm_cli", "serve", "--foreground",
118
+ "--no-open", "--port", str(port), "--fixed-port"]
119
+ if project:
120
+ cmd += ["--project", project]
121
+ if limit:
122
+ cmd += ["--limit", str(limit)]
123
+ log = open(_log_path(), "ab") # noqa: SIM115 — daemon 子进程接管 fd 后生命周期独立
124
+ subprocess.Popen(cmd, stdout=log, stderr=log, stdin=subprocess.DEVNULL,
125
+ start_new_session=True)
126
+ log.close()
127
+
128
+ deadline = time.monotonic() + _START_TIMEOUT
129
+ while time.monotonic() < deadline:
130
+ pid = _read_pid()
131
+ if pid is not None and _http_alive(port):
132
+ url = f"http://127.0.0.1:{port}/"
133
+ print(f"已启动: pid={pid} url={url}(日志: {_log_path()})")
134
+ if open_browser:
135
+ import webbrowser
136
+
137
+ webbrowser.open(url)
138
+ return 0
139
+ time.sleep(0.2)
140
+ print(f"启动失败({_START_TIMEOUT:.0f}s 内未就绪),日志尾部:", file=sys.stderr)
141
+ try:
142
+ tail = _log_path().read_text(errors="replace").splitlines()[-10:]
143
+ print("\n".join(tail), file=sys.stderr)
144
+ except OSError:
145
+ pass
146
+ return 2
147
+
148
+
149
+ def _port_of(pid: int) -> int | None:
150
+ """从日志或保守默认推断端口;pidfile 只存 pid,端口记录在启动行里。"""
151
+ return _read_port_hint() or DEFAULT_PORT
152
+
153
+
154
+ def _read_port_hint() -> int | None:
155
+ """扫日志找最后一条启动行 `csm web 已启动: http://127.0.0.1:PORT/`。"""
156
+ import re as _re
157
+
158
+ pat = _re.compile(r"csm web 已启动: http://127\.0\.0\.1:(\d+)/")
159
+ try:
160
+ for line in reversed(_log_path().read_text(errors="replace").splitlines()):
161
+ if (m := pat.search(line)):
162
+ return int(m.group(1))
163
+ except OSError:
164
+ pass
165
+ return None
166
+
167
+
168
+ def cmd_stop() -> int:
169
+ if _is_launchd_managed() and _read_pid() is None:
170
+ print(f"服务由 launchd 管理,请用 `csm serve uninstall-launchd` 停止", file=sys.stderr)
171
+ return 2
172
+ pid = _read_pid()
173
+ if pid is None:
174
+ print("未运行")
175
+ return 0
176
+ if not _pid_is_csm(pid):
177
+ _pid_path().unlink(missing_ok=True)
178
+ print("pidfile 指向的进程已不是 csm,已清理")
179
+ return 0
180
+ port = _read_port_hint() or DEFAULT_PORT
181
+ try:
182
+ os.kill(pid, signal.SIGTERM)
183
+ except OSError:
184
+ pass
185
+ deadline = time.monotonic() + 5.0
186
+ while time.monotonic() < deadline:
187
+ if not _http_alive(port, timeout=0.5) and not _proc_alive(pid):
188
+ break
189
+ time.sleep(0.2)
190
+ if _proc_alive(pid):
191
+ try:
192
+ os.kill(pid, signal.SIGKILL) # 兜底
193
+ except OSError:
194
+ pass
195
+ _pid_path().unlink(missing_ok=True)
196
+ print(f"已停止 (pid={pid})")
197
+ return 0
198
+
199
+
200
+ def _proc_alive(pid: int) -> bool:
201
+ try:
202
+ os.kill(pid, 0)
203
+ return True
204
+ except OSError:
205
+ return False
206
+
207
+
208
+ def cmd_status() -> int:
209
+ if _is_launchd_managed():
210
+ port = _read_port_hint() or DEFAULT_PORT
211
+ state = "running (launchd)" if _http_alive(port) else "launchd 已装载但未探活"
212
+ print(f"{state} url=http://127.0.0.1:{port}/")
213
+ return 0 if "running" in state else 1
214
+ pid = _read_pid()
215
+ if pid is None:
216
+ print("stopped")
217
+ return 1
218
+ if not _pid_is_csm(pid):
219
+ print("stopped(pidfile 残留)")
220
+ return 1
221
+ port = _read_port_hint() or DEFAULT_PORT
222
+ http_ok = _http_alive(port)
223
+ print(f"{'running' if http_ok else 'degraded(进程在,HTTP 无响应)'}"
224
+ f" pid={pid} url=http://127.0.0.1:{port}/")
225
+ return 0 if http_ok else 1
226
+
227
+
228
+ def cmd_restart(port: int, open_browser: bool, project: str | None, limit: int) -> int:
229
+ cmd_stop()
230
+ time.sleep(0.3)
231
+ return cmd_start(port, open_browser, project, limit)
232
+
233
+
234
+ # ---------------------------------------------------------------------------
235
+ # launchd(macOS 开机自启)
236
+ # ---------------------------------------------------------------------------
237
+
238
+ _PLIST_TMPL = """<?xml version="1.0" encoding="UTF-8"?>
239
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 4.0//EN" "http://www.apple.com/DTDs/PropertyList-4.0.dtd">
240
+ <plist version="4.0">
241
+ <dict>
242
+ <key>Label</key><string>{label}</string>
243
+ <key>ProgramArguments</key>
244
+ <array>
245
+ <string>{csm_bin}</string>
246
+ <string>serve</string>
247
+ <string>--foreground</string>
248
+ <string>--no-open</string>
249
+ <string>--no-pidfile</string>
250
+ <string>--port</string>
251
+ <string>{port}</string>
252
+ </array>
253
+ <key>RunAtLoad</key><true/>
254
+ <key>KeepAlive</key><true/>
255
+ <key>StandardOutPath</key><string>{out_log}</string>
256
+ <key>StandardErrorPath</key><string>{err_log}</string>
257
+ <key>EnvironmentVariables</key>
258
+ <dict>
259
+ <key>PATH</key>
260
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
261
+ </dict>
262
+ </dict>
263
+ </plist>
264
+ """
265
+
266
+
267
+ def cmd_install_launchd(port: int) -> int:
268
+ import shutil
269
+
270
+ csm_bin = shutil.which("csm")
271
+ if not csm_bin:
272
+ print("错误: 找不到已安装的 csm 命令(launchd 需要绝对路径)。"
273
+ "请先 pipx install csm-cli / uv tool install csm-cli", file=sys.stderr)
274
+ return 2
275
+ out_log = _state_dir() / "launchd.out.log"
276
+ err_log = _state_dir() / "launchd.err.log"
277
+ plist = _launchd_plist()
278
+ plist.parent.mkdir(parents=True, exist_ok=True)
279
+ plist.write_text(_PLIST_TMPL.format(
280
+ label=LAUNCHD_LABEL, csm_bin=csm_bin, port=port,
281
+ out_log=out_log, err_log=err_log))
282
+ # launchd 模式不用手动 pidfile:先停手动实例避免端口冲突
283
+ if (pid := _read_pid()) is not None and _pid_is_csm(pid):
284
+ cmd_stop()
285
+ r = subprocess.run(["launchctl", "unload", str(plist)], capture_output=True)
286
+ r = subprocess.run(["launchctl", "load", str(plist)], capture_output=True)
287
+ if r.returncode != 0:
288
+ print(f"launchctl load 失败: {r.stderr.decode(errors='replace').strip()}",
289
+ file=sys.stderr)
290
+ return 2
291
+ print(f"launchd 已装载(开机自启 + 崩溃自动拉起)")
292
+ print(f" url=http://127.0.0.1:{port}/ plist={plist}")
293
+ print(f" 日志: {out_log} / {err_log}")
294
+ return 0
295
+
296
+
297
+ def cmd_uninstall_launchd() -> int:
298
+ plist = _launchd_plist()
299
+ if not plist.is_file():
300
+ print("未安装 launchd 服务")
301
+ return 0
302
+ subprocess.run(["launchctl", "unload", str(plist)], capture_output=True)
303
+ plist.unlink()
304
+ print("launchd 服务已卸载")
305
+ return 0