tokensafe 2.8.4 → 3.0.0

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/src/proxy.py CHANGED
@@ -7,6 +7,8 @@ Endpoint: http://127.0.0.1:8765/v1
7
7
 
8
8
  import sys
9
9
  import os
10
+ import re
11
+ import io
10
12
  import json
11
13
  import time
12
14
  import queue
@@ -22,11 +24,12 @@ sys.path.insert(0, BASE_DIR)
22
24
  from src.compactor import PromptCompactor
23
25
  from src.metrics import MetricsTracker
24
26
  from src.dashboard import Dashboard
25
- from src.loop_detector import LoopDetector
26
27
  from src.secret_redactor import SecretRedactor
27
28
  from src.graph_engine import GraphEngine
28
29
  from src.cache_normalizer import PromptCacheNormalizer
29
30
  from src.governor import ContextGovernor
31
+ from src.result_ledger import fold_tool_results
32
+ from src.tool_pruner import _tool_name, apply_subset, detect_prune_miss
30
33
  from src.paths import resolve_data_dir
31
34
 
32
35
  DEFAULT_PORT = 8765
@@ -311,6 +314,302 @@ def _translate_anthropic_error_body(err_bytes: bytes) -> bytes:
311
314
  return err_bytes
312
315
 
313
316
 
