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/cli.py ADDED
@@ -0,0 +1,91 @@
1
+ """The `refusectomy` command.
2
+
3
+ Forensics over Claude Code transcripts (scan, profile, trace, audit, session, remedy,
4
+ report, bisect) is the engine in `refusectomy.claude_code`, reached unchanged. Three
5
+ commands work across agents: `watch` tails every supported agent's session logs live,
6
+ `proxy` sits between any agent and its API and reads each response's stop reason as it
7
+ streams, and `agents` says what each agent on this machine can and cannot report.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+
13
+ from refusectomy import __version__
14
+
15
+ ENGINE_FLAGS_WITH_VALUE = {"--cwd"}
16
+ ENGINE_FLAGS = {"--include-synthetic"}
17
+
18
+ HELP = f"""refusectomy {__version__} -- find, explain and live-monitor model refusals in CLI agents
19
+
20
+ live, any agent
21
+ watch tail every supported agent's session logs and report refusals as they happen
22
+ proxy observe-only local proxy: point an agent's API base URL at it to see every
23
+ response's stop reason (Anthropic, OpenAI, Gemini wire formats)
24
+ agents which agents are installed here, and what each one's logs can tell you
25
+
26
+ Claude Code (transcript forensics; --cwd DIR before the command limits to one project)
27
+ audit self-check every invariant the numbers depend on
28
+ profile base rates, stickiness, model comparison, confounds -> profile.json
29
+ scan every refusal event (--json writes refusals.json)
30
+ trace which messages were refused, by digest (--verbatim writes a 0600 file)
31
+ session the declines in one session (--live: the current one)
32
+ remedy the playbook for a refusal category, rendered from profile.json
33
+ report support-ticket bundle for a classifier false positive, digest-only
34
+ excise write a clean copy of a declined session -- the decline's debris removed, your
35
+ messages and work kept -- to resume with /resume (--dry-run to preview)
36
+ hook hook entry points: refusectomy hook claude-code [--excise] (Stop / SessionStart)
37
+ bisect active replay to isolate a trigger (needs API credentials)
38
+
39
+ refusectomy COMMAND --help for each command's options. refusectomy --version
40
+ """
41
+
42
+
43
+ def _command(argv: list[str]) -> tuple[str | None, int]:
44
+ """The subcommand and its index, skipping the engine's top-level flags."""
45
+ i = 0
46
+ while i < len(argv):
47
+ a = argv[i]
48
+ if a in ENGINE_FLAGS_WITH_VALUE:
49
+ i += 2
50
+ continue
51
+ if a in ENGINE_FLAGS or (a.startswith("--") and "=" in a):
52
+ i += 1
53
+ continue
54
+ return (None if a.startswith("-") else a), i
55
+ return None, i
56
+
57
+
58
+ def main(argv: list[str] | None = None) -> int:
59
+ argv = list(sys.argv[1:] if argv is None else argv)
60
+ cmd, i = _command(argv)
61
+ if not argv or (cmd is None and set(argv) & {"-h", "--help"}):
62
+ print(HELP)
63
+ return 0
64
+ rest = argv[i + 1:]
65
+ if cmd == "watch":
66
+ from refusectomy.watch import main as run
67
+ return run(rest)
68
+ if cmd == "proxy":
69
+ from refusectomy.proxy import main as run
70
+ return run(rest)
71
+ if cmd == "agents":
72
+ from refusectomy.agents import main as run
73
+ return run(rest)
74
+ if cmd == "excise":
75
+ from refusectomy.excise import main as run
76
+ return run(rest)
77
+ from refusectomy import claude_code
78
+ if cmd == "hook":
79
+ if not rest or rest[0] in {"-h", "--help"}:
80
+ print("usage: refusectomy hook claude-code [--excise] [--session ID] [--no-stdin]\n\n"
81
+ "Claude Code Stop / SessionStart hook: warns the user (systemMessage only,\n"
82
+ "never the model) when the session's decline count rises. With --excise (or\n"
83
+ "REFUSECTOMY_EXCISE=1, or {\"excise\": true} in config.json) it also writes a\n"
84
+ "clean copy of the session and names it, to resume with /resume.")
85
+ return 0
86
+ if rest[0] != "claude-code":
87
+ print(f"refusectomy: no hook for {rest[0]!r} yet -- only claude-code. "
88
+ f"For other agents, run `refusectomy watch` beside them.", file=sys.stderr)
89
+ return 2
90
+ return claude_code.main(argv[:i] + ["guard"] + rest[1:])
91
+ return claude_code.main(argv)
refusectomy/excise.py ADDED
@@ -0,0 +1,310 @@
1
+ """Excise a declined session's debris into a clean copy Claude Code can resume.
2
+
3
+ Removed -- the decline's own debris, and nothing else:
4
+ - every record of a declined response (stop_reason "refusal"), by request id, so the
5
+ streamed siblings go too: the partial output the refusal docs say to discard
6
+ - the harness's <synthetic> notice response and its system refusal record
7
+ - the harness's meta notice message ("... stopped by a safety classifier ..."), which
8
+ otherwise goes back to the model with the next request
9
+ - the results of tool calls made inside a declined response, which would otherwise
10
+ answer a call that no longer exists. A call that had already run keeps its effects on
11
+ disk; the report says how many did.
12
+ Kept, byte for byte: your messages (including any that quote the notice), every response
13
+ that was not declined, every other tool call and result, attachments, and all the work
14
+ material. Nothing is reworded, and nothing is chosen by what a classifier reacts to: the
15
+ classifier still sees everything that was actually asked.
16
+
17
+ The source transcript is never written -- Claude Code may still be appending to it. The
18
+ copy gets a new session id, Claude Code's own `derived-from` lineage record (via "fork"),
19
+ and a parent chain re-linked around what was removed. `claude --resume <id>` (or /resume)
20
+ opens it on your default model, which also releases a refusal-fallback latch.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import os
27
+ import sys
28
+ import uuid
29
+ from datetime import datetime, timezone
30
+
31
+ from refusectomy import claude_code as cc
32
+
33
+ NOTICE_MAX = 4000 # a meta notice is a short harness message, not a document quoting one
34
+
35
+
36
+ def _msg(r: dict) -> dict:
37
+ m = r.get("message")
38
+ return m if isinstance(m, dict) else {}
39
+
40
+
41
+ def _blocks(content) -> list:
42
+ if isinstance(content, list):
43
+ return [b for b in content if isinstance(b, dict)]
44
+ if isinstance(content, str):
45
+ return [{"type": "text", "text": content}]
46
+ return []
47
+
48
+
49
+ def _is_notice(r: dict) -> bool:
50
+ if r.get("type") != "user" or not r.get("isMeta"):
51
+ return False
52
+ bl = _blocks(_msg(r).get("content"))
53
+ return (len(bl) == 1 and bl[0].get("type") == "text"
54
+ and cc.REFUSAL_NOTICE in str(bl[0].get("text", ""))
55
+ and len(str(bl[0].get("text", ""))) < NOTICE_MAX)
56
+
57
+
58
+ def plan(records: list[dict]) -> tuple[set, dict, dict]:
59
+ """(indexes to drop, {index: kept content blocks}, counts) -- decides, changes nothing."""
60
+ declined = set()
61
+ for r in records:
62
+ if r.get("type") == "assistant" and _msg(r).get("stop_reason") == "refusal" and r.get("requestId"):
63
+ declined.add(r["requestId"])
64
+ if r.get("type") == "system" and str(r.get("subtype", "")).startswith("model_refusal") \
65
+ and r.get("requestId"):
66
+ declined.add(r["requestId"])
67
+ drop, strip = set(), {}
68
+ n = {"declined_requests": len(declined), "declined_records": 0, "notice_responses": 0,
69
+ "refusal_records": 0, "meta_notices": 0, "tool_results": 0, "tool_calls_that_ran": 0}
70
+ calls = set()
71
+ for i, r in enumerate(records):
72
+ t, m = r.get("type"), _msg(r)
73
+ if t == "assistant" and (r.get("requestId") in declined or m.get("stop_reason") == "refusal"):
74
+ drop.add(i)
75
+ synthetic = (r.get("requestedModel") or m.get("model")) == "<synthetic>"
76
+ n["notice_responses" if synthetic else "declined_records"] += 1
77
+ calls |= {b.get("id") for b in _blocks(m.get("content")) if b.get("type") == "tool_use"}
78
+ elif t == "system" and str(r.get("subtype", "")).startswith("model_refusal"):
79
+ drop.add(i)
80
+ n["refusal_records"] += 1
81
+ elif _is_notice(r):
82
+ drop.add(i)
83
+ n["meta_notices"] += 1
84
+ calls.discard(None)
85
+ for i, r in enumerate(records):
86
+ if r.get("type") != "user" or i in drop:
87
+ continue
88
+ bl = _blocks(_msg(r).get("content"))
89
+ hit = [b for b in bl if b.get("type") == "tool_result" and b.get("tool_use_id") in calls]
90
+ if not hit:
91
+ continue
92
+ n["tool_results"] += len(hit)
93
+ n["tool_calls_that_ran"] += sum(1 for b in hit if not b.get("is_error"))
94
+ rest = [b for b in bl if b not in hit]
95
+ if rest:
96
+ strip[i] = rest
97
+ else:
98
+ drop.add(i)
99
+ return drop, strip, n
100
+
101
+
102
+ def excise_records(records: list[dict], source_sid: str, new_sid: str) -> tuple[list[dict], dict]:
103
+ drop, strip, n = plan(records)
104
+ gone = {records[i].get("uuid") for i in drop if records[i].get("uuid")}
105
+ parent = {r.get("uuid"): r.get("parentUuid") for r in records if r.get("uuid")}
106
+
107
+ def lift(u):
108
+ seen = set()
109
+ while u in gone and u not in seen:
110
+ seen.add(u)
111
+ u = parent.get(u)
112
+ return u
113
+
114
+ out = [{"type": "derived-from", "v": 1, "sessionId": new_sid,
115
+ "sessions": [{"id": source_sid, "type": "claude_code_session", "via": "fork"}]}]
116
+ relinked = 0
117
+ for i, r in enumerate(records):
118
+ if i in drop:
119
+ continue
120
+ r = dict(r)
121
+ for key in ("parentUuid", "logicalParentUuid"):
122
+ if r.get(key) in gone:
123
+ r[key] = lift(r[key])
124
+ relinked += 1
125
+ if i in strip:
126
+ r["message"] = dict(_msg(r), content=strip[i])
127
+ if "sessionId" in r:
128
+ r["sessionId"] = new_sid
129
+ if "requestSessionId" in r: # as Claude Code's own forks do
130
+ r["requestSessionId"] = new_sid
131
+ out.append(r)
132
+ n.update(kept_records=len(out) - 1, relinked=relinked)
133
+ return out, n
134
+
135
+
136
+ def verify(source: list[dict], fork: list[dict]) -> list[str]:
137
+ """What must hold of a clean copy; empty when it does. Used by tests and `audit`."""
138
+ problems = []
139
+ ids = {r.get("uuid") for r in fork if r.get("uuid")}
140
+ src_ids = {r.get("uuid") for r in source if r.get("uuid")}
141
+ drop, _strip, _n = plan(source)
142
+ gone = {source[i].get("uuid") for i in drop}
143
+ for r in fork:
144
+ p = r.get("parentUuid")
145
+ if p and p not in ids and (p in gone or p in src_ids):
146
+ problems.append(f"parent of {r.get('uuid')} points at a removed record")
147
+ if r.get("type") == "assistant" and _msg(r).get("stop_reason") == "refusal":
148
+ problems.append(f"declined response {r.get('uuid')} still present")
149
+ if (r.get("type") == "system" and str(r.get("subtype", "")).startswith("model_refusal")) or _is_notice(r):
150
+ problems.append(f"notice or refusal record {r.get('uuid')} still present")
151
+ calls = {b.get("id") for r in fork if r.get("type") == "assistant"
152
+ for b in _blocks(_msg(r).get("content")) if b.get("type") == "tool_use"}
153
+ src_calls = {b.get("id") for r in source if r.get("type") == "assistant"
154
+ for b in _blocks(_msg(r).get("content")) if b.get("type") == "tool_use"}
155
+ for r in fork:
156
+ for b in _blocks(_msg(r).get("content")) if r.get("type") == "user" else []:
157
+ if b.get("type") == "tool_result" and b.get("tool_use_id") in src_calls - calls:
158
+ problems.append(f"tool result {b.get('tool_use_id')} answers a removed call")
159
+ kept = {r.get("uuid"): r for r in fork if r.get("uuid")}
160
+ for r in source:
161
+ if r.get("type") == "user" and not r.get("isMeta") and r.get("uuid") \
162
+ and not any(b.get("type") == "tool_result" for b in _blocks(_msg(r).get("content"))):
163
+ k = kept.get(r["uuid"])
164
+ if k is None or _msg(k).get("content") != _msg(r).get("content"):
165
+ problems.append(f"user message {r['uuid']} was not kept unchanged")
166
+ sids = {r.get("sessionId") for r in fork if "sessionId" in r}
167
+ if len(sids) != 1:
168
+ problems.append(f"copy carries {len(sids)} session ids")
169
+ return problems
170
+
171
+
172
+ def _read(path: str) -> list[dict]:
173
+ out = []
174
+ with open(path, errors="replace") as fh:
175
+ for line in fh:
176
+ try:
177
+ r = json.loads(line)
178
+ except ValueError:
179
+ continue # a partial last line from a live writer
180
+ if isinstance(r, dict):
181
+ out.append(r)
182
+ return out
183
+
184
+
185
+ def ledger_path() -> str:
186
+ return os.path.join(cc.REPORT_DIR, "excisions.jsonl")
187
+
188
+
189
+ def ledger() -> list[dict]:
190
+ try:
191
+ with open(ledger_path()) as fh:
192
+ return [json.loads(l) for l in fh if l.strip()]
193
+ except (OSError, ValueError):
194
+ return []
195
+
196
+
197
+ def make_clean_copy(path: str, source_sid: str | None = None, dry_run: bool = False,
198
+ replace_previous: bool = True) -> dict:
199
+ """Write the excised copy beside the source transcript; return what was done."""
200
+ records = _read(path)
201
+ sid = source_sid or next((r.get("sessionId") for r in records if r.get("sessionId")), None) \
202
+ or os.path.splitext(os.path.basename(path))[0]
203
+ new_sid = str(uuid.uuid4())
204
+ fork, n = excise_records(records, sid, new_sid)
205
+ problems = verify(records, fork)
206
+ res = {"source_session": sid, "fork_session": new_sid, "removed": n, "problems": problems,
207
+ "path": os.path.join(os.path.dirname(path), f"{new_sid}.jsonl"),
208
+ "project": cc.project_of(path), "declines": n["refusal_records"]}
209
+ if dry_run or problems or not n["declined_requests"]:
210
+ res["written"] = False
211
+ return res
212
+ tmp = res["path"] + f".{os.getpid()}.tmp"
213
+ with open(tmp, "w") as fh:
214
+ for r in fork:
215
+ fh.write(json.dumps(r, separators=(",", ":"), ensure_ascii=False) + "\n")
216
+ try:
217
+ os.chmod(tmp, os.stat(path).st_mode & 0o777)
218
+ except OSError:
219
+ pass
220
+ os.replace(tmp, res["path"])
221
+ res["written"], res["bytes"] = True, os.path.getsize(res["path"])
222
+ res["ts"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
223
+ if replace_previous:
224
+ res["replaced"] = _retire_previous(sid, keep=new_sid)
225
+ os.makedirs(os.path.dirname(ledger_path()), exist_ok=True)
226
+ with open(ledger_path(), "a") as fh:
227
+ fh.write(json.dumps({k: res[k] for k in ("ts", "source_session", "fork_session", "path",
228
+ "project", "declines", "removed", "bytes")}) + "\n")
229
+ return res
230
+
231
+
232
+ def _retire_previous(source_sid: str, keep: str) -> list[str]:
233
+ """Delete earlier clean copies of the same session -- only ones this tool wrote, and
234
+ only while nobody has resumed them (unchanged size); a resumed copy is a session now."""
235
+ gone = []
236
+ for e in ledger():
237
+ if e.get("source_session") != source_sid or e.get("fork_session") == keep:
238
+ continue
239
+ p = e.get("path") or ""
240
+ try:
241
+ if os.path.getsize(p) != e.get("bytes"):
242
+ continue
243
+ with open(p) as fh:
244
+ first = json.loads(fh.readline())
245
+ if first.get("type") == "derived-from" and \
246
+ (first.get("sessions") or [{}])[0].get("id") == source_sid:
247
+ os.remove(p)
248
+ gone.append(e["fork_session"])
249
+ except (OSError, ValueError):
250
+ continue
251
+ return gone
252
+
253
+
254
+ def enabled(flag: bool = False) -> bool:
255
+ """Opt-in: --excise on the hook, REFUSECTOMY_EXCISE=1, or {"excise": true} in config.json."""
256
+ if flag or os.environ.get("REFUSECTOMY_EXCISE", "").lower() in ("1", "true", "yes"):
257
+ return True
258
+ try:
259
+ with open(os.path.join(cc.REPORT_DIR, "config.json")) as fh:
260
+ return bool(json.load(fh).get("excise"))
261
+ except (OSError, ValueError, AttributeError):
262
+ return False
263
+
264
+
265
+ def describe(res: dict) -> str:
266
+ n = res["removed"]
267
+ parts = [f"{n['declined_records']} declined response record(s)", f"{n['notice_responses']} notice response(s)",
268
+ f"{n['meta_notices']} meta notice(s)", f"{n['refusal_records']} refusal record(s)"]
269
+ if n["tool_results"]:
270
+ parts.append(f"{n['tool_results']} tool result(s) of declined calls")
271
+ s = (f"clean copy {res['fork_session']} -- removed " + ", ".join(parts)
272
+ + f"; kept {n['kept_records']} records, your messages unchanged.")
273
+ if n["tool_calls_that_ran"]:
274
+ s += (f" {n['tool_calls_that_ran']} tool call(s) inside a declined response had already run;"
275
+ f" their effects on disk remain.")
276
+ return s
277
+
278
+
279
+ def main(argv: list[str] | None = None) -> int:
280
+ ap = argparse.ArgumentParser(prog="refusectomy excise", description=__doc__,
281
+ formatter_class=argparse.RawDescriptionHelpFormatter)
282
+ ap.add_argument("--session", help="session id (default: the newest in --cwd)")
283
+ ap.add_argument("--cwd", default=os.getcwd())
284
+ ap.add_argument("--dry-run", action="store_true", help="show what would be removed, write nothing")
285
+ ap.add_argument("--json", action="store_true")
286
+ a = ap.parse_args(argv)
287
+ sid = a.session or cc.current_session_id()
288
+ path = cc.session_transcript(sid, a.cwd) if sid else None
289
+ if path is None and not a.session:
290
+ sid, path = cc.newest_session(a.cwd)
291
+ if not path:
292
+ print("refusectomy excise: no such session transcript", file=sys.stderr)
293
+ return 2
294
+ res = make_clean_copy(path, sid, dry_run=a.dry_run)
295
+ if a.json:
296
+ print(json.dumps(res, indent=2))
297
+ elif not res["removed"]["declined_requests"]:
298
+ print(f"session {sid}: no declines -- nothing to excise.")
299
+ elif res["problems"]:
300
+ print("refusectomy excise: the copy failed verification, nothing written:", file=sys.stderr)
301
+ for p in res["problems"][:10]:
302
+ print(" " + p, file=sys.stderr)
303
+ return 1
304
+ else:
305
+ print(describe(res))
306
+ if res.get("written"):
307
+ print(f"resume it: claude --resume {res['fork_session']} (or /resume inside Claude Code)")
308
+ else:
309
+ print("(dry run: nothing written)")
310
+ return 0
@@ -0,0 +1,253 @@
1
+ """How each model API says "declined", read from the wire.
2
+
3
+ Each provider marks it differently, so each gets a small interpreter; everything above
4
+ this module is provider-neutral.
5
+
6
+ anthropic stop_reason "refusal" (stop_details.category names the classifier) in the
7
+ message, or in the streamed message_delta; an "error" event otherwise
8
+ openai Chat Completions: finish_reason "content_filter", or a "refusal" on the
9
+ message / delta. Responses: an output item of type "refusal", or status
10
+ "incomplete" with incomplete_details.reason "content_filter"
11
+ gemini candidates[].finishReason SAFETY / PROHIBITED_CONTENT / BLOCKLIST / SPII /
12
+ IMAGE_SAFETY, or promptFeedback.blockReason; RECITATION is reported apart
13
+
14
+ `ResponseReader` takes a response's bytes as they arrive -- server-sent events parsed
15
+ incrementally, or a JSON body buffered up to a cap -- and keeps an `Outcome`: enums and
16
+ identifiers only. Text never leaves the reader; the caller digests what it needs.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import re
22
+ from dataclasses import asdict, dataclass
23
+
24
+ KINDS = ("ok", "unknown", "error", "recitation", "filtered", "refusal")
25
+ RANK = {k: i for i, k in enumerate(KINDS)}
26
+ GEMINI_BLOCKS = {"SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", "SPII", "IMAGE_SAFETY",
27
+ "IMAGE_PROHIBITED_CONTENT"}
28
+ GEMINI_RECITATION = {"RECITATION", "IMAGE_RECITATION"}
29
+ _EVENT_END = re.compile(rb"(?:\r\n|\r|\n){2}")
30
+
31
+
32
+ @dataclass
33
+ class Outcome:
34
+ provider: str
35
+ kind: str = "ok" # ok | unknown | error | recitation | filtered | refusal
36
+ reason: str | None = None # the provider's own enum: stop / finish / block reason
37
+ category: str | None = None # classifier category, where the provider names one
38
+ model: str | None = None
39
+ response_id: str | None = None
40
+ mid_stream: bool | None = None # had output begun when it was declined?
41
+ output_started: bool = False
42
+
43
+ def mark(self, kind: str, reason: str | None = None, category: str | None = None) -> None:
44
+ """Record a finding; the most severe one seen in a response wins."""
45
+ if RANK[kind] > RANK[self.kind]:
46
+ self.kind, self.reason = kind, reason
47
+ self.category = category or self.category
48
+ self.mid_stream = self.output_started
49
+
50
+ def finish(self, reason: str | None) -> None:
51
+ if reason and self.kind == "ok":
52
+ self.reason = str(reason)
53
+
54
+ def as_dict(self) -> dict:
55
+ d = asdict(self)
56
+ d.pop("output_started")
57
+ return d
58
+
59
+
60
+ def _anthropic_stop(o: Outcome, stop, details) -> None:
61
+ if stop == "refusal":
62
+ cat = details.get("category") if isinstance(details, dict) else None
63
+ o.mark("refusal", "refusal", cat)
64
+ else:
65
+ o.finish(stop)
66
+
67
+
68
+ def _anthropic(o: Outcome, ev: dict) -> None:
69
+ t = ev.get("type")
70
+ if t == "message_start":
71
+ m = ev.get("message") if isinstance(ev.get("message"), dict) else {}
72
+ o.model, o.response_id = m.get("model") or o.model, m.get("id") or o.response_id
73
+ elif t in ("content_block_start", "content_block_delta"):
74
+ o.output_started = True
75
+ elif t == "message_delta":
76
+ d = ev.get("delta") if isinstance(ev.get("delta"), dict) else {}
77
+ _anthropic_stop(o, d.get("stop_reason"), d.get("stop_details"))
78
+ elif t == "message":
79
+ o.model, o.response_id = ev.get("model") or o.model, ev.get("id") or o.response_id
80
+ o.output_started = bool(ev.get("content"))
81
+ _anthropic_stop(o, ev.get("stop_reason"), ev.get("stop_details"))
82
+ elif t == "error":
83
+ err = ev.get("error") if isinstance(ev.get("error"), dict) else {}
84
+ o.mark("error", str(err.get("type") or "error"))
85
+
86
+
87
+ def _openai(o: Outcome, ev: dict) -> None:
88
+ o.model = ev.get("model") if isinstance(ev.get("model"), str) else o.model
89
+ if isinstance(ev.get("id"), str):
90
+ o.response_id = ev["id"]
91
+ for ch in ev.get("choices") or []: # Chat Completions
92
+ if not isinstance(ch, dict):
93
+ continue
94
+ msg = ch.get("message") or ch.get("delta") or {}
95
+ if isinstance(msg, dict):
96
+ if msg.get("content") or msg.get("tool_calls"):
97
+ o.output_started = True
98
+ if msg.get("refusal"):
99
+ o.mark("refusal", "refusal")
100
+ fr = ch.get("finish_reason")
101
+ if fr == "content_filter":
102
+ o.mark("filtered", fr)
103
+ else:
104
+ o.finish(fr)
105
+ t = ev.get("type") if isinstance(ev.get("type"), str) else ""
106
+ if t.startswith("response.refusal"): # Responses, streamed
107
+ o.mark("refusal", "refusal")
108
+ elif t.startswith("response.output_text") or t.startswith("response.function_call"):
109
+ o.output_started = True
110
+ resp = ev.get("response") if isinstance(ev.get("response"), dict) else (
111
+ ev if ev.get("object") == "response" else None)
112
+ if resp: # Responses, body or final event
113
+ o.model = resp.get("model") or o.model
114
+ o.response_id = resp.get("id") or o.response_id
115
+ for item in resp.get("output") or []:
116
+ for c in (item.get("content") or []) if isinstance(item, dict) else []:
117
+ if isinstance(c, dict) and c.get("type") == "output_text":
118
+ o.output_started = True
119
+ elif isinstance(c, dict) and c.get("type") == "refusal":
120
+ o.mark("refusal", "refusal")
121
+ inc = resp.get("incomplete_details") if isinstance(resp.get("incomplete_details"), dict) else {}
122
+ if resp.get("status") == "incomplete" and inc.get("reason") == "content_filter":
123
+ o.mark("filtered", "content_filter")
124
+ else:
125
+ o.finish(resp.get("status"))
126
+ err = ev.get("error")
127
+ if isinstance(err, dict):
128
+ code = err.get("code") or err.get("type") or "error"
129
+ o.mark("filtered" if code == "content_filter" else "error", str(code))
130
+
131
+
132
+ def _gemini(o: Outcome, ev: dict) -> None:
133
+ o.model = ev.get("modelVersion") or o.model
134
+ o.response_id = ev.get("responseId") or o.response_id
135
+ pf = ev.get("promptFeedback") if isinstance(ev.get("promptFeedback"), dict) else {}
136
+ br = pf.get("blockReason")
137
+ if br and br != "BLOCK_REASON_UNSPECIFIED":
138
+ o.mark("filtered", str(br), "prompt")
139
+ for c in ev.get("candidates") or []:
140
+ if not isinstance(c, dict):
141
+ continue
142
+ if isinstance(c.get("content"), dict) and c["content"].get("parts"):
143
+ o.output_started = True
144
+ fr = c.get("finishReason")
145
+ if fr in GEMINI_BLOCKS:
146
+ o.mark("filtered", fr)
147
+ elif fr in GEMINI_RECITATION:
148
+ o.mark("recitation", fr)
149
+ else:
150
+ o.finish(fr)
151
+ err = ev.get("error")
152
+ if isinstance(err, dict):
153
+ o.mark("error", str(err.get("status") or err.get("code") or "error"))
154
+
155
+
156
+ INTERPRET = {"anthropic": _anthropic, "openai": _openai, "gemini": _gemini}
157
+
158
+
159
+ class ResponseReader:
160
+ """Feed it a response's bytes as they arrive; `close()` returns the Outcome."""
161
+
162
+ MAX_BODY = 64 << 20
163
+
164
+ def __init__(self, provider: str, content_type: str = ""):
165
+ if provider not in INTERPRET:
166
+ raise ValueError(f"unknown provider {provider!r}")
167
+ self.outcome = Outcome(provider)
168
+ self.sse = "event-stream" in (content_type or "").lower()
169
+ self._buf = bytearray()
170
+ self._overflow = False
171
+
172
+ def feed(self, chunk: bytes) -> None:
173
+ if self.sse:
174
+ self._buf += chunk
175
+ while True:
176
+ m = _EVENT_END.search(self._buf)
177
+ if not m:
178
+ break
179
+ block = bytes(self._buf[:m.start()])
180
+ del self._buf[:m.end()]
181
+ self._event(block)
182
+ elif not self._overflow:
183
+ self._buf += chunk
184
+ if len(self._buf) > self.MAX_BODY:
185
+ self._overflow = True
186
+ self._buf = bytearray()
187
+
188
+ def close(self) -> Outcome:
189
+ if self.sse and self._buf.strip():
190
+ self._event(bytes(self._buf))
191
+ elif not self.sse and self._buf and not self._overflow:
192
+ try:
193
+ self._json(json.loads(self._buf.decode("utf-8", "replace")))
194
+ except ValueError:
195
+ pass
196
+ if self._overflow and self.outcome.kind == "ok":
197
+ self.outcome.kind = "unknown"
198
+ self._buf = bytearray()
199
+ return self.outcome
200
+
201
+ def _event(self, block: bytes) -> None:
202
+ data = []
203
+ for line in block.decode("utf-8", "replace").splitlines():
204
+ if line.startswith("data:"):
205
+ v = line[5:]
206
+ data.append(v[1:] if v.startswith(" ") else v)
207
+ payload = "\n".join(data).strip()
208
+ if payload and payload != "[DONE]":
209
+ try:
210
+ self._json(json.loads(payload))
211
+ except ValueError:
212
+ pass
213
+
214
+ def _json(self, ev) -> None:
215
+ if isinstance(ev, list): # Gemini's non-SSE stream is a JSON array
216
+ for x in ev:
217
+ self._json(x)
218
+ elif isinstance(ev, dict):
219
+ INTERPRET[self.outcome.provider](self.outcome, ev)
220
+
221
+
222
+ def _texts(content) -> str:
223
+ if isinstance(content, str):
224
+ return content
225
+ if isinstance(content, list):
226
+ return " ".join(str(b.get("text", "")) for b in content
227
+ if isinstance(b, dict) and b.get("type") in (None, "text", "input_text")
228
+ and isinstance(b.get("text"), str))
229
+ return ""
230
+
231
+
232
+ def last_user_text(provider: str, body: dict) -> str:
233
+ """The text of the last user message in a request body, to be digested -- never kept."""
234
+ if not isinstance(body, dict):
235
+ return ""
236
+ if provider == "gemini":
237
+ for c in reversed(body.get("contents") or []):
238
+ if isinstance(c, dict) and c.get("role", "user") == "user":
239
+ return " ".join(p.get("text", "") for p in c.get("parts") or []
240
+ if isinstance(p, dict) and isinstance(p.get("text"), str))
241
+ return ""
242
+ if provider == "openai" and "input" in body and "messages" not in body:
243
+ inp = body.get("input")
244
+ if isinstance(inp, str):
245
+ return inp
246
+ for m in reversed(inp if isinstance(inp, list) else []):
247
+ if isinstance(m, dict) and m.get("role") == "user":
248
+ return _texts(m.get("content"))
249
+ return ""
250
+ for m in reversed(body.get("messages") or []):
251
+ if isinstance(m, dict) and m.get("role") == "user":
252
+ return _texts(m.get("content"))
253
+ return ""