tokensafe 5.0.0 → 5.0.2

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.
Files changed (53) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/assets/logo.svg +1 -13
  5. package/hooks/claude_code_hook.py +5 -1
  6. package/hooks/cursor_hook.py +1 -1
  7. package/kimi.plugin.json +3 -2
  8. package/package.json +1 -1
  9. package/plugin.json +1 -1
  10. package/rules/AGENTS.md +4 -3
  11. package/server.json +3 -3
  12. package/skills/oumv-protocol/SKILL.md +59 -0
  13. package/skills/token-optimizer/SKILL.md +5 -3
  14. package/skills/token-optimizer/references/mcp-tools.md +1 -1
  15. package/tokensafe/adapter_core.py +62 -18
  16. package/tokensafe/atomic_io.py +20 -16
  17. package/tokensafe/auto_inject.py +2 -2
  18. package/tokensafe/backend_release.py +3 -3
  19. package/tokensafe/batch_editor.py +299 -10
  20. package/tokensafe/batch_search.py +53 -0
  21. package/tokensafe/bounded_flock.py +60 -0
  22. package/tokensafe/burn_monitor.py +60 -2
  23. package/tokensafe/call_context.py +158 -0
  24. package/tokensafe/cli.py +41 -13
  25. package/tokensafe/compactor.py +87 -5
  26. package/tokensafe/context_index.py +3 -0
  27. package/tokensafe/dashboard.py +119 -43
  28. package/tokensafe/environment_auditor.py +30 -2
  29. package/tokensafe/fts_index.py +3 -0
  30. package/tokensafe/graph_engine.py +246 -29
  31. package/tokensafe/installer.py +72 -13
  32. package/tokensafe/loop_detector.py +8 -20
  33. package/tokensafe/mcp_server.py +1084 -188
  34. package/tokensafe/metrics.py +173 -46
  35. package/tokensafe/oumv_brief.py +144 -8
  36. package/tokensafe/oumv_gateway.py +689 -222
  37. package/tokensafe/oumv_home.py +259 -0
  38. package/tokensafe/oumv_policy.py +64 -1
  39. package/tokensafe/proc_run.py +162 -0
  40. package/tokensafe/proxy.py +78 -8
  41. package/tokensafe/retrofit.py +484 -82
  42. package/tokensafe/route_index.py +2 -0
  43. package/tokensafe/savings.py +10 -2
  44. package/tokensafe/scoped_search.py +77 -0
  45. package/tokensafe/session_brief.py +17 -2
  46. package/tokensafe/stack_summary.py +73 -0
  47. package/tokensafe/syntax_guard.py +8 -2
  48. package/tokensafe/telemetry_sync.py +1 -1
  49. package/tokensafe/version_checker.py +1 -1
  50. package/tokensafe/web_reader.py +53 -4
  51. package/tokensafe/workspace_roots.py +127 -9
  52. package/assets/social/linkedin_banner.png +0 -0
  53. package/assets/social/tokensafe_logo_square.png +0 -0