317
+ def _translate_openai_error_body_to_anthropic(err_bytes: bytes) -> bytes:
318
+ """Maps an OpenAI error envelope {"error":{message,type}} onto the Anthropic one."""
319
+ try:
320
+ data = json.loads(err_bytes.decode("utf-8"))
321
+ if (
322
+ isinstance(data, dict)
323
+ and isinstance(data.get("error"), dict)
324
+ and data.get("type") != "error" # already Anthropic envelope
325
+ ):
326
+ inner = data["error"]
327
+ return json.dumps({
328
+ "type": "error",
329
+ "error": {"type": str(inner.get("type") or "api_error"), "message": str(inner.get("message") or "Upstream error")},
330
+ }).encode("utf-8")
331
+ except Exception:
332
+ pass
333
+ return err_bytes
334
+
335
+
336
+ def _translate_anthropic_payload_to_openai(payload: Dict[str, Any]) -> Dict[str, Any]:
337
+ """Converts an Anthropic /v1/messages request payload into the OpenAI chat-completions
338
+ shape used by the internal optimization pipeline (ledger fold, governor, cache
339
+ normalizer operate on the OpenAI form)."""
340
+ out_messages: List[Dict[str, Any]] = []
341
+
342
+ def _text_blocks(content: Any) -> str:
343
+ if isinstance(content, str):
344
+ return content
345
+ if isinstance(content, list):
346
+ parts = []
347
+ for b in content:
348
+ if isinstance(b, dict) and isinstance(b.get("text"), str):
349
+ parts.append(b["text"])
350
+ return "\n".join(parts)
351
+ return ""
352
+
353
+ system_text = _text_blocks(payload.get("system"))
354
+ if system_text:
355
+ out_messages.append({"role": "system", "content": system_text})
356
+
357
+ for msg in payload.get("messages") or []:
358
+ if not isinstance(msg, dict):
359
+ continue
360
+ role = msg.get("role")
361
+ content = msg.get("content")
362
+ if role == "assistant":
363
+ text_parts: List[str] = []
364
+ tool_calls = []
365
+ blocks = content if isinstance(content, list) else ([{"type": "text", "text": content}] if isinstance(content, str) else [])
366
+ for blk in blocks:
367
+ if not isinstance(blk, dict):
368
+ continue
369
+ if blk.get("type") == "text" and isinstance(blk.get("text"), str):
370
+ text_parts.append(blk["text"])
371
+ elif blk.get("type") == "tool_use":
372
+ tool_calls.append({
373
+ "id": blk.get("id") or f"call_{blk.get('name', 'tool')}",
374
+ "type": "function",
375
+ "function": {
376
+ "name": blk.get("name") or "unknown",
377
+ "arguments": json.dumps(blk.get("input") or {}, ensure_ascii=False),
378
+ },
379
+ })
380
+ m: Dict[str, Any] = {"role": "assistant", "content": "\n\n".join(text_parts) if text_parts else None}
381
+ if tool_calls:
382
+ m["tool_calls"] = tool_calls
383
+ out_messages.append(m)
384
+ elif role == "user":
385
+ blocks = content if isinstance(content, list) else ([{"type": "text", "text": content}] if isinstance(content, str) else [])
386
+ pending_results: List[Dict[str, Any]] = []
387
+ for blk in blocks:
388
+ if not isinstance(blk, dict):
389
+ continue
390
+ if blk.get("type") == "tool_result":
391
+ tc = blk.get("content")
392
+ text = tc if isinstance(tc, str) else _text_blocks(tc) if isinstance(tc, list) else json.dumps(tc, ensure_ascii=False)
393
+ pending_results.append({"role": "tool", "tool_call_id": blk.get("tool_use_id") or "toolu_call", "content": text})
394
+ elif blk.get("type") == "text" and isinstance(blk.get("text"), str):
395
+ pending_results.append({"role": "user", "content": blk["text"]})
396
+ out_messages.extend(pending_results)
397
+ if not pending_results:
398
+ out_messages.append({"role": "user", "content": ""})
399
+
400
+ out: Dict[str, Any] = {
401
+ "model": payload.get("model") or "gpt-4o-mini",
402
+ "max_tokens": payload.get("max_tokens") if isinstance(payload.get("max_tokens"), int) and payload["max_tokens"] > 0 else 4096,
403
+ "messages": out_messages,
404
+ }
405
+ if isinstance(payload.get("temperature"), (int, float)):
406
+ out["temperature"] = payload["temperature"]
407
+ if isinstance(payload.get("top_p"), (int, float)):
408
+ out["top_p"] = payload["top_p"]
409
+ if payload.get("stop_sequences"):
410
+ out["stop"] = payload["stop_sequences"]
411
+ if isinstance(payload.get("stream"), bool):
412
+ out["stream"] = payload["stream"]
413
+ tools = payload.get("tools")
414
+ if isinstance(tools, list) and tools:
415
+ oai_tools = []
416
+ for t in tools:
417
+ if not isinstance(t, dict) or not t.get("name"):
418
+ continue
419
+ if isinstance(t.get("parameters"), dict) and t.get("function") is None:
420
+ # already OpenAI-shaped
421
+ oai_tools.append(t)
422
+ continue
423
+ oai_tools.append({
424
+ "type": "function",
425
+ "function": {
426
+ "name": t["name"],
427
+ "description": t.get("description") or "",
428
+ "parameters": t.get("input_schema") if isinstance(t.get("input_schema"), dict) else {"type": "object", "properties": {}},
429
+ },
430
+ })
431
+ if oai_tools:
432
+ out["tools"] = oai_tools
433
+ tc = payload.get("tool_choice")
434
+ if tc == "required" or (isinstance(tc, dict) and tc.get("type") == "any"):
435
+ out["tool_choice"] = "required"
436
+ elif isinstance(tc, dict) and tc.get("type") == "tool" and tc.get("name"):
437
+ out["tool_choice"] = {"type": "function", "function": {"name": tc["name"]}}
438
+ return out
439
+
440
+
441
+ def _translate_openai_json_to_anthropic(resp_json: Dict[str, Any], fallback_model: str = "") -> Dict[str, Any]:
442
+ """Converts a non-streaming OpenAI chat.completion into an Anthropic /v1/messages response."""
443
+ if not isinstance(resp_json, dict) or resp_json.get("object") not in (None, "chat.completion"):
444
+ return resp_json # already Anthropic-shaped or unknown envelope
445
+ choice = (resp_json.get("choices") or [{}])[0]
446
+ msg = choice.get("message") or {}
447
+ blocks: List[Dict[str, Any]] = []
448
+ if isinstance(msg.get("content"), str) and msg["content"]:
449
+ blocks.append({"type": "text", "text": msg["content"]})
450
+ for tc in msg.get("tool_calls") or []:
451
+ if not isinstance(tc, dict):
452
+ continue
453
+ fn = tc.get("function") or {}
454
+ try:
455
+ tool_input = json.loads(fn.get("arguments") or "{}")
456
+ if not isinstance(tool_input, dict):
457
+ tool_input = {"_raw": tool_input}
458
+ except Exception:
459
+ tool_input = {"_raw": fn.get("arguments")}
460
+ blocks.append({"type": "tool_use", "id": tc.get("id") or "toolu_call", "name": fn.get("name") or "unknown", "input": tool_input})
461
+ if not blocks:
462
+ blocks = [{"type": "text", "text": ""}]
463
+ usage = resp_json.get("usage") or {}
464
+ finish = choice.get("finish_reason")
465
+ stop_reason = {"stop": "end_turn", "length": "max_tokens", "tool_calls": "tool_use"}.get(finish, "end_turn" if finish else None)
466
+ out: Dict[str, Any] = {
467
+ "id": resp_json.get("id") or f"msg_{int(time.time() * 1000)}",
468
+ "type": "message",
469
+ "role": "assistant",
470
+ "model": resp_json.get("model") or fallback_model,
471
+ "content": blocks,
472
+ "stop_reason": stop_reason,
473
+ "usage": {
474
+ "input_tokens": int(usage.get("prompt_tokens") or 0),
475
+ "output_tokens": int(usage.get("completion_tokens") or 0),
476
+ },
477
+ }
478
+ return out
479
+
480
+
481
+ class _OpenAISSEToAnthropicTranslator:
482
+ """Converts an OpenAI chat.completion.chunk SSE stream into Anthropic /v1/messages SSE events."""
483
+
484
+ def __init__(self, model: str = ""):
485
+ self.model = model or "claude"
486
+ self._buf = b""
487
+ self._started = False
488
+ self._text_open = False
489
+ self._tool_open: Dict[int, bool] = {}
490
+ self._block_index = 0
491
+ self._msg_id = f"msg_{int(time.time() * 1000)}"
492
+ self._done = False
493
+ self._finished = False
494
+ self._usage_out = 0
495
+
496
+ def _event(self, name: str, data: Dict[str, Any]) -> bytes:
497
+ return (f"event: {name}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n").encode("utf-8")
498
+
499
+ def _start_message(self) -> bytes:
500
+ self._started = True
501
+ return self._event("message_start", {
502
+ "type": "message_start",
503
+ "message": {
504
+ "id": self._msg_id, "type": "message", "role": "assistant",
505
+ "model": self.model, "content": [],
506
+ "usage": {"input_tokens": 0, "output_tokens": 0},
507
+ },
508
+ })
509
+
510
+ def _handle_chunk(self, chunk: Dict[str, Any]) -> bytes:
511
+ out = b""
512
+ if not self._started:
513
+ out += self._start_message()
514
+ choices = chunk.get("choices") or []
515
+ choice = choices[0] if choices else {}
516
+ delta = choice.get("delta") or {}
517
+ if isinstance(delta.get("content"), str) and delta["content"]:
518
+ if not self._text_open:
519
+ out += self._event("content_block_start", {"type": "content_block_start", "index": self._block_index, "content_block": {"type": "text", "text": ""}})
520
+ self._text_open = True
521
+ out += self._event("content_block_delta", {"type": "content_block_delta", "index": self._block_index, "delta": {"type": "text_delta", "text": delta["content"]}})
522
+ for tc in delta.get("tool_calls") or []:
523
+ if not isinstance(tc, dict):
524
+ continue
525
+ idx = int(tc.get("index") or 0)
526
+ if idx not in self._tool_open:
527
+ if self._text_open:
528
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
529
+ self._text_open = False
530
+ self._block_index += 1
531
+ self._tool_open[idx] = True
532
+ fn = tc.get("function") or {}
533
+ out += self._event("content_block_start", {
534
+ "type": "content_block_start", "index": self._block_index,
535
+ "content_block": {"type": "tool_use", "id": tc.get("id") or f"toolu_{idx}", "name": fn.get("name") or "unknown", "input": {}},
536
+ })
537
+ fn = tc.get("function") or {}
538
+ if fn.get("arguments"):
539
+ out += self._event("content_block_delta", {"type": "content_block_delta", "index": self._block_index, "delta": {"type": "input_json_delta", "partial_json": fn["arguments"]}})
540
+ finish = choice.get("finish_reason")
541
+ usage = chunk.get("usage") or {}
542
+ if usage.get("completion_tokens"):
543
+ self._usage_out = int(usage["completion_tokens"])
544
+ if finish and not self._finished:
545
+ self._finished = True
546
+ if self._text_open:
547
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
548
+ self._text_open = False
549
+ stop_reason = {"stop": "end_turn", "length": "max_tokens", "tool_calls": "tool_use"}.get(finish, "end_turn")
550
+ out += self._event("message_delta", {
551
+ "type": "message_delta",
552
+ "delta": {"stop_reason": stop_reason, "stop_sequence": None},
553
+ "usage": {"output_tokens": self._usage_out},
554
+ })
555
+ return out
556
+
557
+ def feed(self, chunk: bytes) -> bytes:
558
+ if not chunk:
559
+ return b""
560
+ self._buf += chunk
561
+ out = b""
562
+ while True:
563
+ nl = self._buf.find(b"\n")
564
+ if nl < 0:
565
+ break
566
+ line = self._buf[:nl].rstrip(b"\r")
567
+ self._buf = self._buf[nl + 1:]
568
+ if not line:
569
+ continue
570
+ if not line.startswith(b"data:"):
571
+ continue
572
+ body = line[5:].strip()
573
+ if body == b"[DONE]":
574
+ if not self._done:
575
+ self._done = True
576
+ if self._text_open:
577
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
578
+ out += self._event("message_delta", {
579
+ "type": "message_delta",
580
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
581
+ "usage": {"output_tokens": self._usage_out},
582
+ })
583
+ out += self._event("message_stop", {"type": "message_stop"})
584
+ continue
585
+ try:
586
+ data = json.loads(body.decode("utf-8"))
587
+ except Exception:
588
+ continue
589
+ if isinstance(data, dict):
590
+ out += self._handle_chunk(data)
591
+ return out
592
+
593
+ def flush(self) -> bytes:
594
+ """Emits final Anthropic close events if the upstream ended abruptly."""
595
+ if self._done and self._started:
596
+ return b""
597
+ out = b""
598
+ if not self._started:
599
+ out += self._start_message()
600
+ if self._text_open:
601
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
602
+ if not self._done:
603
+ out += self._event("message_delta", {
604
+ "type": "message_delta",
605
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
606
+ "usage": {"output_tokens": self._usage_out},
607
+ })
608
+ out += self._event("message_stop", {"type": "message_stop"})
609
+ self._done = True
610
+ return out
611
+
612
+
314
613
  class _AnthropicSSETranslator:
