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/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Refusectomy: find, explain and live-monitor model refusals in CLI coding agents.
|
|
2
|
+
|
|
3
|
+
Claude Code transcripts get the full forensics (`refusectomy.claude_code`); any agent whose
|
|
4
|
+
API base URL you can point at localhost is monitored live through `refusectomy proxy`; and
|
|
5
|
+
`refusectomy watch` tails the session logs of the agents it knows. Refused text is identified
|
|
6
|
+
by digest, never reproduced.
|
|
7
|
+
"""
|
|
8
|
+
__version__ = "0.2.0"
|
refusectomy/__main__.py
ADDED
refusectomy/agents.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""The CLI agents refusectomy knows: where their session logs live, and what those logs can say.
|
|
2
|
+
|
|
3
|
+
claude-code <CLAUDE_CONFIG_DIR or ~/.claude>/projects/**/*.jsonl
|
|
4
|
+
everything: each refusal with the classifier's category, the model, the
|
|
5
|
+
harness's switch to a fallback model, and (by digest) the refused message
|
|
6
|
+
copilot ~/.copilot/session-state/<session>/events.jsonl
|
|
7
|
+
no model stop reason is written, so refusals cannot be seen; tool failures
|
|
8
|
+
and session errors only. Its model traffic goes to GitHub's backend, which
|
|
9
|
+
refusectomy does not intercept
|
|
10
|
+
antigravity ~/.gemini/antigravity-cli/brain/<conversation>/.system_generated/logs/transcript_full.jsonl
|
|
11
|
+
error steps only; a safety block is seen only if the agent logs it as an
|
|
12
|
+
error, and only its status words (SAFETY, PROHIBITED_CONTENT, ...) are read
|
|
13
|
+
proxy signals.jsonl written by `refusectomy proxy` -- any agent pointed at it
|
|
14
|
+
|
|
15
|
+
A reader turns one log record into signals: dicts of enums and identifiers, never text.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import glob
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from typing import Callable
|
|
26
|
+
|
|
27
|
+
from refusectomy.providers import GEMINI_BLOCKS, GEMINI_RECITATION
|
|
28
|
+
|
|
29
|
+
GOOGLE_STATUS = {"RESOURCE_EXHAUSTED", "UNAVAILABLE", "DEADLINE_EXCEEDED", "PERMISSION_DENIED",
|
|
30
|
+
"UNAUTHENTICATED", "INVALID_ARGUMENT", "INTERNAL", "FAILED_PRECONDITION",
|
|
31
|
+
"NOT_FOUND", "CANCELLED", "ABORTED"}
|
|
32
|
+
_CODE = re.compile(r"^[A-Za-z0-9_.:-]{1,40}$")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Agent:
|
|
37
|
+
name: str
|
|
38
|
+
pattern: str
|
|
39
|
+
sees: str
|
|
40
|
+
watch: str
|
|
41
|
+
reader: Callable[[dict, str], list]
|
|
42
|
+
refusal_aware: bool
|
|
43
|
+
|
|
44
|
+
def files(self) -> list[str]:
|
|
45
|
+
return sorted(f for f in glob.glob(self.pattern, recursive=True) if os.path.isfile(f))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _enum(v) -> str | None:
|
|
49
|
+
"""A short code-like string, or nothing: free text never becomes a signal field."""
|
|
50
|
+
return v if isinstance(v, str) and _CODE.match(v) else None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _claude(rec: dict, path: str) -> list:
|
|
54
|
+
from refusectomy.claude_code import project_of
|
|
55
|
+
t = rec.get("type")
|
|
56
|
+
base = {"agent": "claude-code", "session": rec.get("sessionId") or "",
|
|
57
|
+
"project": project_of(path), "ts": rec.get("timestamp") or ""}
|
|
58
|
+
msg = rec.get("message")
|
|
59
|
+
if t == "assistant" and isinstance(msg, dict) and msg.get("stop_reason") == "refusal":
|
|
60
|
+
model = rec.get("requestedModel") or msg.get("model") or ""
|
|
61
|
+
if model == "<synthetic>":
|
|
62
|
+
return [] # the harness's own notice, not a response
|
|
63
|
+
sd = msg.get("stop_details") if isinstance(msg.get("stop_details"), dict) else {}
|
|
64
|
+
return [{**base, "kind": "refusal", "category": _enum(sd.get("category")), "model": model,
|
|
65
|
+
"request_id": rec.get("requestId"), "subagent": bool(rec.get("isSidechain")),
|
|
66
|
+
"mid_stream": bool(msg.get("content"))}]
|
|
67
|
+
if t == "system" and str(rec.get("subtype", "")).startswith("model_refusal"):
|
|
68
|
+
fb = rec.get("subtype") == "model_refusal_fallback"
|
|
69
|
+
return [{**base, "kind": "refusal", "category": _enum(rec.get("apiRefusalCategory")),
|
|
70
|
+
"model": rec.get("originalModel"), "request_id": rec.get("requestId"),
|
|
71
|
+
"warning": True, "fallback": rec.get("fallbackModel") if fb else None}]
|
|
72
|
+
return []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _copilot(rec: dict, path: str) -> list:
|
|
76
|
+
t = str(rec.get("type") or "")
|
|
77
|
+
data = rec.get("data") if isinstance(rec.get("data"), dict) else {}
|
|
78
|
+
err = data.get("error")
|
|
79
|
+
code = _enum(err.get("code") or err.get("type")) if isinstance(err, dict) else None
|
|
80
|
+
base = {"agent": "copilot", "session": os.path.basename(os.path.dirname(path)),
|
|
81
|
+
"ts": rec.get("timestamp") or "", "model": _enum(data.get("model"))}
|
|
82
|
+
if t == "error" or t.endswith(".error"):
|
|
83
|
+
return [{**base, "kind": "error", "reason": code or _enum(t)}]
|
|
84
|
+
if t == "tool.execution_complete" and err:
|
|
85
|
+
return [{**base, "kind": "tool_error", "reason": code}]
|
|
86
|
+
return []
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _antigravity(rec: dict, path: str) -> list:
|
|
90
|
+
if rec.get("type") != "ERROR_MESSAGE":
|
|
91
|
+
return []
|
|
92
|
+
text = str(rec.get("error") or "") + " " + str(rec.get("error_code") or "")
|
|
93
|
+
words = set(re.findall(r"\b[A-Z][A-Z_]{3,}\b", text))
|
|
94
|
+
http = re.search(r"\b([45]\d\d)\b", text)
|
|
95
|
+
conv = path.split(f"{os.sep}brain{os.sep}")[-1].split(os.sep)[0]
|
|
96
|
+
base = {"agent": "antigravity", "session": conv, "ts": rec.get("created_at") or ""}
|
|
97
|
+
if words & GEMINI_BLOCKS:
|
|
98
|
+
return [{**base, "kind": "filtered", "reason": sorted(words & GEMINI_BLOCKS)[0]}]
|
|
99
|
+
if words & GEMINI_RECITATION:
|
|
100
|
+
return [{**base, "kind": "recitation", "reason": sorted(words & GEMINI_RECITATION)[0]}]
|
|
101
|
+
status = sorted(words & GOOGLE_STATUS)
|
|
102
|
+
return [{**base, "kind": "error", "reason": status[0] if status else (http.group(1) if http else None)}]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _proxy(rec: dict, path: str) -> list:
|
|
106
|
+
if rec.get("source") != "proxy" or rec.get("kind") in (None, "ok"):
|
|
107
|
+
return []
|
|
108
|
+
return [{**rec, "agent": "proxy", "client": rec.get("agent")}]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def registry(home: str | None = None) -> list[Agent]:
|
|
112
|
+
from refusectomy.claude_code import TRANSCRIPT_ROOT
|
|
113
|
+
from refusectomy.proxy import signals_path
|
|
114
|
+
h = home or os.path.expanduser("~")
|
|
115
|
+
return [
|
|
116
|
+
Agent("claude-code", os.path.join(TRANSCRIPT_ROOT, "**", "*.jsonl"),
|
|
117
|
+
"refusals, classifier category, model fallback, refused message (digest)",
|
|
118
|
+
"watch; hook claude-code; forensics (profile, report, ...)", _claude, True),
|
|
119
|
+
Agent("copilot", os.path.join(h, ".copilot", "session-state", "*", "events.jsonl"),
|
|
120
|
+
"tool failures and session errors only -- no model stop reason is logged",
|
|
121
|
+
"watch (errors only); its model traffic is not proxiable", _copilot, False),
|
|
122
|
+
Agent("antigravity", os.path.join(h, ".gemini", "antigravity-cli", "brain", "*",
|
|
123
|
+
".system_generated", "logs", "transcript_full.jsonl"),
|
|
124
|
+
"error steps; safety blocks only when logged as errors",
|
|
125
|
+
"watch (errors only); its model traffic is not proxiable", _antigravity, False),
|
|
126
|
+
Agent("proxy", signals_path(),
|
|
127
|
+
"every response's stop reason, from any agent pointed at the proxy",
|
|
128
|
+
"proxy, then watch", _proxy, True),
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def main(argv: list[str] | None = None) -> int:
|
|
133
|
+
ap = argparse.ArgumentParser(prog="refusectomy agents",
|
|
134
|
+
description="Which agents are here, and what each can report.")
|
|
135
|
+
ap.add_argument("--json", action="store_true")
|
|
136
|
+
a = ap.parse_args(argv)
|
|
137
|
+
rows = []
|
|
138
|
+
for ag in registry():
|
|
139
|
+
files = ag.files()
|
|
140
|
+
rows.append({"agent": ag.name, "detected": bool(files), "logs": len(files),
|
|
141
|
+
"refusal_aware": ag.refusal_aware, "sees": ag.sees, "watch": ag.watch,
|
|
142
|
+
"pattern": ag.pattern})
|
|
143
|
+
if a.json:
|
|
144
|
+
print(json.dumps(rows, indent=2))
|
|
145
|
+
return 0
|
|
146
|
+
print(f"{'agent':<13}{'logs':>6} what its logs can say")
|
|
147
|
+
for r in rows:
|
|
148
|
+
print(f"{r['agent']:<13}{r['logs'] if r['detected'] else '-':>6} {r['sees']}")
|
|
149
|
+
print(f"{'':<21}live: {r['watch']}")
|
|
150
|
+
print("\nAny agent whose API base URL you can set is fully visible through the proxy:\n"
|
|
151
|
+
" refusectomy proxy then ANTHROPIC_BASE_URL / OPENAI_BASE_URL / a Gemini base URL\n"
|
|
152
|
+
" -> the address it prints, and `refusectomy watch` beside it.")
|
|
153
|
+
return 0
|