@@ -0,0 +1,259 @@
1
+ """Gateway-owned OUMV state that lives outside the target repository.
2
+
3
+ Everything here is keyed by the same workspace id as the global runtime
4
+ descriptor (``sha256(realpath(workspace))[:16]``) and lives under
5
+ ``TOKENSAFE_HOME`` (default ``~/.tokensafe``), so an agent editing the repo
6
+ cannot rewrite it:
7
+
8
+ - ``policy/<ws_id>.json`` authoritative OUMV policy (deny wins over the repo copy)
9
+ - ``backups/<ws_id>/`` pre-write backups of offline mutations
10
+ - ``tokens/<ws_id>.json`` session tokens of runtimes TokenSafe launched
11
+ - ``locks/<hash>.lock`` per-file advisory write locks
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import time
20
+ from contextlib import contextmanager
21
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
22
+
23
+ POLICY_REPO_REL = os.path.join(".tokensafe", "oumv.json")
24
+ DENIED_CODE = "[OUMV PERMISSION_DENIED: -32007]"
25
+
26
+
27
+ def tokensafe_home() -> str:
28
+ return os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe")
29
+
30
+
31
+ def ws_id(workspace_dir: str) -> str:
32
+ """Same hashing as ``OUMVGateway.global_runtime_file``."""
33
+ canonical = os.path.realpath(os.path.abspath(workspace_dir))
34
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
35
+
36
+
37
+ def policy_file(workspace_dir: str) -> str:
38
+ return os.path.join(tokensafe_home(), "policy", f"{ws_id(workspace_dir)}.json")
39
+
40
+
41
+ def backup_dir(workspace_dir: str) -> str:
42
+ return os.path.join(tokensafe_home(), "backups", ws_id(workspace_dir))
43
+
44
+
45
+ def session_token_file(workspace_dir: str) -> str:
46
+ return os.path.join(tokensafe_home(), "tokens", f"{ws_id(workspace_dir)}.json")
47
+
48
+
49
+ # --------------------------------------------------------------------------- #
50
+ # Session tokens of runtimes TokenSafe launched
51
+ # --------------------------------------------------------------------------- #
52
+
53
+ def _read_json(path: str) -> Dict[str, Any]:
54
+ with open(path, "r", encoding="utf-8") as handle:
55
+ data = json.load(handle)
56
+ if not isinstance(data, dict):
57
+ raise ValueError("root is not an object")
58
+ return data
59
+
60
+
61
+ def record_session_token(workspace_dir: str, kind: str, token: str) -> str:
62
+ """Stores the token TokenSafe handed a runtime it spawned (mode 0600).
63
+
64
+ Some adapters (PHP, Node with an env token) never put the token in their
65
+ descriptor; this file is how the gateway learns what to send.
66
+ """
67
+ path = session_token_file(workspace_dir)
68
+ os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
69
+ try:
70
+ data = _read_json(path)
71
+ except (OSError, ValueError):
72
+ data = {}
73
+ data[kind] = token
74
+ data["workspaceRoot"] = os.path.realpath(os.path.abspath(workspace_dir))
75
+ data["updatedAt"] = time.time()
76
+ from tokensafe.atomic_io import write_atomic
77
+ write_atomic(path, json.dumps(data), mode=0o600)
78
+ return path
79
+
80
+
81
+ def read_session_token(workspace_dir: Optional[str], kind: str) -> Optional[str]:
82
+ if not workspace_dir:
83
+ return None
84
+ try:
85
+ value = _read_json(session_token_file(workspace_dir)).get(kind)
86
+ except (OSError, ValueError):
87
+ return None
88
+ return value.strip() if isinstance(value, str) and value.strip() else None
89
+
90
+
91
+ # --------------------------------------------------------------------------- #
92
+ # Policy: repo copy + authoritative out-of-repo copy, deny wins
93
+ # --------------------------------------------------------------------------- #
94
+
95
+ def is_policy_config_path(path: str) -> bool:
96
+ """True for any ``.tokensafe/oumv.json`` (symlinks and case folded)."""
97
+ try:
98
+ real = os.path.realpath(os.path.abspath(path))
99
+ except (OSError, ValueError):
100
+ return False
101
+ candidates = {os.path.normcase(os.path.abspath(path)), os.path.normcase(real)}
102
+ for candidate in candidates:
103
+ if (os.path.basename(candidate).lower() == "oumv.json"
104
+ and os.path.basename(os.path.dirname(candidate)).lower() == ".tokensafe"):
105
+ return True
106
+ return False
107
+
108
+
109
+ def policy_edit_refusal(path: str) -> str:
110
+ """Refusal for an agent write aimed at the in-repo policy file."""
111
+ workspace = os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(path))))
112
+ return (
113
+ f"{DENIED_CODE} {POLICY_REPO_REL} is OUMV policy and is not editable through TokenSafe "
114
+ f"writes. The authoritative policy for this workspace is {policy_file(workspace)} "
115
+ "(outside the repo; deny wins across both files) — ask the user to change either file."
116
+ )
117
+
118
+
119
+ def _policy_sources(workspace_dir: str) -> List[Tuple[str, Optional[Dict[str, Any]], bool]]:
120
+ """[(path, data-or-None, authoritative)] for every policy file that exists."""
121
+ out: List[Tuple[str, Optional[Dict[str, Any]], bool]] = []
122
+ for path, authoritative in (
123
+ (os.path.join(workspace_dir, POLICY_REPO_REL), False),
124
+ (policy_file(workspace_dir), True),
125
+ ):
126
+ if not os.path.isfile(path):
127
+ continue
128
+ try:
129
+ out.append((path, _read_json(path), authoritative))
130
+ except (OSError, ValueError):
131
+ out.append((path, None, authoritative))
132
+ return out
133
+
134
+
135
+ def permission_denial(workspace_dir: Optional[str], action: str) -> Optional[str]:
136
+ """Error text when either policy file sets ``permissions.<action>=false``.
137
+
138
+ The repo copy keeps its old leniency (an unreadable file is ignored); the
139
+ out-of-repo copy fails closed, because a corrupt authoritative policy must
140
+ not silently re-enable what it was written to forbid.
141
+ """
142
+ if not workspace_dir:
143
+ return None
144
+ for path, data, authoritative in _policy_sources(workspace_dir):
145
+ if data is None:
146
+ if authoritative:
147
+ return (
148
+ f"{DENIED_CODE} the authoritative OUMV policy {path} is unreadable; "
149
+ f"'{action}' is refused until it is fixed."
150
+ )
151
+ continue
152
+ perms = data.get("permissions")
153
+ if isinstance(perms, dict) and perms.get(action) is False:
154
+ label = path if authoritative else POLICY_REPO_REL
155
+ return (
156
+ f"{DENIED_CODE} Workspace policy explicitly prohibits {action} "
157
+ f"({label}: permissions.{action}=false)."
158
+ )
159
+ return None
160
+
161
+
162
+ # --------------------------------------------------------------------------- #
163
+ # Per-file advisory write lock
164
+ # --------------------------------------------------------------------------- #
165
+
166
+ def lock_path_for(path: str) -> str:
167
+ canonical = os.path.realpath(os.path.abspath(path))
168
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
169
+ return os.path.join(tokensafe_home(), "locks", f"{digest}.lock")
170
+
171
+
172
+ def _try_lock(fd: int) -> None:
173
+ try:
174
+ import fcntl
175
+ except ImportError: # Windows
176
+ try:
177
+ import msvcrt
178
+ except ImportError:
179
+ return # no locking primitive: no-op
180
+ os.lseek(fd, 0, os.SEEK_SET)
181
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
182
+ return
183
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
184
+
185
+
186
+ def _unlock(fd: int) -> None:
187
+ try:
188
+ import fcntl
189
+ except ImportError:
190
+ try:
191
+ import msvcrt
192
+ except ImportError:
193
+ return
194
+ try:
195
+ os.lseek(fd, 0, os.SEEK_SET)
196
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
197
+ except OSError:
198
+ pass
199
+ return
200
+ try:
201
+ fcntl.flock(fd, fcntl.LOCK_UN)
202
+ except OSError:
203
+ pass
204
+
205
+
206
+ @contextmanager
207
+ def file_write_lock(path: str, timeout: float = 10.0) -> Iterator[Optional[str]]:
208
+ """Exclusive advisory lock serializing TokenSafe's own writers of `path`.
209
+
210
+ Held across read -> OCC check -> write by ``OUMVGateway.mutate`` and the
211
+ ``apply_edits`` write path, so two TokenSafe writers (two agents, or one
212
+ agent with parallel calls) cannot interleave between the version check and
213
+ ``os.replace``. The lock is advisory: external editors, IDEs, formatters
214
+ and dev servers do not take it, which is why callers keep their final
215
+ re-hash right before the rename.
216
+
217
+ POSIX uses ``fcntl.flock``; Windows ``msvcrt.locking``; elsewhere it is a
218
+ no-op. When the lock directory cannot be created (read-only home) the
219
+ write proceeds unlocked rather than failing. Yields the lock-file path,
220
+ or None when unlocked.
221
+ """
222
+ lock_file = lock_path_for(path)
223
+ try:
224
+ os.makedirs(os.path.dirname(lock_file), mode=0o700, exist_ok=True)
225
+ fd = os.open(lock_file, os.O_RDWR | os.O_CREAT, 0o600)
226
+ except OSError:
227
+ yield None
228
+ return
229
+ acquired = False
230
+ try:
231
+ deadline = time.monotonic() + max(0.0, timeout)
232
+ while True:
233
+ try:
234
+ _try_lock(fd)
235
+ acquired = True
236
+ break
237
+ except OSError:
238
+ if time.monotonic() >= deadline:
239
+ raise TimeoutError(
240
+ f"another TokenSafe writer holds the lock for {path} "
241
+ f"(waited {timeout:g}s); nothing was written"
242
+ )
243
+ time.sleep(0.02)
244
+ yield lock_file
245
+ finally:
246
+ if acquired:
247
+ _unlock(fd)
248
+ os.close(fd)
249
+
250
+
251
+ @contextmanager
252
+ def file_write_locks(paths: List[str], timeout: float = 10.0) -> Iterator[None]:
253
+ """Locks several files in a canonical order (no lock-order deadlock)."""
254
+ from contextlib import ExitStack
255
+ ordered = sorted({lock_path_for(p): p for p in paths}.items())
256
+ with ExitStack() as stack:
257
+ for _lock, original in ordered:
258
+ stack.enter_context(file_write_lock(original, timeout=timeout))
259
+ yield
@@ -22,7 +22,8 @@ signed payload unfiltered.
22
22
  from __future__ import annotations
23
23
 
24
24
  import os
25
- from typing import Any, Dict, Optional, Tuple
25
+ import secrets
26
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
26
27
 
27
28
  PROFILE_READ_ONLY = "read_only"
28
29
  PROFILE_FULL = "full"
@@ -106,6 +107,68 @@ def spawn_env(env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
106
107
  return base
107
108
 
108
109
 
110
+ # Session-token inputs the adapters read: Python/Go/Node/.NET, the Vite plugin,
111
+ # the Angular bridge and the Java sidecar read TOKENSAFE_OUMV_AUTH_TOKEN (then
112
+ # OUMV_TOKEN); the PHP sidecar reads OUMV_TOKEN first. Both are always set, and
113
+ # the token never goes on a command line, where `ps` would show it.
114
+ TOKEN_ENV = "TOKENSAFE_OUMV_AUTH_TOKEN"
115
+ PHP_TOKEN_ENV = "OUMV_TOKEN"
116
+
117
+
118
+ def _flag_value(argv: Sequence[str], flag: str) -> Optional[str]:
119
+ for index, arg in enumerate(argv):
120
+ if arg == flag and index + 1 < len(argv):
121
+ return argv[index + 1]
122
+ if arg.startswith(flag + "="):
123
+ return arg.split("=", 1)[1]
124
+ return None
125
+
126
+
127
+ def with_session_token(
128
+ env: Dict[str, str],
129
+ workspaces: Sequence[str],
130
+ kind: str,
131
+ argv: Optional[Sequence[str]] = None,
132
+ tool: Optional[str] = None,
133
+ ) -> Tuple[Dict[str, str], List[str]]:
134
+ """Gives a runtime TokenSafe spawns a session token and tells the gateway.
135
+
136
+ A token the user already chose (``--token`` on the command line, or either
137
+ env var) is kept; otherwise a fresh ``secrets.token_hex(16)`` is generated.
138
+ It reaches the runtime through the environment only (both env vars, for
139
+ every language, Java included); argv is never extended, so the token does
140
+ not show up in ``ps``. It is recorded, mode 0600, in
141
+ ``TOKENSAFE_HOME/tokens/<ws_id>.json`` for every root in ``workspaces`` so
142
+ the gateway can send it even when the adapter's descriptor omits it.
143
+ The token is never printed. Returns ``(env, argv)``.
144
+ """
145
+ out_env = dict(env)
146
+ out_argv = list(argv or [])
147
+ tool_name = os.path.basename(tool or (out_argv[0] if out_argv else "")).lower()
148
+ php_first = tool_name.startswith("php")
149
+ candidates = [_flag_value(out_argv, "--token")]
150
+ env_order = (PHP_TOKEN_ENV, TOKEN_ENV) if php_first else (TOKEN_ENV, PHP_TOKEN_ENV)
151
+ candidates += [out_env.get(name) for name in env_order]
152
+ token = next((str(c).strip() for c in candidates if c and str(c).strip()), None) or secrets.token_hex(16)
153
+ for name in (TOKEN_ENV, PHP_TOKEN_ENV):
154
+ if not str(out_env.get(name) or "").strip():
155
+ out_env[name] = token
156
+ from tokensafe import oumv_home
157
+ seen = set()
158
+ for root in workspaces:
159
+ if not root:
160
+ continue
161
+ key = os.path.realpath(os.path.abspath(root))
162
+ if key in seen:
163
+ continue
164
+ seen.add(key)
165
+ try:
166
+ oumv_home.record_session_token(key, kind, token)
167
+ except OSError:
168
+ pass # the runtime still starts token-protected; discovery may not authenticate
169
+ return out_env, out_argv
170
+
171
+
109
172
  def deny_text(target: str) -> str:
110
173
  """Refusal that mirrors the adapter's absent method instead of a quota banner."""