315
614
  """Converts an Anthropic /v1/messages SSE event stream into OpenAI chat.completion.chunk SSE lines."""
316
615
 
@@ -432,6 +731,18 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
432
731
  self.wfile.write(payload_bytes)
433
732
  return
434
733
 
734
+ if self.path in ("/v1/models", "/models"):
735
+ # Some agent harnesses probe /v1/models on connect before chatting.
736
+ # The proxy is transparent about upstream models, so we serve a
737
+ # minimal OpenAI-shaped empty catalog instead of a 404.
738
+ body = json.dumps({"object": "list", "data": []}).encode("utf-8")
739
+ self.send_response(200)
740
+ self.send_header("Content-Type", "application/json")
741
+ self.send_header("Content-Length", str(len(body)))
742
+ self.end_headers()
743
+ self.wfile.write(body)
744
+ return
745
+
435
746
  if self.path in ("/", "/dashboard", "/dashboard.html"):
436
747
  tracker = MetricsTracker()
437
748
  html_bytes = Dashboard(tracker).render_html().encode("utf-8")
@@ -496,10 +807,41 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
496
807
  if self.path.startswith("/v1/chat/completions"):
497
808
  self._touch_proxy_heartbeat()
498
809
  self.handle_chat_completions()
810
+ elif self.path.startswith("/v1/messages"):
811
+ # Anthropic-shape ingest (Claude Code points ANTHROPIC_BASE_URL here):
812
+ # translate to the internal OpenAI form, run the same optimization
813
+ # pipeline, and translate the response back to Anthropic shape.
814
+ if not self._ingest_anthropic_body():
815
+ return
816
+ self._touch_proxy_heartbeat()
817
+ self.handle_chat_completions()
499
818
  else:
