rc-shepherd 0.6.1__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.
- rc_shepherd/__init__.py +3 -0
- rc_shepherd/__main__.py +5 -0
- rc_shepherd/cli.py +313 -0
- rc_shepherd/completion.py +109 -0
- rc_shepherd/config.example.toml +88 -0
- rc_shepherd/config.py +387 -0
- rc_shepherd/discovery.py +155 -0
- rc_shepherd/doctor.py +128 -0
- rc_shepherd/procscan.py +104 -0
- rc_shepherd/projects_edit.py +69 -0
- rc_shepherd/service.py +141 -0
- rc_shepherd/supervisor.py +442 -0
- rc_shepherd/units.py +47 -0
- rc_shepherd-0.6.1.dist-info/METADATA +225 -0
- rc_shepherd-0.6.1.dist-info/RECORD +18 -0
- rc_shepherd-0.6.1.dist-info/WHEEL +4 -0
- rc_shepherd-0.6.1.dist-info/entry_points.txt +2 -0
- rc_shepherd-0.6.1.dist-info/licenses/LICENSE +21 -0
rc_shepherd/__init__.py
ADDED
rc_shepherd/__main__.py
ADDED
rc_shepherd/cli.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Command line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shlex
|
|
9
|
+
import signal
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import tomllib
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from rc_shepherd import __version__, completion, doctor, procscan, service
|
|
16
|
+
from rc_shepherd.config import (
|
|
17
|
+
Config,
|
|
18
|
+
ConfigError,
|
|
19
|
+
UnsafeStateDir,
|
|
20
|
+
default_config_path,
|
|
21
|
+
dumps_json,
|
|
22
|
+
example_config,
|
|
23
|
+
load_config,
|
|
24
|
+
parse_config,
|
|
25
|
+
private_dir,
|
|
26
|
+
)
|
|
27
|
+
from rc_shepherd.discovery import DiscoveryError, discover
|
|
28
|
+
from rc_shepherd.projects_edit import set_enabled
|
|
29
|
+
from rc_shepherd.supervisor import Supervisor, build_command, request
|
|
30
|
+
from rc_shepherd.units import format_duration
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CliError(Exception):
|
|
34
|
+
def __init__(self, message: str, code: int = 1):
|
|
35
|
+
super().__init__(message)
|
|
36
|
+
self.code = code
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
NOT_RUNNING = "supervisor not running (see `rc-shepherd service status`)"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def read_state(cfg: Config) -> dict:
|
|
43
|
+
"""The running supervisor's state. Its pid is checked before anyone signals it."""
|
|
44
|
+
try:
|
|
45
|
+
private_dir(cfg.paths.state_file.parent)
|
|
46
|
+
state = json.loads(cfg.paths.state_file.read_text(encoding="utf-8"))
|
|
47
|
+
except UnsafeStateDir as exc:
|
|
48
|
+
raise CliError(str(exc)) from None
|
|
49
|
+
except (OSError, ValueError):
|
|
50
|
+
raise CliError(NOT_RUNNING) from None
|
|
51
|
+
if not isinstance(state, dict) or not procscan.is_supervisor(state.get("pid")):
|
|
52
|
+
raise CliError(NOT_RUNNING + "; the state file is stale")
|
|
53
|
+
return state
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _signal_supervisor(cfg: Config, sig: int) -> bool:
|
|
57
|
+
try:
|
|
58
|
+
os.kill(read_state(cfg)["pid"], sig)
|
|
59
|
+
except (CliError, ProcessLookupError):
|
|
60
|
+
return False
|
|
61
|
+
return True
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# -- commands ------------------------------------------------------------------
|
|
65
|
+
def cmd_run(cfg: Config, args, env, out) -> int:
|
|
66
|
+
if args.dry_run:
|
|
67
|
+
try:
|
|
68
|
+
candidates = discover(cfg)
|
|
69
|
+
except DiscoveryError as exc:
|
|
70
|
+
raise CliError(str(exc)) from None
|
|
71
|
+
for c in candidates:
|
|
72
|
+
if c.serve:
|
|
73
|
+
cmd = build_command(cfg.supervisor.claude_bin, c.path, c.options)
|
|
74
|
+
print(f"cd {shlex.quote(str(c.path))} && {shlex.join(cmd)}", file=out)
|
|
75
|
+
return 0
|
|
76
|
+
try:
|
|
77
|
+
Supervisor(cfg, env=env).run()
|
|
78
|
+
except UnsafeStateDir as exc:
|
|
79
|
+
raise CliError(str(exc), service.CONFIG_EXIT) from None
|
|
80
|
+
return 0
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def cmd_status(cfg: Config, args, env, out, wall=time.time) -> int:
|
|
84
|
+
state = read_state(cfg)
|
|
85
|
+
if args.json:
|
|
86
|
+
print(json.dumps(state, indent=2), file=out)
|
|
87
|
+
return 0
|
|
88
|
+
print(f"supervisor pid {state['pid']} · config {state.get('config_file', '?')}", file=out)
|
|
89
|
+
if not state["projects"]:
|
|
90
|
+
print("no project served", file=out)
|
|
91
|
+
for p in state["projects"]:
|
|
92
|
+
parts = [f"{p['name']:<24}", p["status"]]
|
|
93
|
+
if p.get("pid"):
|
|
94
|
+
parts.append(f"pid {p['pid']}")
|
|
95
|
+
if p.get("since"):
|
|
96
|
+
parts.append(f"up {format_duration(wall() - p['since'])}")
|
|
97
|
+
parts.append(f"{p['restarts']} restart(s)")
|
|
98
|
+
if p.get("restart_pending"):
|
|
99
|
+
parts.append("options changed: restart to apply")
|
|
100
|
+
if p.get("outdated"):
|
|
101
|
+
parts.append("older Claude Code: " + ("restarts once its sessions are idle"
|
|
102
|
+
if cfg.supervisor.restart_on_update == "idle"
|
|
103
|
+
else "restart to update"))
|
|
104
|
+
if p.get("last_error"):
|
|
105
|
+
parts.append(f"last: {p['last_error']}")
|
|
106
|
+
print(" · ".join(parts), file=out)
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def cmd_list(cfg: Config, args, env, out) -> int:
|
|
111
|
+
try:
|
|
112
|
+
candidates = discover(cfg)
|
|
113
|
+
except DiscoveryError as exc:
|
|
114
|
+
raise CliError(str(exc)) from None
|
|
115
|
+
if args.json:
|
|
116
|
+
print(json.dumps([{"path": str(c.path), "serve": c.serve, "reason": c.reason,
|
|
117
|
+
"last_activity": c.last_activity,
|
|
118
|
+
"options": c.options.as_dict() if c.options else None} for c in candidates],
|
|
119
|
+
indent=2), file=out)
|
|
120
|
+
return 0
|
|
121
|
+
for c in candidates:
|
|
122
|
+
print(f"{'serve' if c.serve else 'skip ':<5} {c.path} ({c.reason})", file=out)
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def cmd_toggle(cfg: Config, args, env, out) -> int:
|
|
127
|
+
path = Path(args.path).expanduser().resolve()
|
|
128
|
+
file = cfg.paths.config_file
|
|
129
|
+
text = file.read_text(encoding="utf-8") if file.exists() else ""
|
|
130
|
+
new_text, summary = set_enabled(text, path, args.cmd == "enable", cfg.paths.home)
|
|
131
|
+
try:
|
|
132
|
+
parse_config(tomllib.loads(new_text), cfg.paths)
|
|
133
|
+
except (ConfigError, tomllib.TOMLDecodeError) as exc:
|
|
134
|
+
raise CliError(f"refusing to write an invalid configuration: {exc}") from None
|
|
135
|
+
file.parent.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
if file.exists():
|
|
137
|
+
file.with_name(file.name + ".bak").write_text(text, encoding="utf-8")
|
|
138
|
+
file.write_text(new_text, encoding="utf-8")
|
|
139
|
+
print(f"{summary} in {file}", file=out)
|
|
140
|
+
if _signal_supervisor(cfg, signal.SIGHUP):
|
|
141
|
+
print("supervisor reloaded", file=out)
|
|
142
|
+
return 0
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def cmd_restart(cfg: Config, args, env, out) -> int:
|
|
146
|
+
state = read_state(cfg)
|
|
147
|
+
if args.all:
|
|
148
|
+
request(cfg.paths.state_file, {"action": "restart", "all": True})
|
|
149
|
+
names = "all projects"
|
|
150
|
+
else:
|
|
151
|
+
if not args.project:
|
|
152
|
+
raise CliError("give a project name or path, or --all", 2)
|
|
153
|
+
match = [p for p in state["projects"] if args.project in (p["name"], p["path"])]
|
|
154
|
+
if not match:
|
|
155
|
+
raise CliError(f"unknown project: {args.project}")
|
|
156
|
+
for p in match:
|
|
157
|
+
request(cfg.paths.state_file, {"action": "restart", "path": p["path"]})
|
|
158
|
+
names = ", ".join(p["name"] for p in match)
|
|
159
|
+
os.kill(state["pid"], signal.SIGUSR1)
|
|
160
|
+
print(f"restarting {names} (work in progress in their sessions is interrupted)", file=out)
|
|
161
|
+
return 0
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def cmd_reload(cfg: Config, args, env, out) -> int:
|
|
165
|
+
state = read_state(cfg)
|
|
166
|
+
if args.apply:
|
|
167
|
+
request(cfg.paths.state_file, {"action": "apply"})
|
|
168
|
+
os.kill(state["pid"], signal.SIGUSR1)
|
|
169
|
+
print("configuration reload requested; servers with changed options will restart", file=out)
|
|
170
|
+
else:
|
|
171
|
+
os.kill(state["pid"], signal.SIGHUP)
|
|
172
|
+
print("configuration reload requested; changed options apply on the next restart", file=out)
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def cmd_config(cfg: Config, args, env, out) -> int:
|
|
177
|
+
if args.action == "show":
|
|
178
|
+
print(dumps_json(cfg), file=out)
|
|
179
|
+
elif args.action == "check":
|
|
180
|
+
print(f"configuration ok: {cfg.paths.config_file}"
|
|
181
|
+
+ ("" if cfg.paths.config_file.exists() else " (not found, using defaults)"), file=out)
|
|
182
|
+
else:
|
|
183
|
+
file = cfg.paths.config_file
|
|
184
|
+
if file.exists() and not args.force:
|
|
185
|
+
raise CliError(f"{file} already exists (use --force to overwrite)")
|
|
186
|
+
file.parent.mkdir(parents=True, exist_ok=True)
|
|
187
|
+
file.write_text(example_config(), encoding="utf-8")
|
|
188
|
+
print(f"wrote {file}", file=out)
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def cmd_doctor(cfg: Config, args, env, out) -> int:
|
|
193
|
+
return doctor.report(doctor.checks(cfg, env), out)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def confirm(question: str, stdin) -> bool:
|
|
197
|
+
if not stdin.isatty():
|
|
198
|
+
raise CliError("confirmation needed: run it in a terminal or add --yes", 2)
|
|
199
|
+
print(f"{question} [y/N] ", end="", flush=True)
|
|
200
|
+
return stdin.readline().strip().lower() in ("y", "yes")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def cmd_service(cfg: Config, args, env, out, stdin=None) -> int:
|
|
204
|
+
if args.action == "install":
|
|
205
|
+
config = cfg.paths.config_file if args.config_explicit else None
|
|
206
|
+
return service.install(env, out, path_env=args.path, config=config, start=not args.no_start)
|
|
207
|
+
if args.action == "uninstall":
|
|
208
|
+
if not args.purge:
|
|
209
|
+
return service.uninstall(env, out)
|
|
210
|
+
config_dir = default_config_path(env).parent
|
|
211
|
+
state_dir = cfg.paths.state_file.parent
|
|
212
|
+
listed = ", ".join(str(p) for p in (config_dir, state_dir) if p.exists()) or "nothing else"
|
|
213
|
+
if not args.yes and not confirm(f"Uninstall the service and remove {listed}?", stdin or sys.stdin):
|
|
214
|
+
raise CliError("cancelled")
|
|
215
|
+
if args.config_explicit and not cfg.paths.config_file.is_relative_to(config_dir):
|
|
216
|
+
print(f"kept {cfg.paths.config_file} (outside {config_dir})", file=out)
|
|
217
|
+
# The configuration goes first: uninstalling from a served session ends this command.
|
|
218
|
+
service.purge([config_dir], out)
|
|
219
|
+
code = service.uninstall(env, out)
|
|
220
|
+
service.purge([state_dir], out)
|
|
221
|
+
return code
|
|
222
|
+
return service.passthrough(args.action, getattr(args, "follow", False), everything=getattr(args, "all", False))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def cmd_completion(cfg: Config, args, env, out) -> int:
|
|
226
|
+
if args.names:
|
|
227
|
+
try:
|
|
228
|
+
state = read_state(cfg)
|
|
229
|
+
except CliError:
|
|
230
|
+
return 0
|
|
231
|
+
print("\n".join(sorted({p["name"] for p in state.get("projects", [])})), file=out)
|
|
232
|
+
return 0
|
|
233
|
+
if args.shell is None:
|
|
234
|
+
raise CliError("give a shell: bash or zsh", 2)
|
|
235
|
+
print(completion.script(args.shell, build_parser()), file=out, end="")
|
|
236
|
+
return 0
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
STATE_ONLY_COMMANDS = ("status", "restart", "completion")
|
|
240
|
+
|
|
241
|
+
COMMANDS = {
|
|
242
|
+
"run": cmd_run, "status": cmd_status, "list": cmd_list, "enable": cmd_toggle, "disable": cmd_toggle,
|
|
243
|
+
"restart": cmd_restart, "reload": cmd_reload, "config": cmd_config, "doctor": cmd_doctor,
|
|
244
|
+
"service": cmd_service, "completion": cmd_completion,
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
249
|
+
parser = argparse.ArgumentParser(
|
|
250
|
+
prog="rc-shepherd",
|
|
251
|
+
description="Keep Claude Code Remote Control servers alive for your projects.")
|
|
252
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
253
|
+
parser.add_argument("--config", type=Path,
|
|
254
|
+
help="configuration file (default: ~/.config/rc-shepherd/config.toml)")
|
|
255
|
+
sub = parser.add_subparsers(dest="cmd", required=True, metavar="command")
|
|
256
|
+
|
|
257
|
+
p = sub.add_parser("run", help="run the supervisor in the foreground (used by the service)")
|
|
258
|
+
p.add_argument("--dry-run", action="store_true", help="print the server commands and exit")
|
|
259
|
+
for name, text in (("status", "show the servers run by the supervisor"),
|
|
260
|
+
("list", "show candidate projects and why each is served or skipped")):
|
|
261
|
+
p = sub.add_parser(name, help=text)
|
|
262
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
263
|
+
for name, text in (("enable", "declare a project (or re-enable it) in the configuration"),
|
|
264
|
+
("disable", "keep a project declared but stop serving it")):
|
|
265
|
+
p = sub.add_parser(name, help=text)
|
|
266
|
+
p.add_argument("path", help="project folder")
|
|
267
|
+
p = sub.add_parser("restart", help="restart the server of a project")
|
|
268
|
+
p.add_argument("project", nargs="?", help="project name or path")
|
|
269
|
+
p.add_argument("--all", action="store_true", help="restart every server")
|
|
270
|
+
p = sub.add_parser("reload", help="reload the configuration and rediscover projects")
|
|
271
|
+
p.add_argument("--apply", action="store_true", help="also restart servers whose options changed")
|
|
272
|
+
p = sub.add_parser("config", help="show, check or create the configuration")
|
|
273
|
+
p.add_argument("action", choices=("show", "check", "init"))
|
|
274
|
+
p.add_argument("--force", action="store_true", help="init: overwrite an existing file")
|
|
275
|
+
sub.add_parser("doctor", help="check the setup")
|
|
276
|
+
p = sub.add_parser("service", help="manage the systemd user service")
|
|
277
|
+
actions = p.add_subparsers(dest="action", required=True, metavar="action")
|
|
278
|
+
i = actions.add_parser("install", help="write, enable and (re)start the user service")
|
|
279
|
+
i.add_argument("--path", help="PATH for the service and its sessions (default: the current PATH)")
|
|
280
|
+
i.add_argument("--no-start", action="store_true", help="enable without starting")
|
|
281
|
+
u = actions.add_parser("uninstall", help="stop, disable and remove the user service")
|
|
282
|
+
u.add_argument("--purge", action="store_true", help="also remove the configuration and the runtime state")
|
|
283
|
+
u.add_argument("--yes", action="store_true", help="--purge: do not ask for confirmation")
|
|
284
|
+
actions.add_parser("status", help="systemctl status")
|
|
285
|
+
logs = actions.add_parser("logs", help="recent service logs")
|
|
286
|
+
logs.add_argument("-f", "--follow", action="store_true")
|
|
287
|
+
logs.add_argument("--all", action="store_true",
|
|
288
|
+
help="also show what the sessions' own programs log (sudo, docker...)")
|
|
289
|
+
p = sub.add_parser("completion", help="print a shell completion script")
|
|
290
|
+
p.add_argument("shell", nargs="?", choices=completion.SHELLS)
|
|
291
|
+
p.add_argument("--names", action="store_true", help=argparse.SUPPRESS)
|
|
292
|
+
return parser
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def main(argv: list[str] | None = None, env: dict[str, str] | None = None, out=None) -> int:
|
|
296
|
+
env = dict(os.environ) if env is None else env
|
|
297
|
+
out = sys.stdout if out is None else out
|
|
298
|
+
args = build_parser().parse_args(argv)
|
|
299
|
+
args.config_explicit = args.config is not None
|
|
300
|
+
try:
|
|
301
|
+
cfg = load_config(args.config, env)
|
|
302
|
+
except ConfigError as exc:
|
|
303
|
+
print(f"invalid configuration: {exc}", file=sys.stderr)
|
|
304
|
+
if args.cmd not in STATE_ONLY_COMMANDS:
|
|
305
|
+
return service.CONFIG_EXIT
|
|
306
|
+
# These commands only talk to the running supervisor: keep them usable.
|
|
307
|
+
cfg = load_config(None, {**env, "XDG_CONFIG_HOME": "/nonexistent"})
|
|
308
|
+
cfg.paths.config_file = args.config or default_config_path(env)
|
|
309
|
+
try:
|
|
310
|
+
return COMMANDS[args.cmd](cfg, args, env, out)
|
|
311
|
+
except CliError as exc:
|
|
312
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
313
|
+
return exc.code
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Shell completion scripts, generated from the argument parser so they never drift."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
|
|
7
|
+
SHELLS = ("bash", "zsh")
|
|
8
|
+
# Positional arguments completed by the shell rather than from a word list.
|
|
9
|
+
DIRECTORY_ARGS = ("enable", "disable")
|
|
10
|
+
PROJECT_ARGS = ("restart",)
|
|
11
|
+
|
|
12
|
+
BASH_TEMPLATE = """\
|
|
13
|
+
# bash completion for rc-shepherd (generated by `rc-shepherd completion bash`)
|
|
14
|
+
_rc_shepherd() {{
|
|
15
|
+
local cur prev cmd="" sub="" words="" i w
|
|
16
|
+
cur="${{COMP_WORDS[COMP_CWORD]}}"
|
|
17
|
+
prev="${{COMP_WORDS[COMP_CWORD-1]}}"
|
|
18
|
+
for ((i = 1; i < COMP_CWORD; i++)); do
|
|
19
|
+
w="${{COMP_WORDS[i]}}"
|
|
20
|
+
case "$w" in
|
|
21
|
+
{value_options}) ((i++)) ;;
|
|
22
|
+
-*) ;;
|
|
23
|
+
*) if [[ -z $cmd ]]; then cmd=$w; elif [[ -z $sub ]]; then sub=$w; fi ;;
|
|
24
|
+
esac
|
|
25
|
+
done
|
|
26
|
+
case "$prev" in
|
|
27
|
+
--config) COMPREPLY=($(compgen -f -- "$cur")); return ;;
|
|
28
|
+
{value_options}) COMPREPLY=(); return ;;
|
|
29
|
+
esac
|
|
30
|
+
case "$cmd" in
|
|
31
|
+
{cases}
|
|
32
|
+
esac
|
|
33
|
+
COMPREPLY=($(compgen -W "$words" -- "$cur"))
|
|
34
|
+
if [[ $cur != -* ]]; then
|
|
35
|
+
case "$cmd" in
|
|
36
|
+
{directory_args}) COMPREPLY+=($(compgen -d -- "$cur")) ;;
|
|
37
|
+
{project_args})
|
|
38
|
+
# Project names are folder names: match them literally, never through
|
|
39
|
+
# compgen -W, which would expand $(...) inside a name.
|
|
40
|
+
while IFS= read -r w; do
|
|
41
|
+
[[ -n $w && $w == "$cur"* ]] && COMPREPLY+=("$w")
|
|
42
|
+
done < <("${{COMP_WORDS[0]}}" completion --names 2>/dev/null) ;;
|
|
43
|
+
esac
|
|
44
|
+
fi
|
|
45
|
+
}}
|
|
46
|
+
complete -o filenames -F _rc_shepherd rc-shepherd
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
ZSH_PREFIX = """\
|
|
50
|
+
# zsh completion for rc-shepherd (generated by `rc-shepherd completion zsh`)
|
|
51
|
+
autoload -U +X compinit && compinit
|
|
52
|
+
autoload -U +X bashcompinit && bashcompinit
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _subparsers(parser: argparse.ArgumentParser) -> dict[str, argparse.ArgumentParser]:
|
|
57
|
+
for action in parser._actions:
|
|
58
|
+
if isinstance(action, argparse._SubParsersAction):
|
|
59
|
+
return dict(action.choices)
|
|
60
|
+
return {}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _words(parser: argparse.ArgumentParser) -> list[str]:
|
|
64
|
+
"""Options and positional choices of one (sub)command."""
|
|
65
|
+
words: list[str] = []
|
|
66
|
+
for action in parser._actions:
|
|
67
|
+
if action.help == argparse.SUPPRESS or isinstance(action, argparse._SubParsersAction):
|
|
68
|
+
continue
|
|
69
|
+
words += action.option_strings
|
|
70
|
+
if not action.option_strings and action.choices:
|
|
71
|
+
words += list(action.choices)
|
|
72
|
+
return words
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _value_options(parser: argparse.ArgumentParser) -> set[str]:
|
|
76
|
+
found = set()
|
|
77
|
+
for action in parser._actions:
|
|
78
|
+
if action.option_strings and action.nargs != 0 and action.help != argparse.SUPPRESS:
|
|
79
|
+
found.update(o for o in action.option_strings if o.startswith("--"))
|
|
80
|
+
for sub in _subparsers(parser).values():
|
|
81
|
+
found |= _value_options(sub)
|
|
82
|
+
return found
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def bash_script(parser: argparse.ArgumentParser) -> str:
|
|
86
|
+
commands = _subparsers(parser)
|
|
87
|
+
lines = [f' "") words="{" ".join([*commands, *_words(parser)])}" ;;']
|
|
88
|
+
for name, sub in commands.items():
|
|
89
|
+
nested = _subparsers(sub)
|
|
90
|
+
if not nested:
|
|
91
|
+
lines.append(f' {name}) words="{" ".join(_words(sub))}" ;;')
|
|
92
|
+
continue
|
|
93
|
+
lines.append(f" {name})")
|
|
94
|
+
lines.append(' case "$sub" in')
|
|
95
|
+
lines.append(f' "") words="{" ".join([*nested, *_words(sub)])}" ;;')
|
|
96
|
+
for action, nested_parser in nested.items():
|
|
97
|
+
lines.append(f' {action}) words="{" ".join(_words(nested_parser))}" ;;')
|
|
98
|
+
lines.append(" esac ;;")
|
|
99
|
+
return BASH_TEMPLATE.format(
|
|
100
|
+
value_options="|".join(sorted(_value_options(parser))),
|
|
101
|
+
cases="\n".join(lines),
|
|
102
|
+
directory_args="|".join(DIRECTORY_ARGS),
|
|
103
|
+
project_args="|".join(PROJECT_ARGS),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def script(shell: str, parser: argparse.ArgumentParser) -> str:
|
|
108
|
+
text = bash_script(parser)
|
|
109
|
+
return ZSH_PREFIX + text if shell == "zsh" else text
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# rc-shepherd configuration
|
|
2
|
+
# Location: ~/.config/rc-shepherd/config.toml (or pass --config)
|
|
3
|
+
# Every key is optional; the values below are the defaults unless noted.
|
|
4
|
+
# Apply changes with `rc-shepherd reload` (add --apply to restart servers
|
|
5
|
+
# whose options changed; otherwise they pick them up on their next restart).
|
|
6
|
+
|
|
7
|
+
[discovery]
|
|
8
|
+
# "auto": serve the projects Claude Code knows (~/.claude.json) below `roots`,
|
|
9
|
+
# plus any [[project]] below. "list": serve only the [[project]] entries.
|
|
10
|
+
mode = "auto"
|
|
11
|
+
# Folders that may hold projects (a root itself is never served). Narrow it,
|
|
12
|
+
# e.g. ["~/projects", "~/work"], to serve only some of them.
|
|
13
|
+
roots = ["~"]
|
|
14
|
+
# How many levels below each root a project may be (0 = any depth). A depth
|
|
15
|
+
# above 0 also lists the folders found under the roots, even unknown to Claude.
|
|
16
|
+
# Folders inside hidden ones (.claude/worktrees, .cache...) are never served.
|
|
17
|
+
# The home folder itself is never served: Claude Code never saves its trust,
|
|
18
|
+
# so Remote Control refuses to run there. Use a trusted folder such as ~/hub.
|
|
19
|
+
depth = 0
|
|
20
|
+
# Remote Control cannot answer the folder trust prompt without a terminal:
|
|
21
|
+
# run `claude` once in a folder to trust it.
|
|
22
|
+
require_trust = true
|
|
23
|
+
# Only serve folders that already have Claude sessions (transcripts).
|
|
24
|
+
require_history = true
|
|
25
|
+
# Skip projects with no session newer than this ("" = no limit), e.g. "30d".
|
|
26
|
+
active_within = ""
|
|
27
|
+
# Glob patterns matched on the folder name, or on the full path when the
|
|
28
|
+
# pattern contains "/" or starts with "~". When `allow` is not empty, only
|
|
29
|
+
# matching projects are served. `deny` always wins over `allow`.
|
|
30
|
+
allow = []
|
|
31
|
+
deny = []
|
|
32
|
+
interval = "60s"
|
|
33
|
+
# Maximum number of servers (0 = unlimited); the most recently active win.
|
|
34
|
+
max_servers = 0
|
|
35
|
+
|
|
36
|
+
[defaults]
|
|
37
|
+
# Options for every server. Any of them can be overridden per [[project]].
|
|
38
|
+
# "" keeps this machine's Claude Code settings. Otherwise one of: default,
|
|
39
|
+
# acceptEdits, auto, dontAsk, plan, bypassPermissions (the last one also
|
|
40
|
+
# needs allow_bypass = true).
|
|
41
|
+
permission_mode = ""
|
|
42
|
+
# "same-dir": new sessions share the project folder.
|
|
43
|
+
# "worktree": each new session gets its own git worktree.
|
|
44
|
+
spawn = "same-dir"
|
|
45
|
+
# Maximum concurrent sessions per project.
|
|
46
|
+
capacity = 32
|
|
47
|
+
# Settings file passed with --settings (keep it where sessions cannot write).
|
|
48
|
+
settings = ""
|
|
49
|
+
# Claude in Chrome for new sessions: "" (machine setting), "on" or "off".
|
|
50
|
+
chrome = ""
|
|
51
|
+
# Name shown in the Claude apps. Fields: {name}, {parent}, {host}.
|
|
52
|
+
name_template = "{name}"
|
|
53
|
+
# Extra arguments appended to `claude remote-control`.
|
|
54
|
+
extra_args = []
|
|
55
|
+
# Extra environment variables for the server and its sessions.
|
|
56
|
+
env = {}
|
|
57
|
+
|
|
58
|
+
# Declare projects explicitly: the list itself in "list" mode; in "auto"
|
|
59
|
+
# mode they are served even outside the roots or filters, and their options
|
|
60
|
+
# override [defaults].
|
|
61
|
+
# [[project]]
|
|
62
|
+
# path = "~/projects/my-app"
|
|
63
|
+
# spawn = "worktree"
|
|
64
|
+
# permission_mode = "acceptEdits"
|
|
65
|
+
# enabled = false # keep the entry but stop serving it
|
|
66
|
+
|
|
67
|
+
[supervisor]
|
|
68
|
+
restart_backoff = { base = "5s", max = "5m", healthy_after = "10m" }
|
|
69
|
+
# Time a server gets to exit after SIGTERM before SIGKILL.
|
|
70
|
+
stop_timeout = "10s"
|
|
71
|
+
# Do not start a new server while MemAvailable is below this (0 = no check).
|
|
72
|
+
min_free_memory = 0
|
|
73
|
+
# Command run (without a shell) after `on_failure_after` failures in a row.
|
|
74
|
+
# It also runs at once when a server stops because the Claude login is
|
|
75
|
+
# missing or expired. Placeholders: {name} {path} {code} {failures}
|
|
76
|
+
# {reason} ("login" or "exit"). Example:
|
|
77
|
+
# on_failure = "notify-send 'rc-shepherd' '{name} failed {failures} times'"
|
|
78
|
+
on_failure = ""
|
|
79
|
+
on_failure_after = 3
|
|
80
|
+
claude_bin = "claude"
|
|
81
|
+
# After a Claude Code update, "idle" restarts each server on the new version
|
|
82
|
+
# once its sessions are idle: none runs a command and none of their
|
|
83
|
+
# transcripts changed for `idle_after`. Idle sessions reattach on their own.
|
|
84
|
+
# "off" waits for `rc-shepherd restart`.
|
|
85
|
+
restart_on_update = "idle"
|
|
86
|
+
idle_after = "30m"
|
|
87
|
+
# "text" or "json" (one JSON object per line).
|
|
88
|
+
log_format = "text"
|