111
174
  action = str(target or "").strip()
@@ -0,0 +1,162 @@
1
+ """Cancellable subprocess runs.
2
+
3
+ ``subprocess.run(timeout=...)`` blocks the calling thread until the child exits
4
+ or the timeout fires, and on timeout it kills only the direct child: a test
5
+ runner's workers (pytest-xdist, npm -> node, go test binaries) survive it. A
6
+ write handler that runs such a command (the ``apply_edits`` verify) holds its
7
+ workspace write lock the whole time, so a cancelled call kept every other write
8
+ to that project waiting for up to the full timeout.
9
+
10
+ ``run_cancellable`` starts the command in its own process group / session,
11
+ polls the calling thread's tools/call context (``call_context``: cancelled flag
12
+ and deadline) together with its own timeout, and on either stops the whole
13
+ group: SIGTERM, then SIGKILL after a short grace (Windows: CTRL_BREAK_EVENT,
14
+ then ``kill``).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import signal
21
+ import subprocess
22
+ import time
23
+ from typing import Dict, List, Optional, Sequence
24
+
25
+ from tokensafe import call_context
26
+
27
+ __all__ = ["ProcResult", "run_cancellable", "stop_group", "TERM_GRACE_SEC"]
28
+
29
+ TERM_GRACE_SEC = 2.0
30
+ _POLL_SEC = 0.1
31
+
32
+
33
+ class ProcResult:
34
+ """Outcome of ``run_cancellable``.
35
+
36
+ ``status`` is "exited", "timeout" or "cancelled". ``returncode`` is the
37
+ child's exit code ("exited") or None. ``stdout``/``stderr`` hold whatever
38
+ the child wrote before it ended or was stopped.
39
+ """
40
+
41
+ __slots__ = ("status", "returncode", "stdout", "stderr", "duration", "pid")
42
+
43
+ def __init__(self, status: str, returncode: Optional[int], stdout, stderr, duration: float, pid: int):
44
+ self.status = status
45
+ self.returncode = returncode
46
+ self.stdout = stdout
47
+ self.stderr = stderr
48
+ self.duration = duration
49
+ self.pid = pid
50
+
51
+
52
+ def _popen_group_kwargs() -> Dict[str, object]:
53
+ if os.name == "posix":
54
+ return {"start_new_session": True}
55
+ return {"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)}
56
+
57
+
58
+ def stop_group(proc: subprocess.Popen, grace: float = TERM_GRACE_SEC) -> None:
59
+ """Terminates the child's whole process group: polite first, then forced."""
60
+ if os.name == "posix":
61
+ try:
62
+ pgid = os.getpgid(proc.pid)
63
+ except (ProcessLookupError, OSError):
64
+ pgid = None
65
+ if pgid is not None and pgid != os.getpgid(0):
66
+ try:
67
+ os.killpg(pgid, signal.SIGTERM)
68
+ except (ProcessLookupError, OSError):
69
+ pass
70
+ try:
71
+ proc.wait(timeout=max(0.0, grace))
72
+ except subprocess.TimeoutExpired:
73
+ pass
74
+ # SIGKILL the group even when the leader exited: its workers may not have.
75
+ try:
76
+ os.killpg(pgid, signal.SIGKILL)
77
+ except (ProcessLookupError, OSError):
78
+ pass
79
+ else:
80
+ try:
81
+ proc.terminate()
82
+ proc.wait(timeout=max(0.0, grace))
83
+ except Exception:
84
+ pass
85
+ try:
86
+ proc.kill()
87
+ except Exception:
88
+ pass
89
+ else:
90
+ try:
91
+ proc.send_signal(getattr(signal, "CTRL_BREAK_EVENT"))
92
+ except Exception:
93
+ pass
94
+ try:
95
+ proc.wait(timeout=max(0.0, grace))
96
+ except subprocess.TimeoutExpired:
97
+ pass
98
+ try:
99
+ proc.kill()
100
+ except Exception:
101
+ pass
102
+
103
+
104
+ def run_cancellable(
105
+ argv: Sequence[str],
106
+ *,
107
+ cwd: Optional[str] = None,
108
+ timeout: float,
109
+ env: Optional[Dict[str, str]] = None,
110
+ stdout=subprocess.PIPE,
111
+ stderr=subprocess.PIPE,
112
+ text: bool = True,
113
+ grace: float = TERM_GRACE_SEC,
114
+ ) -> ProcResult:
115
+ """Runs ``argv`` (no shell) bounded by ``timeout`` and the caller's call context.
116
+
117
+ Raises what ``Popen`` raises when the command cannot start (FileNotFoundError,
118
+ PermissionError, ...). Never raises ``CallCancelled``: a cancelled run is
119
+ reported as ``status="cancelled"`` so the caller can still describe what it
120
+ already did (e.g. edits that are on disk).
121
+ """
122
+ started = time.monotonic()
123
+ proc = subprocess.Popen(
124
+ list(argv), cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr,
125
+ text=text, **_popen_group_kwargs(),
126
+ )
127
+ deadline = started + max(0.0, float(timeout))
128
+ status = "exited"
129
+ out = err = None
130
+ out_parts: List = []
131
+ err_parts: List = []
132
+ while True:
133
+ try:
134
+ out, err = proc.communicate(timeout=_POLL_SEC)
135
+ break
136
+ except subprocess.TimeoutExpired:
137
+ pass
138
+ if call_context.is_cancelled():
139
+ status = "cancelled"
140
+ elif time.monotonic() >= deadline:
141
+ status = "timeout"
142
+ else:
143
+ continue
144
+ stop_group(proc, grace)
145
+ try:
146
+ out, err = proc.communicate(timeout=grace)
147
+ except Exception:
148
+ out = err = None
149
+ break
150
+ if out is not None:
151
+ out_parts.append(out)
152
+ if err is not None:
153
+ err_parts.append(err)
154
+ empty = "" if text else b""
155
+ return ProcResult(
156
+ status,
157
+ proc.returncode if status == "exited" else None,
158
+ empty.join(out_parts) if out_parts else empty,
159
+ empty.join(err_parts) if err_parts else empty,
160
+ time.monotonic() - started,
161
+ proc.pid,
162
+ )
@@ -1278,7 +1278,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1278
1278
  openai_payload = _translate_anthropic_payload_to_openai(payload)
1279
1279
  except Exception as e:
1280
1280
  try:
1281
- sys.stderr.write(f"[TokenSafe][debug] translate fail body[:800]={json.dumps(payload)[:800]}\n")
1281
+ sys.stderr.write(_debug_payload_line("translate fail", payload, preview_chars=800))
1282
1282
  except Exception:
1283
1283
  pass
1284
1284
  self._send_json_error(400, f"Failed to translate Anthropic payload: {e}")
@@ -1848,16 +1848,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1848
1848
  # to the client without any server-side trace, making incidents like
1849
1849
  # z.ai 1214 undiagnosable from proxy.log alone.
1850
1850
  try:
1851
+ # Upstream error text can echo request fragments: secrets are
1852
+ # redacted before it reaches the plain-text proxy.log.
1853
+ err_preview = SecretRedactor.redact_text(err_body[:400].decode("utf-8", "replace"))[0]
1851
1854
  sys.stderr.write(
1852
- f"[TokenSafe] {self.command} {self.path} -> upstream {e.code}: "
1853
- f"{err_body[:400].decode('utf-8', 'replace')}\n"
1855
+ f"[TokenSafe] {self.command} {self.path} -> upstream {e.code}: {err_preview}\n"
1854
1856
  )
1855
1857
  if e.code == 400:
1856
- sys.stderr.write(
1857
- "[TokenSafe][debug] upstream-400 payload preview: "
1858
- f"model={payload.get('model')!r} msgs={len(payload.get('messages') or [])} "
1859
- f"body[:1200]={json.dumps(payload, ensure_ascii=False)[:1200]}\n"
1860
- )
1858
+ sys.stderr.write(_debug_payload_line("upstream-400", payload, preview_chars=1200))
1861
1859
  except Exception:
1862
1860
  pass
1863
1861
  if provider == "anthropic" and not client_anthropic:
@@ -1917,6 +1915,78 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1917
1915
  return custom_url, (gemini_key or generic_upstream_key)
1918
1916
  return custom_url, (deepseek_key or generic_upstream_key or openai_key)
1919
1917
 
1918
+ _DEBUG_BODY_ENV = "TOKENSAFE_PROXY_DEBUG_BODY"
1919
+
1920
+
1921
+ def _debug_body_enabled() -> bool:
1922
+ """Raw request-body previews in proxy.log are strictly opt-in."""
1923
+ return str(os.environ.get(_DEBUG_BODY_ENV, "")).strip().lower() in ("1", "true", "yes", "on")
1924
+
1925
+
1926
+ def _payload_shape_summary(payload: Any) -> str:
1927
+ """Structural metadata of a request body, never its text.
1928
+
1929
+ model, message count, per-message role and content block types, total
1930
+ serialized bytes, top-level keys and max_tokens: enough to diagnose an
1931
+ upstream 400 (shape, size, ordering) without writing prompts, tool inputs
1932
+ or tool results to a plain-text log."""
1933
+ if not isinstance(payload, dict):
1934
+ return f"type={type(payload).__name__}"
1935
+ try:
1936
+ body_bytes = len(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
1937
+ except Exception:
1938
+ body_bytes = -1
1939
+ messages = payload.get("messages")
1940
+ messages = messages if isinstance(messages, list) else []
1941
+ shapes: List[str] = []
1942
+ for msg in messages[:40]:
1943
+ if not isinstance(msg, dict):
1944
+ shapes.append(type(msg).__name__)
1945
+ continue
1946
+ role = str(msg.get("role") or "?")[:16]
1947
+ content = msg.get("content")
1948
+ if isinstance(content, list):
1949
+ kinds = [
1950
+ str(b.get("type") or "?")[:24] if isinstance(b, dict) else type(b).__name__
1951
+ for b in content[:12]
1952
+ ]
1953
+ if len(content) > 12:
1954
+ kinds.append(f"+{len(content) - 12}")
1955
+ shapes.append(f"{role}[{','.join(kinds)}]")
1956
+ elif isinstance(content, str):
1957
+ shapes.append(f"{role}[text]")
1958
+ else:
1959
+ shapes.append(f"{role}[{type(content).__name__}]")
1960
+ if msg.get("tool_calls"):
1961
+ shapes[-1] += f"+tool_calls:{len(msg.get('tool_calls') or [])}"
1962
+ if len(messages) > 40:
1963
+ shapes.append(f"...+{len(messages) - 40}")
1964
+ keys = ",".join(sorted(str(k) for k in payload.keys()))
1965
+ tools = payload.get("tools")
1966
+ n_tools = len(tools) if isinstance(tools, list) else 0
1967
+ return (
1968
+ f"model={str(payload.get('model') or '')[:80]!r} msgs={len(messages)} "
1969
+ f"roles={' '.join(shapes)} bytes={body_bytes} tools={n_tools} "
1970
+ f"max_tokens={payload.get('max_tokens', payload.get('max_completion_tokens'))!r} keys={keys}"
1971
+ )
1972
+
1973
+
1974
+ def _debug_payload_line(label: str, payload: Any, preview_chars: int = 1200) -> str:
1975
+ """One proxy.log line describing a rejected payload.
1976
+
1977
+ Default: structural metadata only. With TOKENSAFE_PROXY_DEBUG_BODY=1 a
1978
+ raw body preview is appended, secrets redacted first."""
1979
+ line = f"[TokenSafe][debug] {label} payload shape: {_payload_shape_summary(payload)}"
1980
+ if _debug_body_enabled():
1981
+ try:
1982
+ raw = json.dumps(payload, ensure_ascii=False)
1983
+ except Exception:
1984
+ raw = repr(payload)
1985
+ redacted = SecretRedactor.redact_text(raw)[0]
1986
+ line += f" body[:{preview_chars}]={redacted[:preview_chars]}"
1987
+ return line + "\n"
1988
+
1989
+
1920
1990
  def _key_fingerprint(api_key: str) -> str:
1921
1991
  """Stable fingerprint of a client API key (never store the key itself)."""
1922
1992
  import hashlib