500
819
  self.send_response(404)
501
820
  self.end_headers()
502
821
 
822
+ def _ingest_anthropic_body(self) -> bool:
823
+ """Translates the request body from Anthropic /v1/messages shape to the
824
+ internal OpenAI chat-completions shape. Returns False after sending an
825
+ error response when the payload is invalid."""
826
+ try:
827
+ body = self._read_request_body()
828
+ payload = json.loads(body.decode("utf-8"))
829
+ if not isinstance(payload, dict) or not isinstance(payload.get("messages"), list):
830
+ raise ValueError("JSON body must be an Anthropic messages object")
831
+ except Exception as e:
832
+ self._send_json_error(400, f"Invalid /v1/messages payload: {e}")
833
+ return False
834
+ try:
835
+ openai_payload = _translate_anthropic_payload_to_openai(payload)
836
+ except Exception as e:
837
+ self._send_json_error(400, f"Failed to translate Anthropic payload: {e}")
838
+ return False
839
+ self._client_shape = "anthropic"
840
+ # Hand the translated body to handle_chat_completions directly: the
841
+ # original Content-Length header no longer matches the new bytes.
842
+ self._ingested_body = json.dumps(openai_payload, ensure_ascii=False).encode("utf-8")
843
+ return True
844
+
503
845
  @staticmethod
