tokensafe 4.2.11 → 4.2.12

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.2.11",
2
+ "version": "4.2.12",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -92,7 +92,7 @@ def handle(event: str, payload: dict) -> dict:
92
92
  }
93
93
  return {}
94
94
 
95
- context, meta = compact_for_injection(prompt, AGENT, session_id)
95
+ context, meta = compact_for_injection(prompt, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
96
96
  if context and meta.get("compacted"):
97
97
  parts.append(
98
98
  f"{context}\n"
@@ -160,7 +160,7 @@ def handle(event: str, payload: dict) -> dict:
160
160
  tool_input = {}
161
161
  if tool in ("Bash", "Shell", "bash"):
162
162
  command = str(tool_input.get("command") or "")
163
- verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
163
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
164
164
  if verdict["decision"] == "deny":
165
165
  return {
166
166
  "hookSpecificOutput": {
@@ -183,7 +183,7 @@ def handle(event: str, payload: dict) -> dict:
183
183
  file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
184
184
  content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
185
185
  append = bool(tool_input.get("append") or tool_input.get("Append") or False)
186
- verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id)
186
+ verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
187
187
  if verdict["decision"] == "deny":
188
188
  return {
189
189
  "hookSpecificOutput": {
@@ -42,7 +42,7 @@ def handle(event: str, payload: dict) -> dict:
42
42
 
43
43
  if event == "beforeShellExecution":
44
44
  command = str(payload.get("command") or "")
45
- verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
45
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
46
46
  if verdict["decision"] == "deny":
47
47
  return {"permission": "deny", "user_message": verdict["reason"]}
48
48
  if verdict["decision"] == "ask":
@@ -51,7 +51,7 @@ def handle(event: str, payload: dict) -> dict:
51
51
 
52
52
  if event == "beforeReadFile":
53
53
  file_path = str(payload.get("file_path") or "")
54
- verdict = guard_read(file_path, AGENT, session_id)
54
+ verdict = guard_read(file_path, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
55
55
  if verdict["decision"] == "deny":
56
56
  return {"permission": "deny", "user_message": verdict["reason"]}
57
57
  return {"permission": "allow"}
@@ -93,7 +93,7 @@ def handle(event: str, payload: dict) -> dict:
93
93
  }
94
94
  return {}
95
95
 
96
- context, meta = compact_for_injection(prompt, AGENT, session_id)
96
+ context, meta = compact_for_injection(prompt, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
97
97
  if context and meta.get("compacted"):
98
98
  parts.append(
99
99
  f"{context}\n"
@@ -118,7 +118,7 @@ def handle(event: str, payload: dict) -> dict:
118
118
 
119
119
  if tool in ("Bash", "Shell", "bash"):
120
120
  command = str(tool_input.get("command") or "")
121
- verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
121
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
122
122
  if verdict["decision"] == "deny":
123
123
  return {
124
124
  "hookSpecificOutput": {
@@ -140,7 +140,7 @@ def handle(event: str, payload: dict) -> dict:
140
140
  file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
141
141
  content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
142
142
  append = bool(tool_input.get("append") or tool_input.get("Append") or False)
143
- verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id)
143
+ verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
144
144
  if verdict["decision"] == "deny":
145
145
  return {
146
146
  "hookSpecificOutput": {
@@ -160,7 +160,7 @@ def handle(event: str, payload: dict) -> dict:
160
160
 
161
161
  elif tool in ("Read", "read_file", "view_file"):
162
162
  file_path = str(tool_input.get("file_path") or tool_input.get("path") or tool_input.get("Path") or "")
163
- verdict = guard_read(file_path, AGENT, session_id)
163
+ verdict = guard_read(file_path, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
164
164
  if verdict["decision"] == "deny":
165
165
  return {
166
166
  "hookSpecificOutput": {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.2.11",
3
+ "version": "4.2.12",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.2.11",
4
+ "version": "4.2.12",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.2.11",
4
+ "version": "4.2.12",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "logo": "assets/logo.png",
7
7
  "developerName": "TokenSafe",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.2.11",
6
+ "version": "4.2.12",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.2.11",
26
+ "version": "4.2.12",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.2.11",
42
+ "version": "4.2.12",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -16,6 +16,7 @@ import os
16
16
  import sys
17
17
  import re
18
18
  import json
19
+ import time
19
20
  from typing import Dict, Any, Optional, Tuple
20
21
 
21
22
  from src.tokenizer import count_tokens
@@ -100,7 +101,75 @@ def _get_tracker():
100
101
  return None
101
102
 
102
103
 
103
- def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str, Dict[str, Any]]:
104
+ # --- Model attribution -------------------------------------------------------
105
+ # Lifecycle hooks never receive the host model, so event details resolve it
106
+ # best-effort: 1) the session transcript (CC-family JSONL stores message.model
107
+ # on assistant entries — read the file tail only, cached by mtime so repeated
108
+ # hook invocations stay cheap), 2) the local proxy's state file (the proxy sees
109
+ # every request and stamps its last-seen model), 3) host env (MODEL /
110
+ # AGY_MODEL). Anything unknown stays "" — the landing feed renders "—" instead
111
+ # of a fabricated name (see telemetry_sync / record_telemetry).
112
+ _MODEL_TRANSCRIPT_CACHE: Dict[str, Tuple[float, str]] = {}
113
+ _PROXY_STATE_TTL_S = 600
114
+ _TRANSCRIPT_TAIL_BYTES = 262144
115
+
116
+
117
+ def _sniff_transcript_model(transcript_path: str) -> str:
118
+ path = str(transcript_path or "")
119
+ if not path:
120
+ return ""
121
+ try:
122
+ mtime = os.path.getmtime(path)
123
+ except OSError:
124
+ return ""
125
+ cached = _MODEL_TRANSCRIPT_CACHE.get(path)
126
+ if cached and cached[0] == mtime:
127
+ return cached[1]
128
+ model = ""
129
+ try:
130
+ with open(path, "rb") as f:
131
+ f.seek(0, os.SEEK_END)
132
+ size = f.tell()
133
+ f.seek(max(0, size - _TRANSCRIPT_TAIL_BYTES))
134
+ tail = f.read().decode("utf-8", errors="ignore")
135
+ for line in reversed(tail.splitlines()):
136
+ if '"model"' not in line:
137
+ continue
138
+ m = re.search(r'"model"\s*:\s*"([^"]+)"', line)
139
+ if m and m.group(1):
140
+ model = m.group(1)[:64]
141
+ break
142
+ except OSError:
143
+ model = ""
144
+ _MODEL_TRANSCRIPT_CACHE[path] = (mtime, model)
145
+ return model
146
+
147
+
148
+ def _read_proxy_state_model() -> str:
149
+ try:
150
+ from src.paths import resolve_data_dir
151
+ state_path = os.path.join(resolve_data_dir(), "proxy_state.json")
152
+ with open(state_path, "r", encoding="utf-8") as f:
153
+ state = json.load(f)
154
+ if time.time() - float(state.get("ts") or 0) > _PROXY_STATE_TTL_S:
155
+ return ""
156
+ return str(state.get("model") or "")[:64]
157
+ except Exception:
158
+ return ""
159
+
160
+
161
+ def resolve_event_model(transcript_path: str = "", session_id: str = "") -> str:
162
+ """Best-effort model attribution for recorded events. Fails open to ''."""
163
+ model = _sniff_transcript_model(transcript_path)
164
+ if model:
165
+ return model
166
+ model = _read_proxy_state_model()
167
+ if model:
168
+ return model
169
+ return os.environ.get("MODEL") or os.environ.get("AGY_MODEL") or ""
170
+
171
+
172
+ def compact_for_injection(prompt: str, agent: str, session_id: str, transcript_path: str = "") -> Tuple[str, Dict[str, Any]]:
104
173
  """Compacts a user prompt into its TOCP form for context injection.
105
174
 
106
175
  Returns (context_text, meta). context_text is '' when compaction is not
@@ -124,7 +193,8 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
124
193
  event_type="PROMPT",
125
194
  original_tokens=compaction["original_tokens"],
126
195
  optimized_tokens=compaction["compact_tokens"],
127
- details={"agent": agent, "mode": "hook_inject", "tier": compaction.get("tier", "REGEX")},
196
+ details={"agent": agent, "mode": "hook_inject", "tier": compaction.get("tier", "REGEX"),
197
+ "model": resolve_event_model(transcript_path, session_id)},
128
198
  )
129
199
  except Exception:
130
200
  pass
@@ -134,7 +204,7 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
134
204
  return "", meta
135
205
 
136
206
 
137
- def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "") -> Dict[str, Any]:
207
+ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "", transcript_path: str = "") -> Dict[str, Any]:
138
208
  """Pre-execution shell guard. Returns:
139
209
  {decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is the
140
210
  MEASURED mass of blocked output (0 for allowed commands)."""
@@ -154,7 +224,8 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "")
154
224
  event_type=f"GUARD_{kind}",
155
225
  original_tokens=est,
156
226
  optimized_tokens=0,
157
- details={"agent": agent, "command": cmd[:120]},
227
+ details={"agent": agent, "command": cmd[:120],
228
+ "model": resolve_event_model(transcript_path, session_id)},
158
229
  )
159
230
  except Exception:
160
231
  pass
@@ -193,7 +264,7 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "")
193
264
  return result
194
265
 
195
266
 
196
- def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, Any]:
267
+ def guard_read(file_path: str, agent: str, session_id: str = "", transcript_path: str = "") -> Dict[str, Any]:
197
268
  """Pre-read guard: denies lockfiles/bundles/dist junk that would burn the
198
269
  context window. Blocked reads are recorded as measured savings."""
199
270
  result = {"decision": "allow", "reason": "", "saved_tokens": 0}
@@ -211,7 +282,8 @@ def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, An
211
282
  event_type="GUARD_JUNK_READ",
212
283
  original_tokens=est,
213
284
  optimized_tokens=0,
214
- details={"agent": agent, "file": os.path.basename(normalized)},
285
+ details={"agent": agent, "file": os.path.basename(normalized),
286
+ "model": resolve_event_model(transcript_path, session_id)},
215
287
  )
216
288
  except Exception:
217
289
  pass
@@ -225,7 +297,7 @@ def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, An
225
297
  return result
226
298
 
227
299
 
228
- def guard_write(file_path: str, content: str, append: bool = False, agent: str = "", session_id: str = "") -> Dict[str, Any]:
300
+ def guard_write(file_path: str, content: str, append: bool = False, agent: str = "", session_id: str = "", transcript_path: str = "") -> Dict[str, Any]:
229
301
  """Pre-write egress guard (v3.0.0): full-file Write over an existing file
230
302
  burns expensive OUTPUT tokens. Policy:
231
303
  - new file / append / no content -> allow
@@ -273,6 +345,7 @@ def guard_write(file_path: str, content: str, append: bool = False, agent: str =
273
345
  "existing_lines": len(existing_lines),
274
346
  "delta_lines": delta_lines,
275
347
  "decision": decision,
348
+ "model": resolve_event_model(transcript_path, session_id),
276
349
  },
277
350
  )
278
351
  except Exception:
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.2.11"
45
+ "version": "4.2.12"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
package/src/proxy.py CHANGED
@@ -668,12 +668,33 @@ class _AnthropicSSETranslator:
668
668
  }
669
669
  return (b"data: " + json.dumps(payload, ensure_ascii=False).encode("utf-8") + b"\n\n")
670
670
 
671
+ def _touch_proxy_model_state(self, model: str) -> None:
672
+ """Persists the last-seen model so hook-side attribution can read it:
673
+ adapters resolve event models from ~/.tokensafe/data/proxy_state.json
674
+ because lifecycle hosts never pass the model to hooks. Throttled to one
675
+ write per 30s (or on model change); never raises."""
676
+ now = time.time()
677
+ if model == getattr(self, "_model_state_model", "") and now - getattr(self, "_model_state_ts", 0.0) < 30.0:
678
+ return
679
+ try:
680
+ from src.paths import resolve_data_dir
681
+ state_path = os.path.join(resolve_data_dir(), "proxy_state.json")
682
+ tmp = f"{state_path}.tmp.{os.getpid()}"
683
+ with open(tmp, "w", encoding="utf-8") as f:
684
+ json.dump({"model": str(model or "")[:64], "ts": now}, f)
685
+ os.replace(tmp, state_path)
686
+ self._model_state_ts = now
687
+ self._model_state_model = model
688
+ except Exception:
689
+ pass
690
+
671
691
  def _handle_event(self, event: str, data: Dict[str, Any]) -> bytes:
672
692
  out = b""
673
693
  if event == "message_start":
674
694
  msg = data.get("message") or {}
675
695
  if msg.get("model"):
676
696
  self.model = msg["model"]
697
+ self._touch_proxy_model_state(str(self.model))
677
698
  self._usage_in = int((msg.get("usage") or {}).get("input_tokens") or 0)
678
699
  out += self._chunk({"role": "assistant", "content": ""})
679
700
  elif event == "content_block_start":
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.2.11"
244
+ "User-Agent": "TokenSafe-Sync/4.2.12"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -350,12 +350,22 @@ class TelemetrySync:
350
350
  except Exception:
351
351
  ts_int = int(time.time())
352
352
 
353
- model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
353
+ # Model attribution: event details win, then host-provided env
354
+ # (AGY_MODEL / MODEL). No hardcoded default — hook-path events
355
+ # genuinely don't know the model unless the host exposes it,
356
+ # and an empty value renders as "—" instead of lying.
357
+ model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or ""
358
+ # Agent attribution fills the landing feed's model column when
359
+ # the model itself is unknown (details.agent is always present
360
+ # on hook-recorded events).
361
+ agent_name = ""
354
362
  if r["details"]:
355
363
  try:
356
364
  det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
357
- if isinstance(det, dict) and det.get("model"):
358
- model_name = str(det["model"])
365
+ if isinstance(det, dict):
366
+ if det.get("model"):
367
+ model_name = str(det["model"])
368
+ agent_name = str(det.get("agent") or "")
359
369
  except Exception:
360
370
  pass
361
371
 
@@ -365,6 +375,7 @@ class TelemetrySync:
365
375
  "saved_tokens": int(r["saved_tokens"] or 0),
366
376
  "usd_saved": float(r["est_usd_saved"] or 0.0),
367
377
  "model": model_name,
378
+ "agent": agent_name,
368
379
  "timestamp": ts_int,
369
380
  "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
370
381
  }))
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.2.11"
20
+ CURRENT_VERSION = "4.2.12"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage