refusectomy 0.2.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.
- refusectomy/__init__.py +8 -0
- refusectomy/__main__.py +3 -0
- refusectomy/agents.py +153 -0
- refusectomy/claude_code.py +2747 -0
- refusectomy/cli.py +91 -0
- refusectomy/excise.py +310 -0
- refusectomy/providers.py +253 -0
- refusectomy/proxy.py +302 -0
- refusectomy/watch.py +248 -0
- refusectomy-0.2.0.dist-info/METADATA +211 -0
- refusectomy-0.2.0.dist-info/RECORD +15 -0
- refusectomy-0.2.0.dist-info/WHEEL +5 -0
- refusectomy-0.2.0.dist-info/entry_points.txt +2 -0
- refusectomy-0.2.0.dist-info/licenses/LICENSE +21 -0
- refusectomy-0.2.0.dist-info/top_level.txt +1 -0
refusectomy/proxy.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Observe-only local proxy: every model response's stop reason, from any agent.
|
|
2
|
+
|
|
3
|
+
Point an agent's API base URL at it --
|
|
4
|
+
|
|
5
|
+
ANTHROPIC_BASE_URL=http://127.0.0.1:8787/anthropic Claude Code, Anthropic SDKs
|
|
6
|
+
OPENAI_BASE_URL=http://127.0.0.1:8787/openai/v1 OpenAI SDKs and compatibles
|
|
7
|
+
<gemini base url> = http://127.0.0.1:8787/gemini Gemini SDKs
|
|
8
|
+
|
|
9
|
+
-- and it forwards each request unchanged to the real API over verified TLS, relays the
|
|
10
|
+
response back chunk by chunk as it arrives, and reads the stop reason on the way past.
|
|
11
|
+
|
|
12
|
+
For each response it appends one JSON line to signals.jsonl in the state directory:
|
|
13
|
+
time, provider, route (path only), status, outcome, the provider's reason and category,
|
|
14
|
+
model, request id, whether output had begun, the client's User-Agent product, the session
|
|
15
|
+
id where the agent sends one, and -- for a refusal or block -- the digest and shape of the
|
|
16
|
+
last user message. It never records headers, bodies, query strings (Gemini can carry an
|
|
17
|
+
API key there) or text, and prints a line for anything that is not a plain success.
|
|
18
|
+
|
|
19
|
+
What it never does: change a request or a response, retry, re-route, or keep credentials.
|
|
20
|
+
It listens on loopback only, because every request through it carries an API credential.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import http.client
|
|
26
|
+
import http.server
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import shutil
|
|
30
|
+
import socket
|
|
31
|
+
import ssl
|
|
32
|
+
import subprocess
|
|
33
|
+
import sys
|
|
34
|
+
import threading
|
|
35
|
+
import time
|
|
36
|
+
import urllib.parse
|
|
37
|
+
from datetime import datetime, timezone
|
|
38
|
+
|
|
39
|
+
from refusectomy.providers import ResponseReader, Outcome, last_user_text
|
|
40
|
+
|
|
41
|
+
HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te",
|
|
42
|
+
"trailer", "trailers", "transfer-encoding", "upgrade", "host", "content-length",
|
|
43
|
+
"accept-encoding"}
|
|
44
|
+
DEFAULT_ROUTES = {
|
|
45
|
+
"anthropic": ("anthropic", "https://api.anthropic.com"),
|
|
46
|
+
"openai": ("openai", "https://api.openai.com"),
|
|
47
|
+
"gemini": ("gemini", "https://generativelanguage.googleapis.com"),
|
|
48
|
+
}
|
|
49
|
+
LOOPBACK = {"127.0.0.1", "::1", "localhost"}
|
|
50
|
+
NOTEWORTHY = {"refusal", "filtered", "recitation", "error", "unknown"}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def signals_path() -> str:
|
|
54
|
+
from refusectomy.claude_code import REPORT_DIR
|
|
55
|
+
return os.path.join(REPORT_DIR, "signals.jsonl")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _now() -> str:
|
|
59
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class SignalLog:
|
|
63
|
+
"""Thread-safe JSONL sink plus an optional per-signal callback (printing, notifying)."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, path: str | None, on_signal=None):
|
|
66
|
+
self.path, self.on_signal, self._lock = path, on_signal, threading.Lock()
|
|
67
|
+
if path:
|
|
68
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
69
|
+
|
|
70
|
+
def __call__(self, sig: dict) -> None:
|
|
71
|
+
with self._lock:
|
|
72
|
+
if self.path:
|
|
73
|
+
with open(self.path, "a") as fh:
|
|
74
|
+
fh.write(json.dumps(sig) + "\n")
|
|
75
|
+
if self.on_signal:
|
|
76
|
+
self.on_signal(sig)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def describe(sig: dict) -> str:
|
|
80
|
+
"""One line for a human: identifiers and enums only."""
|
|
81
|
+
bits = [sig["ts"][11:19], sig.get("provider", "?"), sig.get("model") or "?",
|
|
82
|
+
str(sig.get("kind", "?")).upper()]
|
|
83
|
+
if sig.get("category"):
|
|
84
|
+
bits.append(sig["category"])
|
|
85
|
+
if sig.get("reason") and sig.get("reason") != sig.get("kind"):
|
|
86
|
+
bits.append(f"({sig['reason']})")
|
|
87
|
+
if sig.get("mid_stream") is not None and sig.get("kind") in ("refusal", "filtered"):
|
|
88
|
+
bits.append("mid-stream" if sig["mid_stream"] else "before output")
|
|
89
|
+
if sig.get("request_id"):
|
|
90
|
+
bits.append(f"req={sig['request_id']}")
|
|
91
|
+
if sig.get("agent"):
|
|
92
|
+
bits.append(f"agent={sig['agent']}")
|
|
93
|
+
if sig.get("prompt"):
|
|
94
|
+
bits.append(f"prompt=sha256:{sig['prompt']['sha256_12']} {sig['prompt']['chars']}c")
|
|
95
|
+
return " ".join(bits)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def notify(title: str, line: str) -> None:
|
|
99
|
+
"""Best-effort desktop notification; never blocks, never raises."""
|
|
100
|
+
try:
|
|
101
|
+
if shutil.which("notify-send"):
|
|
102
|
+
subprocess.Popen(["notify-send", title, line], stdout=subprocess.DEVNULL,
|
|
103
|
+
stderr=subprocess.DEVNULL)
|
|
104
|
+
elif sys.platform == "darwin" and shutil.which("osascript"):
|
|
105
|
+
subprocess.Popen(["osascript", "-e", f"display notification {json.dumps(line)} "
|
|
106
|
+
f"with title {json.dumps(title)}"],
|
|
107
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
108
|
+
except Exception:
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ProxyServer(http.server.ThreadingHTTPServer):
|
|
113
|
+
daemon_threads = True
|
|
114
|
+
allow_reuse_address = True
|
|
115
|
+
|
|
116
|
+
def __init__(self, addr, routes: dict, sink, timeout_s: float = 900,
|
|
117
|
+
ssl_context: ssl.SSLContext | None = None):
|
|
118
|
+
host = addr[0]
|
|
119
|
+
self.address_family = socket.AF_INET6 if ":" in host else socket.AF_INET
|
|
120
|
+
super().__init__(addr, Handler)
|
|
121
|
+
self.routes, self.sink, self.timeout_s = routes, sink, timeout_s
|
|
122
|
+
self.ssl_context = ssl_context or ssl.create_default_context()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
126
|
+
protocol_version = "HTTP/1.1"
|
|
127
|
+
server_version = "refusectomy-proxy"
|
|
128
|
+
|
|
129
|
+
def log_message(self, *args) -> None: # no access log: a path can carry a key
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
def do_GET(self):
|
|
133
|
+
self._relay()
|
|
134
|
+
|
|
135
|
+
do_POST = do_PUT = do_PATCH = do_DELETE = do_OPTIONS = do_HEAD = do_GET
|
|
136
|
+
|
|
137
|
+
def _reply(self, status: int, obj: dict) -> None:
|
|
138
|
+
body = json.dumps(obj).encode()
|
|
139
|
+
self.send_response_only(status)
|
|
140
|
+
self.send_header("Content-Type", "application/json")
|
|
141
|
+
self.send_header("Content-Length", str(len(body)))
|
|
142
|
+
self.end_headers()
|
|
143
|
+
if self.command != "HEAD":
|
|
144
|
+
self.wfile.write(body)
|
|
145
|
+
|
|
146
|
+
def _body(self) -> bytes | None:
|
|
147
|
+
n = self.headers.get("Content-Length")
|
|
148
|
+
if n is not None:
|
|
149
|
+
return self.rfile.read(int(n))
|
|
150
|
+
if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower():
|
|
151
|
+
out = bytearray()
|
|
152
|
+
while True:
|
|
153
|
+
size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)
|
|
154
|
+
if size == 0:
|
|
155
|
+
while self.rfile.readline() not in (b"\r\n", b"\n", b""):
|
|
156
|
+
pass
|
|
157
|
+
return bytes(out)
|
|
158
|
+
out += self.rfile.read(size)
|
|
159
|
+
self.rfile.readline()
|
|
160
|
+
return None
|
|
161
|
+
|
|
162
|
+
def _relay(self) -> None:
|
|
163
|
+
t0 = time.time()
|
|
164
|
+
name, _, rest = self.path.lstrip("/").partition("/")
|
|
165
|
+
route = self.server.routes.get(name)
|
|
166
|
+
if not route:
|
|
167
|
+
known = ", ".join("/" + r for r in self.server.routes)
|
|
168
|
+
return self._reply(404, {"error": {"type": "refusectomy_proxy",
|
|
169
|
+
"message": f"unknown route /{name}; known: {known}"}})
|
|
170
|
+
provider, base = route
|
|
171
|
+
up = urllib.parse.urlsplit(base)
|
|
172
|
+
target = up.path.rstrip("/") + "/" + rest
|
|
173
|
+
try:
|
|
174
|
+
body = self._body()
|
|
175
|
+
except (ValueError, OSError):
|
|
176
|
+
# Malformed framing must get an answer, not a dead thread and a client timeout.
|
|
177
|
+
self.close_connection = True
|
|
178
|
+
return self._reply(400, {"error": {"type": "refusectomy_proxy",
|
|
179
|
+
"message": "malformed request body framing"}})
|
|
180
|
+
headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
|
|
181
|
+
headers["Host"] = up.netloc
|
|
182
|
+
headers["Accept-Encoding"] = "identity" # read the stream as it is, not compressed
|
|
183
|
+
try:
|
|
184
|
+
if up.scheme == "https":
|
|
185
|
+
conn = http.client.HTTPSConnection(up.hostname, up.port, timeout=self.server.timeout_s,
|
|
186
|
+
context=self.server.ssl_context)
|
|
187
|
+
else:
|
|
188
|
+
conn = http.client.HTTPConnection(up.hostname, up.port, timeout=self.server.timeout_s)
|
|
189
|
+
conn.request(self.command, target, body=body, headers=headers)
|
|
190
|
+
resp = conn.getresponse()
|
|
191
|
+
except (OSError, http.client.HTTPException) as e:
|
|
192
|
+
self._emit(provider, name, rest, 502, Outcome(provider, "error", type(e).__name__),
|
|
193
|
+
None, body, t0)
|
|
194
|
+
return self._reply(502, {"error": {"type": "refusectomy_proxy",
|
|
195
|
+
"message": f"upstream unreachable: {type(e).__name__}"}})
|
|
196
|
+
reader = ResponseReader(provider, resp.getheader("Content-Type", ""))
|
|
197
|
+
self.send_response_only(resp.status, resp.reason)
|
|
198
|
+
for k, v in resp.getheaders():
|
|
199
|
+
if k.lower() not in HOP:
|
|
200
|
+
self.send_header(k, v)
|
|
201
|
+
has_body = self.command != "HEAD" and resp.status not in (204, 304) and resp.status >= 200
|
|
202
|
+
if has_body:
|
|
203
|
+
self.send_header("Transfer-Encoding", "chunked")
|
|
204
|
+
else:
|
|
205
|
+
self.send_header("Content-Length", "0")
|
|
206
|
+
self.end_headers()
|
|
207
|
+
try:
|
|
208
|
+
while has_body:
|
|
209
|
+
data = resp.read1(65536)
|
|
210
|
+
if not data:
|
|
211
|
+
break
|
|
212
|
+
reader.feed(data)
|
|
213
|
+
self.wfile.write(b"%x\r\n%s\r\n" % (len(data), data))
|
|
214
|
+
self.wfile.flush()
|
|
215
|
+
if has_body:
|
|
216
|
+
self.wfile.write(b"0\r\n\r\n")
|
|
217
|
+
self.wfile.flush()
|
|
218
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
219
|
+
self.close_connection = True # the client left; still record what was seen
|
|
220
|
+
finally:
|
|
221
|
+
conn.close()
|
|
222
|
+
out = reader.close()
|
|
223
|
+
if resp.status >= 400 and out.kind == "ok":
|
|
224
|
+
out.kind, out.reason = "error", f"http_{resp.status}"
|
|
225
|
+
rid = resp.getheader("request-id") or resp.getheader("x-request-id")
|
|
226
|
+
self._emit(provider, name, rest, resp.status, out, rid, body, t0)
|
|
227
|
+
|
|
228
|
+
def _emit(self, provider, name, rest, status, out: Outcome, rid, body, t0) -> None:
|
|
229
|
+
ua = (self.headers.get("User-Agent") or "").split(" ")[0][:80]
|
|
230
|
+
sig = {"ts": _now(), "source": "proxy", "provider": provider,
|
|
231
|
+
"route": f"/{name}/{rest.split('?')[0]}", "method": self.command,
|
|
232
|
+
"status": status, **out.as_dict(), "request_id": rid,
|
|
233
|
+
"ms": int(1000 * (time.time() - t0)), "agent": ua or None,
|
|
234
|
+
"session": self.headers.get("X-Claude-Code-Session-Id") or None}
|
|
235
|
+
if out.kind in ("refusal", "filtered", "recitation") and body:
|
|
236
|
+
try:
|
|
237
|
+
text = last_user_text(provider, json.loads(body))
|
|
238
|
+
except ValueError:
|
|
239
|
+
text = ""
|
|
240
|
+
if text:
|
|
241
|
+
from refusectomy.claude_code import fingerprint
|
|
242
|
+
sha, _words, shape = fingerprint(text)
|
|
243
|
+
sig["prompt"] = {"sha256_12": sha, "chars": len(text), "shape": shape}
|
|
244
|
+
self.server.sink(sig)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def parse_routes(specs: list[str]) -> dict:
|
|
248
|
+
routes = dict(DEFAULT_ROUTES)
|
|
249
|
+
for spec in specs:
|
|
250
|
+
name, sep, url = spec.partition("=")
|
|
251
|
+
provider = name.split(":")[0]
|
|
252
|
+
if not sep or provider not in ("anthropic", "openai", "gemini"):
|
|
253
|
+
raise SystemExit(f"--upstream wants PROVIDER=URL or PROVIDER:ROUTE=URL "
|
|
254
|
+
f"(provider anthropic|openai|gemini), got {spec!r}")
|
|
255
|
+
route = name.split(":")[1] if ":" in name else provider
|
|
256
|
+
if urllib.parse.urlsplit(url).scheme not in ("https", "http"):
|
|
257
|
+
raise SystemExit(f"--upstream {spec!r}: need an http(s) URL")
|
|
258
|
+
routes[route] = (provider, url.rstrip("/"))
|
|
259
|
+
return routes
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def main(argv: list[str] | None = None) -> int:
|
|
263
|
+
ap = argparse.ArgumentParser(
|
|
264
|
+
prog="refusectomy proxy", description=__doc__,
|
|
265
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
266
|
+
ap.add_argument("--port", type=int, default=8787)
|
|
267
|
+
ap.add_argument("--host", default="127.0.0.1", help="loopback only (127.0.0.1, ::1, localhost)")
|
|
268
|
+
ap.add_argument("--upstream", action="append", default=[], metavar="PROVIDER[:ROUTE]=URL",
|
|
269
|
+
help="override or add an upstream, e.g. anthropic=https://gateway.example "
|
|
270
|
+
"or openai:azure=https://x.openai.azure.com")
|
|
271
|
+
ap.add_argument("--log", help="signal log path (default: signals.jsonl in the state dir)")
|
|
272
|
+
ap.add_argument("--notify", action="store_true", help="desktop notification per refusal")
|
|
273
|
+
ap.add_argument("--all", action="store_true", help="print every response, not only the noteworthy")
|
|
274
|
+
a = ap.parse_args(argv)
|
|
275
|
+
if a.host not in LOOPBACK:
|
|
276
|
+
print("refusectomy proxy listens on loopback only: every request through it carries "
|
|
277
|
+
"an API credential.", file=sys.stderr)
|
|
278
|
+
return 2
|
|
279
|
+
routes = parse_routes(a.upstream)
|
|
280
|
+
path = a.log or signals_path()
|
|
281
|
+
|
|
282
|
+
def show(sig: dict) -> None:
|
|
283
|
+
if a.all or sig.get("kind") in NOTEWORTHY:
|
|
284
|
+
line = describe(sig)
|
|
285
|
+
print(line, file=sys.stderr, flush=True)
|
|
286
|
+
if a.notify and sig.get("kind") in ("refusal", "filtered"):
|
|
287
|
+
notify("refusectomy", line)
|
|
288
|
+
|
|
289
|
+
srv = ProxyServer((a.host, a.port), routes, SignalLog(path, show))
|
|
290
|
+
base = f"http://{'[' + a.host + ']' if ':' in a.host else a.host}:{srv.server_address[1]}"
|
|
291
|
+
print(f"refusectomy proxy on {base} -- observe-only; signals -> {path}", file=sys.stderr)
|
|
292
|
+
for route, (provider, url) in routes.items():
|
|
293
|
+
hint = {"anthropic": "ANTHROPIC_BASE_URL=", "openai": "OPENAI_BASE_URL="}.get(provider, "base URL ")
|
|
294
|
+
suffix = "/v1" if provider == "openai" and urllib.parse.urlsplit(url).path in ("", "/") else ""
|
|
295
|
+
print(f" {route:<10} -> {url:<44} {hint}{base}/{route}{suffix}", file=sys.stderr)
|
|
296
|
+
try:
|
|
297
|
+
srv.serve_forever()
|
|
298
|
+
except KeyboardInterrupt:
|
|
299
|
+
pass
|
|
300
|
+
finally:
|
|
301
|
+
srv.server_close()
|
|
302
|
+
return 0
|
refusectomy/watch.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Live monitor: tail every supported agent's session logs, and the proxy's signal log, and
|
|
2
|
+
report each refusal as it is written. Read-only.
|
|
3
|
+
|
|
4
|
+
It prints identifiers and enums -- agent, project, session, model, category -- never the
|
|
5
|
+
text of anything, and the advice the corpus supports: on a first decline, abandon the
|
|
6
|
+
session rather than rephrasing in it; when Claude Code's refusal fallback moves a session
|
|
7
|
+
onto another model, say so and how to release it. Rates are quoted only when `refusectomy
|
|
8
|
+
profile` has measured them on this machine.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from collections import Counter
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
|
|
20
|
+
from refusectomy.agents import Agent, registry
|
|
21
|
+
|
|
22
|
+
DECLINE = {"refusal", "filtered", "recitation"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _ordinal(n: int) -> str:
|
|
26
|
+
return f"{n}{'th' if 10 <= n % 100 <= 20 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')}"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _when(ts: str) -> datetime | None:
|
|
30
|
+
try:
|
|
31
|
+
d = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
|
|
32
|
+
return d if d.tzinfo else d.replace(tzinfo=timezone.utc)
|
|
33
|
+
except ValueError:
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Tail:
|
|
38
|
+
"""New complete lines of a growing file. A partial last line waits for its newline."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, path: str, from_end: bool):
|
|
41
|
+
self.path, self.rem = path, b""
|
|
42
|
+
try:
|
|
43
|
+
self.pos = os.path.getsize(path) if from_end else 0
|
|
44
|
+
except OSError:
|
|
45
|
+
self.pos = 0
|
|
46
|
+
|
|
47
|
+
def lines(self) -> list[bytes]:
|
|
48
|
+
try:
|
|
49
|
+
size = os.path.getsize(self.path)
|
|
50
|
+
except OSError:
|
|
51
|
+
return []
|
|
52
|
+
if size < self.pos: # truncated or replaced
|
|
53
|
+
self.pos, self.rem = 0, b""
|
|
54
|
+
if size == self.pos:
|
|
55
|
+
return []
|
|
56
|
+
with open(self.path, "rb") as fh:
|
|
57
|
+
fh.seek(self.pos)
|
|
58
|
+
data = fh.read(size - self.pos)
|
|
59
|
+
self.pos += len(data)
|
|
60
|
+
parts = (self.rem + data).split(b"\n")
|
|
61
|
+
self.rem = parts.pop()
|
|
62
|
+
return [p for p in parts if p.strip()]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Watcher:
|
|
66
|
+
def __init__(self, agents: list[Agent], since_minutes: float = 0, out=print,
|
|
67
|
+
as_json: bool = False, notify: bool = False, show_tools: bool = False,
|
|
68
|
+
profile: dict | None = None, excise: bool = False, quiet_s: float = 3.0):
|
|
69
|
+
self.agents, self.out, self.as_json = agents, out, as_json
|
|
70
|
+
self.notify, self.show_tools, self.profile = notify, show_tools, profile or {}
|
|
71
|
+
self.cutoff = time.time() - 60 * since_minutes
|
|
72
|
+
self.since = since_minutes
|
|
73
|
+
self.tails: dict[str, tuple[Agent, Tail]] = {}
|
|
74
|
+
self.seen: set = set()
|
|
75
|
+
self.declines: Counter = Counter()
|
|
76
|
+
self._first_scan = True
|
|
77
|
+
self.excise, self.quiet_s = excise, quiet_s
|
|
78
|
+
self.pending: dict[str, str] = {} # transcript path -> session, awaiting quiet
|
|
79
|
+
|
|
80
|
+
def discover(self) -> None:
|
|
81
|
+
for ag in self.agents:
|
|
82
|
+
for f in ag.files():
|
|
83
|
+
if f in self.tails:
|
|
84
|
+
continue
|
|
85
|
+
try:
|
|
86
|
+
recent = os.path.getmtime(f) >= self.cutoff
|
|
87
|
+
except OSError:
|
|
88
|
+
continue
|
|
89
|
+
# At start-up an existing log is read from its end, unless --since asks
|
|
90
|
+
# for its recent past; a log that appears later is a new session, read whole.
|
|
91
|
+
from_end = self._first_scan and not (self.since and recent)
|
|
92
|
+
self.tails[f] = (ag, Tail(f, from_end))
|
|
93
|
+
self._first_scan = False
|
|
94
|
+
|
|
95
|
+
def poll(self) -> int:
|
|
96
|
+
found = []
|
|
97
|
+
for path, (ag, tail) in list(self.tails.items()):
|
|
98
|
+
for raw in tail.lines():
|
|
99
|
+
try:
|
|
100
|
+
rec = json.loads(raw)
|
|
101
|
+
except ValueError:
|
|
102
|
+
continue
|
|
103
|
+
if not isinstance(rec, dict):
|
|
104
|
+
continue
|
|
105
|
+
try:
|
|
106
|
+
found.extend((sig, path) for sig in ag.reader(rec, path))
|
|
107
|
+
except Exception:
|
|
108
|
+
continue # one odd record never stops the watch
|
|
109
|
+
# In time order across every log, so a recap reads as one timeline (stable within
|
|
110
|
+
# a log, which keeps a refused turn ahead of its warning record).
|
|
111
|
+
epoch = datetime.min.replace(tzinfo=timezone.utc)
|
|
112
|
+
found.sort(key=lambda sp: _when(sp[0].get("ts", "")) or epoch)
|
|
113
|
+
shown = sum(self.handle(sig, path) for sig, path in found)
|
|
114
|
+
self._excise_pending()
|
|
115
|
+
return shown
|
|
116
|
+
|
|
117
|
+
def _excise_pending(self) -> None:
|
|
118
|
+
"""Write a clean copy once a declined session's log has been quiet for a moment, so
|
|
119
|
+
the copy never cuts into a turn the harness is still writing."""
|
|
120
|
+
for path, sid in list(self.pending.items()):
|
|
121
|
+
try:
|
|
122
|
+
if time.time() - os.path.getmtime(path) < self.quiet_s:
|
|
123
|
+
continue
|
|
124
|
+
from refusectomy import excise
|
|
125
|
+
res = excise.make_clean_copy(path, sid)
|
|
126
|
+
except Exception:
|
|
127
|
+
res = None
|
|
128
|
+
del self.pending[path]
|
|
129
|
+
if res and res.get("written") and not self.as_json:
|
|
130
|
+
self.out(f"{'':10}-> clean copy without the decline's debris: /resume {res['fork_session']}")
|
|
131
|
+
elif res and res.get("written"):
|
|
132
|
+
self.out(json.dumps({"kind": "clean_copy", "session": sid, "fork_session": res["fork_session"]}))
|
|
133
|
+
|
|
134
|
+
def handle(self, sig: dict, path: str | None = None) -> int:
|
|
135
|
+
if sig.get("kind") == "tool_error" and not self.show_tools:
|
|
136
|
+
return 0
|
|
137
|
+
# The cutoff only trims a --since replay. Lines read past a log's starting offset
|
|
138
|
+
# are new by construction -- and a record can be stamped before it is written
|
|
139
|
+
# (a request that began before the watch did), so filtering live lines by their
|
|
140
|
+
# timestamp would drop exactly those.
|
|
141
|
+
when = _when(sig.get("ts", ""))
|
|
142
|
+
if self.since and when and when.timestamp() < self.cutoff:
|
|
143
|
+
return 0
|
|
144
|
+
sess = (sig.get("agent"), sig.get("session"))
|
|
145
|
+
key = (sess, sig.get("request_id")) if sig.get("request_id") else None
|
|
146
|
+
if key and key in self.seen:
|
|
147
|
+
# The warning record for a refusal already reported: only a fallback is news.
|
|
148
|
+
if sig.get("fallback") and (key, "fallback") not in self.seen:
|
|
149
|
+
self.seen.add((key, "fallback"))
|
|
150
|
+
self._emit(sig, [self._latch(sig)])
|
|
151
|
+
return 1
|
|
152
|
+
return 0
|
|
153
|
+
if key:
|
|
154
|
+
self.seen.add(key)
|
|
155
|
+
if sig.get("fallback"):
|
|
156
|
+
self.seen.add((key, "fallback"))
|
|
157
|
+
advice = []
|
|
158
|
+
if sig.get("kind") in DECLINE:
|
|
159
|
+
self.declines[sess] += 1
|
|
160
|
+
advice = self._advice(sig, self.declines[sess])
|
|
161
|
+
if self.excise and path and sig.get("agent") == "claude-code" \
|
|
162
|
+
and f"{os.sep}subagents{os.sep}" not in path:
|
|
163
|
+
self.pending[path] = sig.get("session")
|
|
164
|
+
self._emit(sig, advice)
|
|
165
|
+
return 1
|
|
166
|
+
|
|
167
|
+
def _latch(self, sig: dict) -> str:
|
|
168
|
+
return (f"-> Claude Code moved this session from {sig.get('model') or '?'} to "
|
|
169
|
+
f"{sig['fallback']} (refusal fallback); it stays there until /clear or /model")
|
|
170
|
+
|
|
171
|
+
def _advice(self, sig: dict, n: int) -> list[str]:
|
|
172
|
+
out = [self._latch(sig)] if sig.get("fallback") else []
|
|
173
|
+
ar, ao = self.profile.get("p_after_refuse"), self.profile.get("p_after_ok")
|
|
174
|
+
odds = ""
|
|
175
|
+
if ar and ao and ar[1] and ao[1]:
|
|
176
|
+
odds = f" On this machine the next request declines {100 * ar[0] / ar[1]:.0f}% of the time."
|
|
177
|
+
if n == 1:
|
|
178
|
+
out.append(f"{_ordinal(n)} decline in this session. Abandon it rather than rephrasing:"
|
|
179
|
+
f" start fresh with only what the next step needs.{odds}")
|
|
180
|
+
else:
|
|
181
|
+
out.append(f"{_ordinal(n)} decline in this session -- a run. Rephrasing in place is"
|
|
182
|
+
f" what extends it.{odds}")
|
|
183
|
+
return out
|
|
184
|
+
|
|
185
|
+
def _emit(self, sig: dict, advice: list[str]) -> None:
|
|
186
|
+
if self.as_json:
|
|
187
|
+
self.out(json.dumps(sig))
|
|
188
|
+
return
|
|
189
|
+
when = _when(sig.get("ts", ""))
|
|
190
|
+
clock = when.astimezone().strftime("%H:%M:%S") if when else "--:--:--"
|
|
191
|
+
where = sig.get("project") or (f"via {sig['client']}" if sig.get("client") else "")
|
|
192
|
+
bits = [clock, f"{sig.get('agent', '?'):<11}", where, str(sig.get("session") or "")[:8],
|
|
193
|
+
str(sig.get("kind", "?")).upper(), sig.get("category") or sig.get("reason") or "",
|
|
194
|
+
sig.get("model") or ""]
|
|
195
|
+
if sig.get("subagent"):
|
|
196
|
+
bits.append("(subagent)")
|
|
197
|
+
if sig.get("request_id"):
|
|
198
|
+
bits.append(str(sig["request_id"]))
|
|
199
|
+
self.out(" ".join(b for b in bits if b))
|
|
200
|
+
for a in advice:
|
|
201
|
+
self.out(f"{'':10}{a}")
|
|
202
|
+
if self.notify and sig.get("kind") in DECLINE:
|
|
203
|
+
from refusectomy.proxy import notify
|
|
204
|
+
notify("refusectomy", f"{sig.get('agent')}: {sig.get('kind')} "
|
|
205
|
+
f"{sig.get('category') or sig.get('reason') or ''}".strip())
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def main(argv: list[str] | None = None) -> int:
|
|
209
|
+
names = [a.name for a in registry()]
|
|
210
|
+
ap = argparse.ArgumentParser(prog="refusectomy watch", description=__doc__,
|
|
211
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
212
|
+
ap.add_argument("--agents", default=",".join(names), help=f"comma list of {', '.join(names)}")
|
|
213
|
+
ap.add_argument("--since", type=float, default=0, metavar="MINUTES",
|
|
214
|
+
help="also report what was written in the last MINUTES")
|
|
215
|
+
ap.add_argument("--interval", type=float, default=1.0, metavar="SECONDS")
|
|
216
|
+
ap.add_argument("--once", action="store_true", help="one pass, then exit (with --since: a recap)")
|
|
217
|
+
ap.add_argument("--json", action="store_true", help="one JSON signal per line, no advice")
|
|
218
|
+
ap.add_argument("--notify", action="store_true", help="desktop notification per decline")
|
|
219
|
+
ap.add_argument("--tools", action="store_true", help="also show agents' tool failures")
|
|
220
|
+
ap.add_argument("--excise", action="store_true",
|
|
221
|
+
help="write a clean copy of each declined Claude Code session (see `refusectomy excise`)")
|
|
222
|
+
a = ap.parse_args(argv)
|
|
223
|
+
wanted = {x.strip() for x in a.agents.split(",") if x.strip()}
|
|
224
|
+
unknown = wanted - set(names)
|
|
225
|
+
if unknown:
|
|
226
|
+
print(f"refusectomy watch: unknown agent(s) {', '.join(sorted(unknown))}", file=sys.stderr)
|
|
227
|
+
return 2
|
|
228
|
+
agents = [ag for ag in registry() if ag.name in wanted]
|
|
229
|
+
from refusectomy.claude_code import load_profile
|
|
230
|
+
w = Watcher(agents, a.since, as_json=a.json, notify=a.notify, show_tools=a.tools,
|
|
231
|
+
profile=load_profile(), out=lambda s: print(s, flush=True), excise=a.excise,
|
|
232
|
+
quiet_s=0 if a.once else 3.0)
|
|
233
|
+
w.discover()
|
|
234
|
+
if not a.once and not a.json:
|
|
235
|
+
live = [f"{ag.name} ({len([p for p in w.tails if w.tails[p][0] is ag])})" for ag in agents]
|
|
236
|
+
print(f"refusectomy watch: {', '.join(live)} -- Ctrl-C to stop", file=sys.stderr)
|
|
237
|
+
try:
|
|
238
|
+
n = 0
|
|
239
|
+
while True:
|
|
240
|
+
w.poll()
|
|
241
|
+
if a.once:
|
|
242
|
+
return 0
|
|
243
|
+
time.sleep(a.interval)
|
|
244
|
+
n += 1
|
|
245
|
+
if n % 5 == 0:
|
|
246
|
+
w.discover()
|
|
247
|
+
except KeyboardInterrupt:
|
|
248
|
+
return 0
|