claudown 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.
claudown/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """claudown: zero-token guard for Claude's 5-hour usage limit.
2
+
3
+ When installed with pip, this folder becomes the `claudown` package. The same
4
+ files also run directly as scripts (python scripts/<name>.py) and as Claude
5
+ Code hooks copied to ~/.claude/claudown/.
6
+ """
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1,323 @@
1
+ """Shared helpers for claudown (config, paths, state, trigger lock, logging).
2
+
3
+ Zero-token by design: this module never imports an HTTP client, the Anthropic
4
+ SDK, or anything that opens a socket. Everything it knows comes from stdin,
5
+ environment variables and small JSON files under the Claude config directory.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any, Dict, Optional, Tuple
17
+
18
+ VERSION = "0.1.0"
19
+ NAME = "claudown"
20
+ WINDOW_SECONDS = 5 * 60 * 60 # Claude's rolling 5-hour usage window
21
+
22
+ DEFAULTS: Dict[str, str] = {
23
+ "SHUTDOWN_THRESHOLD": "95", # percent of the 5-hour window
24
+ "DRY_RUN": "true", # armed ONLY when explicitly "false"
25
+ "ACTION": "auto", # auto | shutdown | notify | both | none
26
+ "BLOCK_TOOLS": "true", # gate blocks tool calls/prompts at threshold
27
+ "BACKSTOP_ENABLED": "true", # StopFailure(rate_limit) triggers the action
28
+ "SHUTDOWN_DELAY_SECONDS": "0",
29
+ "SHUTDOWN_COMMAND": "", # optional full override, e.g. "systemctl suspend"
30
+ "WEBHOOK_URL": "", # web surface: where the cloud watcher POSTs
31
+ "WEBHOOK_TOKEN": "", # shared secret checked by local_webhook_listener
32
+ "WEBHOOK_FORMAT": "json", # json | text (text suits ntfy-style endpoints)
33
+ "WEB_POLL_SECONDS": "30", # web_limit_watcher polling interval
34
+ "SENSOR_STALE_SECONDS": "900", # older sensor data -> use transcript sensor
35
+ "TOKEN_BUDGET_5H": "", # transcript sensor: weighted tokens = 100 %
36
+ "CACHE_READ_WEIGHT": "0.1", # transcript sensor: weight of cache-read tokens
37
+ "STATUSLINE_CHAIN_COMMAND": "", # optional: keep your previous status line
38
+ "COMPUTER_USE_SHUTDOWN": "false", # optional macOS CLI path, see cli_computer_use_shutdown.py
39
+ }
40
+
41
+ TRUTHY = {"1", "true", "yes", "on", "y"}
42
+ FALSY = {"0", "false", "no", "off", "n"}
43
+
44
+
45
+ # --------------------------------------------------------------------------- paths
46
+ def claude_dir() -> Path:
47
+ """Claude Code's config directory (honours CLAUDE_CONFIG_DIR)."""
48
+ custom = os.environ.get("CLAUDE_CONFIG_DIR")
49
+ return Path(custom).expanduser() if custom else Path.home() / ".claude"
50
+
51
+
52
+ def state_path() -> Path:
53
+ return claude_dir() / "claudown_state.json"
54
+
55
+
56
+ def lock_path() -> Path:
57
+ return claude_dir() / "claudown_trigger.json"
58
+
59
+
60
+ def log_path() -> Path:
61
+ return claude_dir() / "claudown.log"
62
+
63
+
64
+ def disabled_flag_path() -> Path:
65
+ return claude_dir() / "claudown.disabled"
66
+
67
+
68
+ def install_dir() -> Path:
69
+ return claude_dir() / "claudown"
70
+
71
+
72
+ def config_file_path() -> Path:
73
+ return install_dir() / "config.json"
74
+
75
+
76
+ # -------------------------------------------------------------------------- config
77
+ _config_cache: Optional[Dict[str, Any]] = None
78
+
79
+
80
+ def _file_config() -> Dict[str, Any]:
81
+ global _config_cache
82
+ if _config_cache is None:
83
+ _config_cache = {}
84
+ candidates = [config_file_path()]
85
+ project = os.environ.get("CLAUDE_PROJECT_DIR")
86
+ if project:
87
+ candidates.insert(0, Path(project) / ".claude" / "claudown" / "config.json")
88
+ for path in candidates:
89
+ data = read_json(path)
90
+ if isinstance(data, dict):
91
+ _config_cache = data
92
+ break
93
+ return _config_cache
94
+
95
+
96
+ def cfg(key: str) -> str:
97
+ """Precedence: environment variable > config.json > built-in default."""
98
+ if key in os.environ and os.environ[key] != "":
99
+ return os.environ[key]
100
+ val = _file_config().get(key)
101
+ if val is not None and str(val) != "":
102
+ return str(val).lower() if isinstance(val, bool) else str(val)
103
+ return DEFAULTS.get(key, "")
104
+
105
+
106
+ def cfg_float(key: str) -> Optional[float]:
107
+ try:
108
+ return float(cfg(key))
109
+ except (TypeError, ValueError):
110
+ return None
111
+
112
+
113
+ def cfg_bool(key: str) -> bool:
114
+ return cfg(key).strip().lower() in TRUTHY
115
+
116
+
117
+ def is_dry_run() -> bool:
118
+ """Safe default: anything other than an explicit false value is a dry run."""
119
+ return cfg("DRY_RUN").strip().lower() not in FALSY
120
+
121
+
122
+ def threshold() -> float:
123
+ val = cfg_float("SHUTDOWN_THRESHOLD")
124
+ if val is None or not (0 < val <= 100):
125
+ return 95.0
126
+ return val
127
+
128
+
129
+ def is_remote() -> bool:
130
+ """True inside Claude Code on the web (cloud VM)."""
131
+ return os.environ.get("CLAUDE_CODE_REMOTE", "").lower() == "true"
132
+
133
+
134
+ def is_disabled() -> bool:
135
+ return disabled_flag_path().exists() or os.environ.get("CLAUDOWN_DISABLE", "") in TRUTHY
136
+
137
+
138
+ # ---------------------------------------------------------------------------- I/O
139
+ def utf8_stdio() -> None:
140
+ """Windows consoles and pipes default to a legacy code page; force UTF-8 so
141
+ status text with symbols never crashes a hook."""
142
+ for stream in (sys.stdout, sys.stderr):
143
+ try:
144
+ stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]
145
+ except Exception:
146
+ pass
147
+
148
+
149
+ def read_json(path: Path) -> Optional[Any]:
150
+ try:
151
+ with open(path, "r", encoding="utf-8") as fh:
152
+ return json.load(fh)
153
+ except (OSError, ValueError):
154
+ return None
155
+
156
+
157
+ def write_json_atomic(path: Path, data: Any) -> None:
158
+ path.parent.mkdir(parents=True, exist_ok=True)
159
+ fd, tmp = tempfile.mkstemp(prefix=".claudown_", suffix=".tmp", dir=str(path.parent))
160
+ try:
161
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
162
+ json.dump(data, fh, indent=2, sort_keys=True)
163
+ os.replace(tmp, path)
164
+ except Exception:
165
+ try:
166
+ os.unlink(tmp)
167
+ except OSError:
168
+ pass
169
+ raise
170
+
171
+
172
+ def read_stdin_json() -> Dict[str, Any]:
173
+ try:
174
+ raw = sys.stdin.read()
175
+ except Exception:
176
+ return {}
177
+ if not raw or not raw.strip():
178
+ return {}
179
+ try:
180
+ data = json.loads(raw)
181
+ return data if isinstance(data, dict) else {}
182
+ except ValueError:
183
+ return {}
184
+
185
+
186
+ def log(message: str) -> None:
187
+ line = f"{time.strftime('%Y-%m-%d %H:%M:%S')} [claudown] {message}\n"
188
+ try:
189
+ p = log_path()
190
+ p.parent.mkdir(parents=True, exist_ok=True)
191
+ with open(p, "a", encoding="utf-8") as fh:
192
+ fh.write(line)
193
+ except OSError:
194
+ pass
195
+
196
+
197
+ # --------------------------------------------------------------------------- state
198
+ def load_state() -> Dict[str, Any]:
199
+ data = read_json(state_path())
200
+ return data if isinstance(data, dict) else {}
201
+
202
+
203
+ def update_state(**fields: Any) -> None:
204
+ """Merge a few keys into the state file (best effort)."""
205
+ st = load_state()
206
+ st.update(fields)
207
+ try:
208
+ write_json_atomic(state_path(), st)
209
+ except OSError as exc:
210
+ log(f"could not update state: {exc!r}")
211
+
212
+
213
+ def to_float(value: Any) -> Optional[float]:
214
+ try:
215
+ if value is None or isinstance(value, bool):
216
+ return None
217
+ return float(value)
218
+ except (TypeError, ValueError):
219
+ return None
220
+
221
+
222
+ def sensor_reading(now: Optional[float] = None) -> Tuple[Optional[float], Optional[float], str]:
223
+ """Return (percent, resets_at, status) from the statusLine sensor's state file.
224
+
225
+ status is one of: fresh, expired-window, stale, no-data.
226
+ """
227
+ now = time.time() if now is None else now
228
+ st = load_state()
229
+ pct = to_float(st.get("five_hour_pct"))
230
+ resets_at = to_float(st.get("five_hour_resets_at"))
231
+ updated = to_float(st.get("updated_at"))
232
+ if pct is None or updated is None:
233
+ return None, None, "no-data"
234
+ if resets_at is not None and now >= resets_at:
235
+ # The window the reading belonged to is over; usage has rolled back.
236
+ return 0.0, None, "expired-window"
237
+ stale_after = cfg_float("SENSOR_STALE_SECONDS") or 900.0
238
+ if now - updated > stale_after:
239
+ return pct, resets_at, "stale"
240
+ return pct, resets_at, "fresh"
241
+
242
+
243
+ def _transcript_module():
244
+ try:
245
+ from . import vscode_transcript_sensor as mod # installed as the claudown package
246
+ except ImportError:
247
+ import vscode_transcript_sensor as mod # run from the scripts folder
248
+ return mod
249
+
250
+
251
+ def effective_usage(now: Optional[float] = None) -> Dict[str, Any]:
252
+ """Best local estimate of 5-hour usage. statusLine sensor first, transcripts second.
253
+
254
+ Returns a dict: pct (float|None), resets_at (float|None), source (str).
255
+ """
256
+ now = time.time() if now is None else now
257
+ pct, resets_at, status = sensor_reading(now)
258
+ if status in ("fresh", "expired-window"):
259
+ return {"pct": pct, "resets_at": resets_at, "source": f"statusline:{status}"}
260
+
261
+ # statusLine silent or stale (the native VS Code panel never runs it): read transcripts.
262
+ try:
263
+ est = _transcript_module().estimate(now=now)
264
+ except Exception as exc: # never let the fallback crash a hook
265
+ log(f"transcript sensor failed: {exc!r}")
266
+ est = {"pct": None}
267
+ if est.get("pct") is not None:
268
+ return {
269
+ "pct": est["pct"],
270
+ "resets_at": est.get("resets_at"),
271
+ "source": f"transcript:{est.get('basis', 'estimate')}",
272
+ }
273
+ if status == "stale" and pct is not None:
274
+ # Stale but within its window: better than nothing, flagged as such.
275
+ return {"pct": pct, "resets_at": resets_at, "source": "statusline:stale"}
276
+ return {"pct": None, "resets_at": None, "source": f"unknown:{est.get('basis', 'no-data')}"}
277
+
278
+
279
+ # ---------------------------------------------------------------- trigger lock
280
+ def active_lock(now: Optional[float] = None) -> Optional[Dict[str, Any]]:
281
+ """Return the trigger lock if it still covers the current window, else None."""
282
+ now = time.time() if now is None else now
283
+ data = read_json(lock_path())
284
+ if not isinstance(data, dict):
285
+ return None
286
+ resets_at = to_float(data.get("window_resets_at"))
287
+ triggered_at = to_float(data.get("triggered_at")) or 0.0
288
+ if resets_at is not None:
289
+ return data if now < resets_at else None
290
+ return data if now - triggered_at < WINDOW_SECONDS else None
291
+
292
+
293
+ def acquire_lock(info: Dict[str, Any], now: Optional[float] = None) -> bool:
294
+ """Atomically create the trigger lock. False if a live lock already exists."""
295
+ now = time.time() if now is None else now
296
+ path = lock_path()
297
+ path.parent.mkdir(parents=True, exist_ok=True)
298
+ if path.exists() and active_lock(now) is None:
299
+ try:
300
+ path.unlink() # expired lock from a previous window
301
+ except OSError:
302
+ pass
303
+ payload = dict(info)
304
+ payload.setdefault("triggered_at", now)
305
+ try:
306
+ fd = os.open(str(path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
307
+ except FileExistsError:
308
+ return False
309
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
310
+ json.dump(payload, fh, indent=2, sort_keys=True)
311
+ return True
312
+
313
+
314
+ def release_lock() -> bool:
315
+ try:
316
+ lock_path().unlink()
317
+ return True
318
+ except OSError:
319
+ return False
320
+
321
+
322
+ def script_dir() -> Path:
323
+ return Path(__file__).resolve().parent
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env python3
2
+ """claudown installer - works on Windows, macOS and Linux (no bash needed).
3
+
4
+ python scripts/claudown_setup.py install for you (~/.claude), DRY RUN
5
+ python scripts/claudown_setup.py --threshold 90 custom threshold (percent)
6
+ python scripts/claudown_setup.py --arm install ARMED (DRY_RUN=false): really shuts down
7
+ python scripts/claudown_setup.py --project PATH install into a repo's .claude/ (Claude Code on the web)
8
+ python scripts/claudown_setup.py --uninstall [--project PATH]
9
+
10
+ Your existing settings.json is backed up and merged, never replaced. A status
11
+ line you already had is kept and shown above the claudown line.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import shlex
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any, Dict, List, Optional
26
+
27
+ try:
28
+ from . import claudown_common as c
29
+ except ImportError:
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+ import claudown_common as c # noqa: E402
32
+
33
+ SRC = Path(__file__).resolve().parent
34
+ OUR_SCRIPTS = ("statusline_sensor.py", "pretooluse_gate.py", "shutdown_orchestrator.py",
35
+ "web_limit_watcher.py")
36
+ ENV_KEYS = ("SHUTDOWN_THRESHOLD", "DRY_RUN", "ACTION")
37
+
38
+
39
+ def is_ours(cmd: Any) -> bool:
40
+ s = str(cmd or "").replace("\\", "/")
41
+ return "claudown/" in s and any(name in s for name in OUR_SCRIPTS)
42
+
43
+
44
+ def strip_ours(hooks: Dict[str, Any]) -> Dict[str, Any]:
45
+ for event in list(hooks):
46
+ groups = []
47
+ for g in hooks[event] or []:
48
+ g = dict(g)
49
+ g["hooks"] = [h for h in g.get("hooks", []) if not is_ours(h.get("command"))]
50
+ if g["hooks"]:
51
+ groups.append(g)
52
+ if groups:
53
+ hooks[event] = groups
54
+ else:
55
+ del hooks[event]
56
+ return hooks
57
+
58
+
59
+ def _win_short(path: str) -> str:
60
+ """8.3 short path (no spaces) so the command works in Git Bash AND PowerShell."""
61
+ try:
62
+ import ctypes
63
+
64
+ buf = ctypes.create_unicode_buffer(1024)
65
+ if ctypes.windll.kernel32.GetShortPathNameW(path, buf, 1024): # type: ignore[attr-defined]
66
+ return buf.value
67
+ except Exception:
68
+ pass
69
+ return path
70
+
71
+
72
+ def shell_path(path: Path) -> str:
73
+ p = str(path)
74
+ if os.name == "nt":
75
+ if " " in p:
76
+ p = _win_short(p)
77
+ p = p.replace("\\", "/")
78
+ return f'"{p}"' if " " in p else p
79
+ return shlex.quote(p)
80
+
81
+
82
+ def command_builder(project: bool, target: Path, python: str):
83
+ if project:
84
+ # Cloud sessions are Linux with python3; paths are relative to the repo.
85
+ return lambda name: f'python3 "$CLAUDE_PROJECT_DIR/.claude/claudown/{name}"'
86
+ py = shell_path(Path(python))
87
+ return lambda name: f"{py} {shell_path(target / name)}"
88
+
89
+
90
+ def install_files(target: Path) -> None:
91
+ target.mkdir(parents=True, exist_ok=True)
92
+ for f in list(SRC.glob("*.py")) + list(SRC.glob("*.sh")):
93
+ shutil.copy2(f, target / f.name)
94
+ if os.name != "nt":
95
+ os.chmod(target / f.name, 0o755)
96
+
97
+
98
+ def merge(settings: Path, target: Path, args: argparse.Namespace, project: bool) -> Dict[str, Any]:
99
+ data: Dict[str, Any] = {}
100
+ if settings.exists():
101
+ try:
102
+ data = json.loads(settings.read_text(encoding="utf-8") or "{}")
103
+ except ValueError:
104
+ raise SystemExit(f"{settings} is not valid JSON; fix it first (nothing was changed).")
105
+ backup = settings.with_name(f"settings.json.bak.{int(time.time())}")
106
+ shutil.copy2(settings, backup)
107
+ print(f"Backed up your existing settings to {backup}")
108
+
109
+ conf_path = target / "config.json"
110
+ conf: Dict[str, Any] = c.read_json(conf_path) or {}
111
+ hooks = strip_ours(data.get("hooks") or {})
112
+ sl = data.get("statusLine")
113
+
114
+ if args.uninstall:
115
+ if isinstance(sl, dict) and is_ours(sl.get("command")):
116
+ chained = conf.get("STATUSLINE_CHAIN_COMMAND")
117
+ if chained:
118
+ data["statusLine"] = {"type": "command", "command": chained}
119
+ else:
120
+ data.pop("statusLine", None)
121
+ env = data.get("env") or {}
122
+ for k in ENV_KEYS:
123
+ env.pop(k, None)
124
+ data["env"] = env
125
+ if not env:
126
+ data.pop("env")
127
+ data["hooks"] = hooks
128
+ if not hooks:
129
+ data.pop("hooks")
130
+ settings.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
131
+ if target.exists():
132
+ shutil.rmtree(target)
133
+ print("claudown removed. Its log and state files in the .claude folder were left for you.")
134
+ return data
135
+
136
+ q = command_builder(project, target, args.python)
137
+ if isinstance(sl, dict) and sl.get("command") and not is_ours(sl.get("command")):
138
+ conf["STATUSLINE_CHAIN_COMMAND"] = sl["command"]
139
+ print(f"Kept your existing status line (shown above claudown's): {sl['command']}")
140
+ data["statusLine"] = {"type": "command", "command": q("statusline_sensor.py"), "refreshInterval": 60}
141
+
142
+ hooks.setdefault("PreToolUse", []).append(
143
+ {"matcher": "*", "hooks": [{"type": "command", "command": q("pretooluse_gate.py"), "timeout": 30}]})
144
+ hooks.setdefault("UserPromptSubmit", []).append(
145
+ {"hooks": [{"type": "command", "command": q("pretooluse_gate.py"), "timeout": 30}]})
146
+ hooks.setdefault("StopFailure", []).append(
147
+ {"matcher": "rate_limit",
148
+ "hooks": [{"type": "command", "command": q("shutdown_orchestrator.py"), "timeout": 60}]})
149
+ if project:
150
+ hooks.setdefault("SessionStart", []).append(
151
+ {"hooks": [{"type": "command", "command": q("web_limit_watcher.py"), "timeout": 30}]})
152
+ data["hooks"] = hooks
153
+
154
+ env = data.setdefault("env", {})
155
+ if args.threshold:
156
+ env["SHUTDOWN_THRESHOLD"] = str(args.threshold)
157
+ env.setdefault("SHUTDOWN_THRESHOLD", "95")
158
+ env["DRY_RUN"] = "false" if args.arm else env.get("DRY_RUN", "true")
159
+ env["ACTION"] = args.action or env.get("ACTION") or ("notify" if project else "auto")
160
+
161
+ if project:
162
+ print("Web setup: put WEBHOOK_URL and WEBHOOK_TOKEN in your cloud environment's "
163
+ "environment variables (never commit them). See GETTING_STARTED.md, part 2C.")
164
+ if conf:
165
+ target.mkdir(parents=True, exist_ok=True)
166
+ c.write_json_atomic(conf_path, conf)
167
+
168
+ settings.parent.mkdir(parents=True, exist_ok=True)
169
+ settings.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
170
+ print(f"Added claudown to {settings}")
171
+ print(f" threshold={env['SHUTDOWN_THRESHOLD']}% DRY_RUN={env['DRY_RUN']} ACTION={env['ACTION']}")
172
+ return data
173
+
174
+
175
+ def _main(argv: Optional[List[str]] = None) -> int:
176
+ ap = argparse.ArgumentParser(prog="claudown-setup", description=__doc__,
177
+ formatter_class=argparse.RawDescriptionHelpFormatter)
178
+ ap.add_argument("--project", metavar="PATH", help="install into PATH/.claude (for Claude Code on the web)")
179
+ ap.add_argument("--threshold", type=float, help="percent of the 5-hour window (default 95)")
180
+ ap.add_argument("--arm", action="store_true", help="DRY_RUN=false: really shut down")
181
+ ap.add_argument("--action", choices=["auto", "shutdown", "notify", "both", "none"])
182
+ ap.add_argument("--uninstall", action="store_true")
183
+ ap.add_argument("--python", default=sys.executable, help=argparse.SUPPRESS)
184
+ args = ap.parse_args(argv)
185
+ if args.threshold is not None and not (0 < args.threshold <= 100):
186
+ ap.error("--threshold must be between 1 and 100")
187
+ if args.threshold is not None:
188
+ args.threshold = f"{args.threshold:g}"
189
+
190
+ project = bool(args.project)
191
+ if project:
192
+ root = Path(args.project).expanduser().resolve()
193
+ if not root.is_dir():
194
+ print(f"Project folder not found: {root}", file=sys.stderr)
195
+ return 1
196
+ base = root / ".claude"
197
+ else:
198
+ base = c.claude_dir()
199
+ target = base / "claudown"
200
+ settings = base / "settings.json"
201
+ base.mkdir(parents=True, exist_ok=True)
202
+
203
+ if not args.uninstall:
204
+ install_files(target)
205
+ merge(settings, target, args, project)
206
+ if args.uninstall:
207
+ return 0
208
+
209
+ print("\nSelf-test (dry run, nothing is executed):")
210
+ env = dict(os.environ, DRY_RUN="true")
211
+ subprocess.run([sys.executable, str(target / "shutdown_orchestrator.py"), "--test"], env=env)
212
+ print()
213
+ if args.arm:
214
+ print("!! claudown is ARMED. At the threshold your computer WILL shut down without saving your work.")
215
+ else:
216
+ print("claudown is installed in DRY RUN mode: it only writes what it would do to "
217
+ f"{c.log_path() if not project else '.claude/claudown.log'}. Re-run with --arm to enable it.")
218
+ if project:
219
+ print(f"Commit {target} and {settings} to the repository so web sessions pick them up.")
220
+ print("Restart Claude Code (or open a new session) so the changes load.")
221
+ return 0
222
+
223
+
224
+ def main(argv: Optional[List[str]] = None) -> int:
225
+ c.utf8_stdio()
226
+ return _main(argv)
227
+
228
+
229
+ if __name__ == "__main__":
230
+ sys.exit(main())