504
846
  def _touch_proxy_heartbeat():
505
847
  """Marks the proxy as actively serving agent traffic.
@@ -546,7 +888,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
546
888
 
547
889
  def handle_chat_completions(self):
548
890
  try:
549
- body = self._read_request_body()
891
+ body = getattr(self, "_ingested_body", None)
892
+ if body is None:
893
+ body = self._read_request_body()
550
894
  payload = json.loads(body.decode("utf-8"))
551
895
  if not isinstance(payload, dict):
552
896
  raise ValueError("JSON body must be an object")
@@ -566,6 +910,21 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
566
910
  if secrets_scrubbed > 0:
567
911
  print(f"[TokenSafe] Scrubbed {secrets_scrubbed} sensitive secret(s) from payload before transmission.")
568
912
 
913
+ # 1.5 Tool Result Ledger: fold aged, oversized tool results into compact
914
+ # anchors + local archive (idempotent via marker; cache-aware). Runs
915
+ # before the governor so the governor sees the lightened mass.
916
+ if messages and not is_quota_exceeded:
917
+ try:
918
+ messages, ledger_stats = fold_tool_results(messages)
919
+ payload["messages"] = messages
920
+ if ledger_stats.get("folded"):
921
+ print(
922
+ f"[TokenSafe] Tool Result Ledger: folded {ledger_stats['folded']} result(s), "
923
+ f"~{ledger_stats['saved_tokens']} input tokens lighter."
924
+ )
925
+ except Exception:
926
+ pass
927
+
569
928
  # 2. Ingress Optimization: REPLACE the last user message with its TOCP form.
570
929
  # Paused when Community 500k monthly measured quota is exceeded.
571
930
  target_symbol = None
@@ -626,6 +985,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
626
985
 
627
986
  upstream_url, resolved_key = self._resolve_upstream(conf_keys, custom_url)
628
987
  provider = self._detect_provider(upstream_url)
988
+ # Client shape: "anthropic" when the request arrived on /v1/messages
989
+ # (Claude Code via ANTHROPIC_BASE_URL), else OpenAI-native.
990
+ client_anthropic = getattr(self, "_client_shape", "") == "anthropic"
991
+ # Optional upstream model mapping: route client model names (e.g. claude-*)
992
+ # to the model the upstream account actually serves.
993
+ upstream_model = os.environ.get("TOKENSAFE_UPSTREAM_MODEL", "").strip()
994
+ if upstream_model:
995
+ payload["model"] = upstream_model
629
996
 
630
997
  # 5. Epoch-Aware Context Governor (runs BEFORE cache normalization so breakpoints stay valid)
631
998
  if messages and not is_quota_exceeded:
@@ -639,6 +1006,27 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
639
1006
  if gov_stats.get("throttled"):
640
1007
  BROADCASTER.publish("governor_throttle", gov_stats)
641
1008
 
1009
+ # 5.5 Session-stable tool pruning (opt-in, TOKENSAFE_TOOL_PRUNING=1):
1010
+ # relevance subset chosen once per pseudo-session and kept
1011
+ # byte-stable for the whole session (KV-cache safe). The agent
1012
+ # still knows ALL its tools — pruned-tool calls still execute;
1013
+ # we only measure the miss rate.
1014
+ sent_tool_names = None
1015
+ if isinstance(payload.get("tools"), list) and payload["tools"] and not is_quota_exceeded:
1016
+ sent_tool_names = {n for n in (_tool_name(t) for t in payload["tools"]) if n}
1017
+ try:
1018
+ pruned_tools, prune_meta = apply_subset(
1019
+ payload["tools"],
1020
+ payload.get("messages") or [],
1021
+ str(payload.get("model") or ""),
1022
+ )
1023
+ if prune_meta.get("applied"):
1024
+ payload["tools"] = pruned_tools
1025
+ sent_tool_names = {n for n in (_tool_name(t) for t in pruned_tools) if n}
1026
+ print(f"[TokenSafe] Tool pruning: {prune_meta.get('pool')} → {prune_meta.get('subset')} tools (session-stable).")
1027
+ except Exception:
1028
+ pass
1029
+
642
1030
  # 6. Prompt Cache Prefix & Tool Normalization (multi-breakpoint + deterministic ordering)
643
1031
  if not is_quota_exceeded:
644
1032
  if messages:
@@ -658,6 +1046,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
658
1046
  )
659
1047
 
660
1048
  if provider == "anthropic":
1049
+ # Outbound OpenAI->Anthropic translation is skipped when the CLIENT
1050
+ # itself speaks Anthropic (ingest): the pipeline ran on the internal
1051
+ # OpenAI form, and this puts it back into Anthropic shape for upstream.
661
1052
  payload = _translate_openai_payload_to_anthropic(payload)
662
1053
 
663
1054
  headers = {"Content-Type": "application/json"}
@@ -693,12 +1084,25 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
693
1084
  if is_stream:
694
1085
  self.send_header("Cache-Control", "no-cache")
695
1086
  self.end_headers()
696
- sse_t = _AnthropicSSETranslator(str(payload.get("model") or "")) if provider == "anthropic" else None
1087
+ # Stream translation matrix:
1088
+ # anthropic upstream + openai client -> Anthropic SSE -> OpenAI chunks
1089
+ # openai upstream + anthropic client -> OpenAI chunks -> Anthropic SSE
1090
+ # otherwise -> byte passthrough
1091
+ sse_t = None
1092
+ if provider == "anthropic" and not client_anthropic:
1093
+ sse_t = _AnthropicSSETranslator(str(payload.get("model") or ""))
1094
+ elif provider != "anthropic" and client_anthropic:
1095
+ sse_t = _OpenAISSEToAnthropicTranslator(str(payload.get("model") or ""))
697
1096
  reader = getattr(resp, "read1", None) or resp.read
1097
+ # Best-effort usage capture from the stream tail: Anthropic
1098
+ # reports final usage in the trailing message_delta events.
1099
+ sse_tail = bytearray() if sse_t is not None else None
698
1100
  while True:
699
1101
  try:
700
1102
  chunk = reader(4096)
701
1103
  except TypeError:
1104
+ # Defensive fallback for readers without sized reads:
1105
+ # buffer the whole stream, emit once (no streaming).
702
1106
  chunk = resp.read()
703
1107
  if chunk:
704
1108
  out = sse_t.feed(chunk) if sse_t else chunk
@@ -708,6 +1112,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
708
1112
  break
709
1113
  if not chunk:
710
1114
  break
1115
+ if sse_tail is not None:
1116
+ sse_tail.extend(chunk)
1117
+ if len(sse_tail) > 65536:
1118
+ del sse_tail[: len(sse_tail) - 65536]
711
1119
  out = sse_t.feed(chunk) if sse_t else chunk
712
1120
  if out:
713
1121
  self.wfile.write(out)
@@ -717,9 +1125,24 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
717
1125
  if tail:
718
1126
  self.wfile.write(tail)
719
1127
  self.wfile.flush()
1128
+ # Parse trailing usage (non-fatal; non-Anthropic streams skip)
1129
+ try:
1130
+ if sse_t is not None and sse_tail:
1131
+ tail_text = sse_tail.decode("utf-8", "replace")
1132
+ m_usage = re.search(
1133
+ r'"usage":\s*\{[^}]*"(?:cache_read_input_tokens|input_tokens)":\s*(\d+)',
1134
+ tail_text,
1135
+ )
1136
+ m_cached = re.search(r'"cache_read_input_tokens":\s*(\d+)', tail_text)
1137
+ if m_cached:
1138
+ BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(m_cached.group(1))})
1139
+ elif m_usage:
1140
+ BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": 0})
1141
+ except Exception:
1142
+ pass
720
1143
  else:
721
1144
  resp_data = resp.read()
722
- if provider == "anthropic":
1145
+ if provider == "anthropic" and not client_anthropic:
723
1146
  try:
724
1147
  raw_json = json.loads(resp_data.decode("utf-8"))
725
1148
  resp_data = json.dumps(
@@ -728,6 +1151,15 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
728
1151
  ).encode("utf-8")
729
1152
  except Exception:
730
1153
  pass
1154
+ elif client_anthropic and provider != "anthropic":
1155
+ try:
1156
+ raw_json = json.loads(resp_data.decode("utf-8"))
1157
+ resp_data = json.dumps(
1158
+ _translate_openai_json_to_anthropic(raw_json, str(payload.get("model") or "")),
1159
+ ensure_ascii=False,
1160
+ ).encode("utf-8")
1161
+ except Exception:
1162
+ pass
731
1163
  self.send_header("Content-Length", str(len(resp_data)))
732
1164
  self.end_headers()
733
1165
  self.wfile.write(resp_data)
@@ -743,6 +1175,22 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
743
1175
  )
744
1176
  if cached:
745
1177
  BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(cached)})
1178
+ # Prune-miss telemetry: model called a tool outside the
1179
+ # sent subset (call still flows to the agent).
1180
+ if sent_tool_names:
1181
+ miss = detect_prune_miss(resp_json, sent_tool_names)
1182
+ if miss:
1183
+ BROADCASTER.publish("prune_miss", {"tool": miss})
1184
+ try:
1185
+ proxy_tracker.record_event(
1186
+ session_id="proxy_session",
1187
+ event_type="TOOL_PRUNE_MISS",
1188
+ original_tokens=0,
1189
+ optimized_tokens=0,
1190
+ details={"tool": miss, "subset_size": len(sent_tool_names)},
1191
+ )
1192
+ except Exception:
1193
+ pass
746
1194
  except Exception:
747
1195
  pass
748
1196
 
@@ -756,8 +1204,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
756
1204
  with e:
757
1205
  err_body = e.read()
758
1206
  ctype = e.headers.get("Content-Type", "application/json") if e.headers else "application/json"
759
- if provider == "anthropic":
1207
+ if provider == "anthropic" and not client_anthropic:
760
1208
  err_body = _translate_anthropic_error_body(err_body)
1209
+ elif client_anthropic and provider != "anthropic":
1210
+ err_body = _translate_openai_error_body_to_anthropic(err_body)
761
1211
  self.send_response(e.code)
762
1212
  self.send_header("Content-Type", ctype)
763
1213
  self.send_header("Content-Length", str(len(err_body)))