@allansantos-dev/smart-tool 0.9.57 → 0.9.61

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,75 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.61 - beta
4
+
5
+ - Old Camoufox builds leave the user's cache. camoufox 0.5.6 installs each build in its own folder and never deletes
6
+ the previous one, so the cache grew by about 2.5 GB per build (8.2 GB on this machine, 2.5 GB of it in use). After
7
+ an update has been verified, the installer runs `web_adapters/browser/prune_camoufox.py`, which deletes the builds
8
+ of the active build's repository older than the active one and logs each removal with its size and the total freed.
9
+ It removes nothing when `pinned` is set in Camoufox's `config.json` or no build is active, and never touches the
10
+ active build, a newer one or another repository's. Each folder is renamed to a hidden name in `browsers/` before it
11
+ is deleted, which Windows refuses while a file inside is open, so a build in use is kept whole and logged; a
12
+ deletion cut short is finished on the next run. A failed pruning is reported and the update stays
13
+ (`tests/test_prune_camoufox.py`, `tests/test_install_legacy.py`). Research:
14
+ `docs/research/2026-11-04-camoufox-cache-pruning.md`.
15
+
16
+ ## 0.9.60 - beta
17
+
18
+ - A new `package-lock.json` reaches every install. `install_runtime.py` ran `npm ci` only when a parser file was
19
+ missing, so an install that already had them kept the old TypeScript, java-parser, Angular compiler and Playwright
20
+ MCP. After `npm ci` succeeds it now records the lock's SHA-256 in `node_modules/.smart-tool-lock.sha256`; a lock
21
+ that differs runs `npm ci` again, and `install_runtime.py --check` reports `node_packages: missing`, so an update
22
+ runs the dependency step for an install whose packages came from another lock, including one installed before this
23
+ version (`tests/test_install_runtime.py`). npm's own `node_modules/.package-lock.json` is not compared, because npm
24
+ ignores it whenever another tool touched the tree.
25
+ - A newer Camoufox browser build for the same library version arrives on every update. Since 0.9.59 an update whose
26
+ dependency files did not change skipped `fetch_camoufox.py`, so a new build reached an install only when one of
27
+ those files changed. When the dependency step is skipped, the installer now runs `fetch_camoufox.py` before stopping
28
+ the service. Camoufox compares the active build with the newest supported release, downloads a newer one into its
29
+ own folder and switches to it only after the SHA-256 check, so the running browser keeps its files and the stop
30
+ window does not grow. A failed download ends the update before anything was stopped or copied
31
+ (`tests/test_install_legacy.py`).
32
+
33
+ ## 0.9.59 - beta
34
+
35
+ - An update keeps open Claude Code sessions connected. The installer ran pip and `install_runtime.py` while the
36
+ service was stopped, about 48 s on a current machine, and Claude Code stops reconnecting after 5 attempts (about
37
+ 15 s), so every open session lost Smart Tool until `/mcp` (33 times in Claude Code's logs from 2026-10-02 to
38
+ 2026-11-04). After a completed update the installer records a SHA-256 of the files that decide the dependencies
39
+ (`requirements.txt`, `install_runtime.py`, `node_locator.py`, the Node `package.json` and `package-lock.json`, the
40
+ browser `requirements.txt`, `fetch_camoufox.py` and `ranged_download.py`) in `.dependencies.sha256`; the next update
41
+ whose files match skips that step and says so. A changed file, a missing record or a missing venv runs it as before,
42
+ and an update rolled back after the step leaves the old record (`tests/test_install_legacy.py`).
43
+ - A restart keeps the port the clients already know. The service tried the default port first, so a restart after
44
+ it had moved to another port went back to the default and cut every session still on the other one; it now tries
45
+ the port in the clients' configuration first, then the default, then any free port (`tests/test_endpoint_sync.py`).
46
+ - A search inside `$(...)` or `` `...` `` is judged in the folder its segment runs in. The redirect hook decided every
47
+ substitution of a command with the folder at its start, so `cd outside; echo $(grep -rn x .)` was redirected as a
48
+ search of the session folder, and a `cd` inside a substitution moved the commands after it; a substitution is now
49
+ decided with the state of its own segment, and its `cd` stays inside it (`tests/test_router.py`).
50
+ - The test files can run in one process (`python -m unittest a b ...`, as the `affected_tests` command suggests).
51
+ Classes replaced functions of shared modules in `setUpClass` without restoring them, and the gateway tests left a
52
+ user adapter folder behind, so 21 tests failed and 8 errored together while each file passed alone; the
53
+ replacements now go through `mock.patch.object` with a class cleanup (`tests/_env.py`, `patch_for_class`).
54
+ - `server/discover`, which Claude Code 2.1.316 sends before `initialize`, keeps its JSON-RPC -32601 answer: the
55
+ daemon speaks protocol 2025-06-18, and a client that gets any error other than -32022 falls back to `initialize`, as
56
+ the protocol revision that defines the method asks (`tests/test_mcp_transport.py`).
57
+
58
+ ## 0.9.58 - beta
59
+
60
+ - Claude Code no longer drops the Smart Tool connection while the service is up. `GET /mcp` and `DELETE /mcp` answer
61
+ 405 with `Allow: POST`, as the MCP Streamable HTTP transport allows for a server with no server-initiated stream and
62
+ no client-ended sessions; they answered 404, which the MCP SDK client treats as a broken connection: Claude Code's
63
+ logs held two `Failed to open SSE stream: Not Found` per connection, 4,838 between 2026-10-02 and 2026-11-04, and the
64
+ connection was later closed "with errors" and reopened. A DELETE elsewhere answers 404 instead of 501
65
+ (`tests/test_mcp_transport.py`).
66
+ - A tool call longer than a minute reaches Claude Code. Claude Code aborts an MCP request whose response has not
67
+ started within 60 s, so a long `web_search`, `web_fetch` or `smart_scout` ended in `The operation timed out.` (202
68
+ times in the same logs). A `tools/call` from a client that accepts `text/event-stream` and still running after 10 s
69
+ is answered as an SSE stream: headers at once, a comment every 15 s, and the result as its only event. A faster call,
70
+ or a client that does not accept SSE, gets the single JSON body as before (`tests/test_mcp_transport.py`; diagnosis
71
+ in `docs/research/2026-11-04-mcp-client-drops.md`).
72
+
3
73
  ## 0.9.57 - beta
4
74
 
5
75
  - Codex runs Smart Tool's hooks with no `/hooks` step. Installing or updating the Codex redirect hook or the
package/README.md CHANGED
@@ -17,7 +17,7 @@ registered as the `playwright` server where this machine lets a browser be drive
17
17
  An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
18
18
  are cheaper, or just tells the agent what Smart Tool would do.
19
19
 
20
- **Status:** 0.9.57 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
20
+ **Status:** 0.9.61 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
21
21
 
22
22
  ## How it works
23
23
 
@@ -83,7 +83,7 @@ gateway such as Ollama, nothing about your code leaves the machine.
83
83
  ## Install
84
84
 
85
85
  ```powershell
86
- npx @allansantos-dev/smart-tool@0.9.57 install
86
+ npx @allansantos-dev/smart-tool@0.9.61 install
87
87
  ```
88
88
 
89
89
  Updates install themselves, on by default: the tray checks npm when it starts (at logon) and every 24 h, and when there
package/install.py CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env python3
2
2
  import argparse
3
3
  import filecmp
4
+ import hashlib
4
5
  import json
5
6
  import os
6
7
  import re
@@ -24,6 +25,10 @@ HOOK_SCRIPTS = ("pretool_router.py", "session_audit.py")
24
25
  STARTUP_SCRIPT = Path(os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming"))) / "Microsoft" / "Windows" / \
25
26
  "Start Menu" / "Programs" / "Startup" / "SmartTool-Tray.vbs"
26
27
  MANIFEST = ".install-manifest.json"
28
+ DEPENDENCY_INPUTS = ("requirements.txt", "install_runtime.py", "node_locator.py", "web_adapters/node/package.json",
29
+ "web_adapters/node/package-lock.json", "web_adapters/browser/requirements.txt",
30
+ "web_adapters/browser/fetch_camoufox.py", "web_adapters/browser/ranged_download.py")
31
+ DEPENDENCY_STAMP = ".dependencies.sha256"
27
32
  REGISTRY = Path(paths.DATA_DIR) / "daemon.json"
28
33
  BLOCKED = {"__pycache__", ".token-guard", ".git", ".pytest_cache", ".data", ".artifacts", ".claude", ".vscode",
29
34
  ".impeccable", "tests", "sessions", "results", "dist", "node_modules", ".node-runtime", ".venv",
@@ -280,6 +285,50 @@ def restore_packages(python, frozen, backup):
280
285
  str(backup / "requirements.frozen.txt")], check=True)
281
286
 
282
287
 
288
+ def dependency_digest(root):
289
+ """SHA-256 over the DEPENDENCY_INPUTS under root: the files that decide what pip and install_runtime.py install."""
290
+ digest = hashlib.sha256()
291
+ for rel in DEPENDENCY_INPUTS:
292
+ digest.update(rel.encode("utf-8") + b"\0" + (root / rel).read_bytes() + b"\0")
293
+ return digest.hexdigest()
294
+
295
+
296
+ def runtime_complete(target, python):
297
+ """`install_runtime.py --check` of target: Node, parsers, browser packages and browsers all present. It only
298
+ reads, so it runs while the daemon is still up."""
299
+ return subprocess.run([str(python), str(target / "install_runtime.py"), "--check"], cwd=target,
300
+ capture_output=True, text=True, timeout=120).returncode == 0
301
+
302
+
303
+ def dependencies_current(target, python):
304
+ """True when the last update that completed in target ran the dependency step with the inputs this package
305
+ ships and the web runtime is still complete, so pip and install_runtime.py would change nothing. Running them
306
+ anyway keeps the daemon down for about 48 s, longer than an MCP client keeps reconnecting (Claude Code gives up
307
+ after 5 attempts, about 15 s)."""
308
+ stamp = target / DEPENDENCY_STAMP
309
+ return (python.is_file() and stamp.is_file()
310
+ and stamp.read_text(encoding="utf-8").strip() == dependency_digest(SOURCE)
311
+ and runtime_complete(target, python))
312
+
313
+
314
+ def refresh_camoufox(target):
315
+ """Runs target's `fetch_camoufox.py` while the daemon is still up, so a newer browser build for the same library
316
+ version arrives on every update. Camoufox installs each build in its own folder and switches the active one only
317
+ after the download checks out, so the running browser keeps its files; with no newer build it only looks up the
318
+ releases."""
319
+ browser = target / "web_adapters" / "browser"
320
+ subprocess.run([str(browser / ".venv" / "Scripts" / "python.exe"), str(browser / "fetch_camoufox.py")], check=True)
321
+
322
+
323
+ def prune_camoufox(target):
324
+ """Runs target's `prune_camoufox.py` after a verified update, so the Camoufox builds older than the active one leave
325
+ the user's cache. The update is already complete, so a failure is reported, not rolled back."""
326
+ browser = target / "web_adapters" / "browser"
327
+ result = subprocess.run([str(browser / ".venv" / "Scripts" / "python.exe"), str(browser / "prune_camoufox.py")])
328
+ if result.returncode:
329
+ print(f"Old Camoufox builds not pruned: prune_camoufox.py exited {result.returncode}.", file=sys.stderr)
330
+
331
+
283
332
  def install_dependencies(target, python):
284
333
  if not python.exists():
285
334
  venv.create(python.parent.parent, with_pip=True)
@@ -411,6 +460,9 @@ def prune_backups(target):
411
460
 
412
461
  def _update(args, target, files, existed, python, pythonw):
413
462
  """Replaces the installed files, dependencies and daemon, restoring the previous version on any failure."""
463
+ run_deps = not args.skip_deps and not dependencies_current(target, python)
464
+ if not args.skip_deps and not run_deps:
465
+ refresh_camoufox(target)
414
466
  stop_processes(target)
415
467
  if not args.no_start:
416
468
  wait_port_free(target)
@@ -421,10 +473,12 @@ def _update(args, target, files, existed, python, pythonw):
421
473
  copy_files(target, files, backup, changed, removed)
422
474
  clear_bytecode(target)
423
475
  print(f"Files changed: {len(changed)}; removed as obsolete: {len(removed)}")
424
- if not args.skip_deps:
476
+ if run_deps:
425
477
  frozen = freeze(python)
426
478
  deps_touched = True
427
479
  install_dependencies(target, python)
480
+ elif not args.skip_deps:
481
+ print("Dependencies unchanged since the last update; pip and install_runtime.py skipped.")
428
482
  if not args.no_start:
429
483
  mark_updating(False)
430
484
  start(target, python, pythonw)
@@ -448,7 +502,11 @@ def _update(args, target, files, existed, python, pythonw):
448
502
  raise SystemExit(1)
449
503
  shutil.rmtree(backup, ignore_errors=True)
450
504
  raise SystemExit(1)
505
+ if run_deps:
506
+ (target / DEPENDENCY_STAMP).write_text(dependency_digest(SOURCE), encoding="utf-8")
451
507
  shutil.rmtree(backup)
508
+ if not args.skip_deps and not args.no_start:
509
+ prune_camoufox(target)
452
510
 
453
511
 
454
512
  if __name__ == "__main__":
@@ -239,10 +239,39 @@ def _run_once(args, cwd, env, flags, label, idle_s, stream):
239
239
  raise RuntimeError(f"{label} failed (exit {process.returncode}): {tail[-1] if tail else 'no output'}")
240
240
 
241
241
 
242
+ def _lock_digest():
243
+ return hashlib.sha256((NODE_DIR / "package-lock.json").read_bytes()).hexdigest()
244
+
245
+
246
+ def _lock_stamp():
247
+ """Written after `npm ci` succeeds; `npm ci` deletes node_modules first, so a failed run leaves no stamp."""
248
+ return NODE_DIR / "node_modules" / ".smart-tool-lock.sha256"
249
+
250
+
251
+ def _node_packages_current():
252
+ """node_modules was installed from the package-lock.json shipped now and still holds every entry point. npm's own
253
+ hidden lockfile is not compared because npm ignores it whenever another tool touched the tree."""
254
+ try:
255
+ stamped = _lock_stamp().read_text(encoding="utf-8").strip()
256
+ except OSError:
257
+ return False
258
+ return stamped == _lock_digest() and all(path.is_file() for path in (
259
+ OPEN_WEBSEARCH_CLI, TYPESCRIPT_PARSER, JAVA_PARSER, ANGULAR_PARSER, PLAYWRIGHT_MCP_CLI))
260
+
261
+
262
+ def _install_node_packages(npm):
263
+ if _node_packages_current():
264
+ return
265
+ _run([npm, "ci", "--omit=dev", "--no-audit", "--no-fund"], cwd=NODE_DIR,
266
+ label="Web adapters and code parser via npm", idle_s=300)
267
+ _lock_stamp().write_text(_lock_digest(), encoding="utf-8")
268
+
269
+
242
270
  def _check():
243
271
  node, _npm = _node_commands()
244
272
  status = {
245
273
  "node": bool(node),
274
+ "node_packages": bool(node and _node_packages_current()),
246
275
  "open_websearch": bool(node and OPEN_WEBSEARCH_CLI.is_file()),
247
276
  "typescript_parser": bool(node and TYPESCRIPT_PARSER.is_file()),
248
277
  "java_parser":bool(node and JAVA_PARSER.is_file()),
@@ -318,10 +347,7 @@ def install(reuse_browser_runtime=None):
318
347
  if not node or not npm:
319
348
  _install_node()
320
349
  node, npm = _node_commands()
321
- if not all(path.is_file() for path in (OPEN_WEBSEARCH_CLI, TYPESCRIPT_PARSER, JAVA_PARSER, ANGULAR_PARSER,
322
- PLAYWRIGHT_MCP_CLI)):
323
- _run([npm, "ci", "--omit=dev", "--no-audit", "--no-fund"], cwd=NODE_DIR,
324
- label="Web adapters and code parser via npm", idle_s=300)
350
+ _install_node_packages(npm)
325
351
  if reuse_browser_runtime:
326
352
  existing = Path(reuse_browser_runtime).expanduser().resolve()
327
353
  if not (existing / "Scripts" / "python.exe").is_file():
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.57",
3
+ "version": "0.9.61",
4
4
  "description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Allan Santos",
package/redirect_rule.py CHANGED
@@ -404,16 +404,20 @@ def _bash(command, cwd, powershell=False):
404
404
 
405
405
 
406
406
  def _shell(command, cwd, state, powershell, depth):
407
- """(decision, target, reason) of one shell script; substitutions and `bash -c`/`powershell -Command` scripts are
408
- decided with the same state (folder, variables, loop variables)."""
407
+ """(decision, target, reason) of one shell script; `bash -c`/`powershell -Command` scripts are decided with the
408
+ same state (folder, variables, loop variables), and each substitution with the state of the segment it sits in,
409
+ as a subshell whose `cd` does not leak out."""
409
410
  verdict = ("allow", None, "No content search over a folder.")
410
411
  text, inner = _substitutions(_strip_heredocs(command), powershell)
411
- for script in inner if depth < MAX_NESTING else ():
412
- found = _shell(script, cwd, state, powershell, depth + 1)
413
- if found[0] == "redirect":
414
- return found
412
+ pending = inner if depth < MAX_NESTING else []
415
413
  variables, lists, listing = state["variables"], state["lists"], None
416
414
  for segment, after_pipe in segments(text):
415
+ count = segment.count(LISTING) + segment.count(SUBSTITUTION)
416
+ for script in pending[:count]:
417
+ found = _shell(script, cwd, {**state}, powershell, depth + 1)
418
+ if found[0] == "redirect":
419
+ return found
420
+ pending = pending[count:]
417
421
  words = _split(segment, powershell)
418
422
  if words[:2] == ["while", "read"]:
419
423
  name = next((t for t in words[2:] if not t.startswith("-")), None)
@@ -88,6 +88,10 @@ REGISTRY_PATH = os.path.join(RUN_DIR, "daemon.json")
88
88
  DEFAULT_PORT = int(os.environ.get("SMART_TOOL_PORT", "8765"))
89
89
  PROTOCOL_VERSION = "2025-06-18"
90
90
  MCP_MAX_REQUEST_BYTES = 10 * 1024 * 1024
91
+ # Claude Code aborts an MCP POST whose response has not started within 60 s; a tool call still running after
92
+ # MCP_STREAM_AFTER_S is answered as an SSE stream instead, with a comment every MCP_KEEPALIVE_S.
93
+ MCP_STREAM_AFTER_S = 10
94
+ MCP_KEEPALIVE_S = 15
91
95
  _BOUND_PORT = DEFAULT_PORT
92
96
 
93
97
  DDG_SEARCH_SCRIPT = web_search_adapters.DDG_SEARCH_SCRIPT
@@ -4211,6 +4215,16 @@ def _dispatch(method, params, session_id):
4211
4215
  raise KeyError(method)
4212
4216
 
4213
4217
 
4218
+ def _rpc_reply(method, params, session_id, req_id):
4219
+ """JSON-RPC response to one request: its result, or the error the client should see."""
4220
+ try:
4221
+ return {"jsonrpc": "2.0", "id": req_id, "result": _dispatch(method, params, session_id)}
4222
+ except KeyError:
4223
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"method not supported: {method}"}}
4224
+ except Exception as exc:
4225
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32000, "message": _sanitize_text(str(exc))}}
4226
+
4227
+
4214
4228
  _LOOPBACK_HOSTNAMES = frozenset({"127.0.0.1", "localhost", "::1"})
4215
4229
 
4216
4230
 
@@ -4350,9 +4364,31 @@ class MCPHandler(BaseHTTPRequestHandler):
4350
4364
  raise RequestTooLarge(f"Request body over {max_bytes} bytes")
4351
4365
  return self.rfile.read(length) if length else b""
4352
4366
 
4367
+ def _mcp_method_not_allowed(self):
4368
+ """405 for GET and DELETE on /mcp: no server-initiated stream and no client-ended sessions. The spec's answer for
4369
+ both; the MCP SDK client treats any other status, 404 included, as a broken connection."""
4370
+ self.send_response(405)
4371
+ self.send_header("Allow", "POST")
4372
+ self.send_header("Content-Length", "0")
4373
+ self.end_headers()
4374
+
4375
+ def do_DELETE(self):
4376
+ """Routes a DELETE: 405 on /mcp, 404 elsewhere."""
4377
+ if self._reject_foreign_origin():
4378
+ return
4379
+ if self.path == "/mcp":
4380
+ self._mcp_method_not_allowed()
4381
+ return
4382
+ self._write_json(404, {"error": "not found"})
4383
+
4353
4384
  def do_GET(self):
4385
+ """Routes a GET: 405 on /mcp, the health and status probes, the setup and project pages and their data; 404
4386
+ elsewhere."""
4354
4387
  if self._reject_foreign_origin():
4355
4388
  return
4389
+ if self.path == "/mcp":
4390
+ self._mcp_method_not_allowed()
4391
+ return
4356
4392
  if self.path == "/health":
4357
4393
  self._write_json(200, {"status": "ok", "version": version.VERSION})
4358
4394
  return
@@ -4508,17 +4544,42 @@ class MCPHandler(BaseHTTPRequestHandler):
4508
4544
  self.end_headers()
4509
4545
  return
4510
4546
 
4511
- try:
4512
- result = _dispatch(method, params, session_id)
4513
- except KeyError:
4514
- self._write_json(200, {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"method not supported: {method}"}})
4547
+ if method == "tools/call" and "text/event-stream" in (self.headers.get("Accept") or ""):
4548
+ self._answer_tool_call(params, session_id, req_id)
4515
4549
  return
4516
- except Exception as exc:
4517
- self._write_json(200, {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32000, "message": _sanitize_text(str(exc))}})
4550
+ reply = _rpc_reply(method, params, session_id, req_id)
4551
+ headers = {"Mcp-Session-Id": session_id} if method == "initialize" and "result" in reply else {}
4552
+ self._write_json(200, reply, headers)
4553
+
4554
+ def _answer_tool_call(self, params, session_id, req_id):
4555
+ """Answers a tools/call from a client that accepts SSE: one JSON body when the call ends within
4556
+ MCP_STREAM_AFTER_S, else an SSE stream started at once, a comment every MCP_KEEPALIVE_S and the reply as its
4557
+ only event. A client gone before the end leaves the call to finish unanswered, as a closed JSON request does."""
4558
+ box = {}
4559
+ worker = threading.Thread(target=lambda: box.update(reply=_rpc_reply("tools/call", params, session_id, req_id)),
4560
+ daemon=True)
4561
+ worker.start()
4562
+ worker.join(MCP_STREAM_AFTER_S)
4563
+ if not worker.is_alive():
4564
+ self._write_json(200, box["reply"])
4518
4565
  return
4519
-
4520
- headers = {"Mcp-Session-Id": session_id} if method == "initialize" else {}
4521
- self._write_json(200, {"jsonrpc": "2.0", "id": req_id, "result": result}, headers)
4566
+ try:
4567
+ self.send_response(200)
4568
+ self.send_header("Content-Type", "text/event-stream")
4569
+ self.send_header("Cache-Control", "no-store")
4570
+ self.send_header("X-Content-Type-Options", "nosniff")
4571
+ self.end_headers()
4572
+ self.wfile.flush()
4573
+ worker.join(MCP_KEEPALIVE_S)
4574
+ while worker.is_alive():
4575
+ self.wfile.write(b": keepalive\n\n")
4576
+ self.wfile.flush()
4577
+ worker.join(MCP_KEEPALIVE_S)
4578
+ event = json.dumps(box["reply"], ensure_ascii=False)
4579
+ self.wfile.write(f"event: message\ndata: {event}\n\n".encode("utf-8"))
4580
+ self.wfile.flush()
4581
+ except (ConnectionError, BrokenPipeError):
4582
+ pass
4522
4583
 
4523
4584
 
4524
4585
  def _write_registry(port):
@@ -4551,9 +4612,11 @@ def _smart_tool_answers(port):
4551
4612
 
4552
4613
 
4553
4614
  def _bind_server():
4554
- """Default port, then the port clients already know, then any free port (announced in daemon.json and synced to
4555
- the clients by endpoint_sync). A port held by another live Smart Tool stops this start instead of duplicating it."""
4556
- for port in dict.fromkeys(p for p in (DEFAULT_PORT, endpoint_sync.known_port(), 0) if p is not None):
4615
+ """The port clients already know, then the default port, then any free port (announced in daemon.json and synced
4616
+ to the clients by endpoint_sync). A connected session keeps the URL it started with, so a restart that moved
4617
+ back to the default would cut every session on the known port. A port held by another live Smart Tool stops this
4618
+ start instead of duplicating it."""
4619
+ for port in dict.fromkeys(p for p in (endpoint_sync.known_port(), DEFAULT_PORT, 0) if p is not None):
4557
4620
  try:
4558
4621
  return _ExclusiveThreadingHTTPServer(("127.0.0.1", port), MCPHandler)
4559
4622
  except OSError:
package/version.py CHANGED
@@ -1,7 +1,7 @@
1
1
  """Single source of the Smart Tool version and of the User-Agent sent to public APIs."""
2
2
  import re
3
3
 
4
- VERSION = "0.9.57"
4
+ VERSION = "0.9.61"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7
 
@@ -0,0 +1,66 @@
1
+ """Removes the Camoufox builds older than the active one after a verified update. camoufox 0.5.6 installs each build in
2
+ its own folder under `browsers/<repo>/` and never deletes the previous ones, so the cache grows by about 2.5 GB per
3
+ build. Nothing is removed while the user pinned a build (`camoufox set` writes `pinned` in config.json), and only the
4
+ active build's own repository is pruned: the active build and any newer one stay. Each folder is first renamed to a
5
+ hidden name, which Windows refuses while any file inside is open, so a build in use is skipped whole instead of left
6
+ half removed; a hidden folder left by an interrupted deletion is removed on the next run."""
7
+ import os
8
+ import shutil
9
+ import time
10
+
11
+ REMOVING_PREFIX = ".removing-"
12
+
13
+
14
+ def folder_size(path):
15
+ """Bytes of the files under path."""
16
+ return sum(os.path.getsize(os.path.join(root, name)) for root, _dirs, names in os.walk(path) for name in names)
17
+
18
+
19
+ def _delete(build, browsers_dir):
20
+ """Renames the build's folder to a hidden one in browsers_dir and deletes it; the size freed, or None when the
21
+ rename was refused because a file inside is in use."""
22
+ name = f"{build.repo_name}/{build.path.name}"
23
+ size = folder_size(build.path)
24
+ hidden = browsers_dir / f"{REMOVING_PREFIX}{build.repo_name}-{build.path.name}-{time.time_ns()}"
25
+ try:
26
+ os.rename(build.path, hidden)
27
+ except PermissionError as exc:
28
+ print(f"Kept Camoufox build {name}: in use ({exc.strerror})", flush=True)
29
+ return None
30
+ shutil.rmtree(hidden)
31
+ print(f"Removed old Camoufox build {name} ({size / 2**20:.0f} MB)", flush=True)
32
+ return size
33
+
34
+
35
+ def prune(installed, config, browsers_dir):
36
+ """Deletes the builds in installed (camoufox `InstalledVersion`s) of the active build's repository whose version is
37
+ older than the active one, unless config pins a build, and returns the bytes freed."""
38
+ if config.get("pinned"):
39
+ print(f"Camoufox build pinned to {config['pinned']}: old builds kept", flush=True)
40
+ return 0
41
+ freed = 0
42
+ for leftover in browsers_dir.glob(f"{REMOVING_PREFIX}*"):
43
+ size = folder_size(leftover)
44
+ shutil.rmtree(leftover)
45
+ freed += size
46
+ print(f"Removed an interrupted deletion: {leftover.name} ({size / 2**20:.0f} MB)", flush=True)
47
+ active = next((build for build in installed if build.is_active), None)
48
+ if active is None:
49
+ print("No active Camoufox build: old builds kept", flush=True)
50
+ return freed
51
+ for build in installed:
52
+ if build.repo_name == active.repo_name and build.version < active.version:
53
+ freed += _delete(build, browsers_dir) or 0
54
+ print(f"Old Camoufox builds pruned: {freed / 2**30:.2f} GB freed; active build "
55
+ f"{active.repo_name}/{active.path.name} kept", flush=True)
56
+ return freed
57
+
58
+
59
+ def main():
60
+ """Prunes the user's real Camoufox cache, read through camoufox's own multiversion manager."""
61
+ from camoufox import multiversion
62
+ prune(multiversion.list_installed(), multiversion.load_config(), multiversion.BROWSERS_DIR)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()