tokensafe 2.4.3 → 2.5.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.
@@ -90,7 +90,8 @@ class AgentFirewall:
90
90
  session_id: str,
91
91
  file_path: str,
92
92
  symbol: str = "",
93
- tracker: Optional[MetricsTracker] = None
93
+ tracker: Optional[MetricsTracker] = None,
94
+ allow_pointer: bool = False,
94
95
  ) -> Tuple[bool, Optional[str], int]:
95
96
  """
96
97
  Two-stage lookup:
@@ -98,6 +99,9 @@ class AgentFirewall:
98
99
  2. Cross-session entry whose content_hash matches the file's CURRENT
99
100
  bytes — survives restarts and git-checkout mtime resets; any real
100
101
  edit changes the hash and invalidates the entry.
102
+ When allow_pointer=True and hit_scope == 'session' (caller already
103
+ holds this exact content in its active context), returns a compact
104
+ self-healing pointer instead of re-emitting the skeleton body.
101
105
  Returns: (is_hit, cached_content_or_none, tokens_saved)
102
106
  """
103
107
  if not file_path or not os.path.exists(file_path):
@@ -117,27 +121,37 @@ class AgentFirewall:
117
121
 
118
122
  hit_data = None
119
123
  hit_scope = "session"
120
- with tracker._get_connection() as conn:
121
- # Stage 1: in-session, mtime-validated
122
- row = conn.execute("""
123
- SELECT id, content, tokens, mtime, hit_count
124
- FROM subagent_file_cache
125
- WHERE session_id = ? AND file_path = ? AND symbol = ?;
126
- """, (session_id, abs_path, symbol_key)).fetchone()
127
-
128
- if row and row["mtime"] >= current_mtime:
129
- hit_data = (row["id"], row["content"], row["tokens"], row["hit_count"] + 1)
130
- elif current_hash:
131
- # Stage 2: cross-session, content-hash-validated
132
- row2 = conn.execute("""
133
- SELECT id, content, tokens, hit_count
124
+
125
+ def _query():
126
+ nonlocal hit_data, hit_scope
127
+ with tracker._get_connection() as conn:
128
+ # Stage 1: in-session, mtime-validated
129
+ row = conn.execute("""
130
+ SELECT id, content, tokens, mtime, hit_count
134
131
  FROM subagent_file_cache
135
- WHERE file_path = ? AND symbol = ? AND content_hash = ?
136
- ORDER BY created_at DESC LIMIT 1;
137
- """, (abs_path, symbol_key, current_hash)).fetchone()
138
- if row2:
139
- hit_data = (row2["id"], row2["content"], row2["tokens"], row2["hit_count"] + 1)
140
- hit_scope = "persistent"
132
+ WHERE session_id = ? AND file_path = ? AND symbol = ?;
133
+ """, (session_id, abs_path, symbol_key)).fetchone()
134
+
135
+ if row and row["mtime"] >= current_mtime:
136
+ hit_data = (row["id"], row["content"], row["tokens"], row["hit_count"] + 1)
137
+ elif current_hash:
138
+ # Stage 2: cross-session, content-hash-validated
139
+ row2 = conn.execute("""
140
+ SELECT id, content, tokens, hit_count
141
+ FROM subagent_file_cache
142
+ WHERE file_path = ? AND symbol = ? AND content_hash = ?
143
+ ORDER BY created_at DESC LIMIT 1;
144
+ """, (abs_path, symbol_key, current_hash)).fetchone()
145
+ if row2:
146
+ hit_data = (row2["id"], row2["content"], row2["tokens"], row2["hit_count"] + 1)
147
+ hit_scope = "persistent"
148
+
149
+ try:
150
+ _query()
151
+ except sqlite3.OperationalError:
152
+ cls._INITIALIZED_DBS.discard(tracker.db_path)
153
+ cls._ensure_table(tracker)
154
+ _query()
141
155
 
142
156
  if hit_data:
143
157
  cache_id, content, tokens, hit_count = hit_data
@@ -146,28 +160,48 @@ class AgentFirewall:
146
160
  conn.execute("UPDATE subagent_file_cache SET hit_count = ? WHERE id = ?;", (hit_count, cache_id))
147
161
  except Exception:
148
162
  pass
163
+
164
+ short_hash = current_hash[:8] if current_hash else "cached"
165
+ use_pointer = bool(allow_pointer and hit_scope == "session" and tokens > 60)
166
+
167
+ if use_pointer:
168
+ sym_label = f"::{symbol_key}" if symbol_key else ""
169
+ payload = (
170
+ f"// [TokenSafe Subagent Firewall: Pointer Hit for '{os.path.basename(abs_path)}{sym_label}' "
171
+ f"(unchanged, sha256:{short_hash}) — reuse the content returned earlier in this session; "
172
+ f"if you are a fresh subagent or your context was compacted, re-call smart_read_file with force_full=true]\n"
173
+ )
174
+ opt_tokens = count_tokens(payload)
175
+ else:
176
+ scope_label = "Persistent cache" if hit_scope == "persistent" else "Reused session read"
177
+ sym_label = f"::{symbol_key}" if symbol_key else ""
178
+ # Static deterministic header (no changing hit counters that bust LLM prefix KV-cache)
179
+ header = (
180
+ f"// [TokenSafe Subagent Firewall: {scope_label} for "
181
+ f"'{os.path.basename(abs_path)}{sym_label}' (sha256:{short_hash})]\n"
182
+ )
183
+ payload = header + content
184
+ opt_tokens = 40
185
+
186
+ saved = max(0, tokens - opt_tokens)
149
187
  try:
150
188
  tracker.record_event(
151
189
  session_id=session_id,
152
190
  event_type="SUBAGENT_DEDUP",
153
191
  original_tokens=tokens,
154
- optimized_tokens=40, # minimal cache reference tokens
192
+ optimized_tokens=opt_tokens,
155
193
  details={
156
194
  "target_file": os.path.basename(abs_path),
157
195
  "symbol": symbol_key,
158
196
  "hit_number": hit_count,
159
- "scope": hit_scope
197
+ "scope": hit_scope,
198
+ "pointer": use_pointer,
160
199
  }
161
200
  )
162
201
  except Exception:
163
202
  pass
164
203
 
165
- scope_label = "Persistent cache" if hit_scope == "persistent" else "Reused session read"
166
- header = (
167
- f"// [TokenSafe Subagent Firewall: {scope_label} for '{os.path.basename(abs_path)}' "
168
- f"(Dedup Hit #{hit_count}, Saved ~{tokens - 40} tokens)]\n"
169
- )
170
- return True, header + content, max(0, tokens - 40)
204
+ return True, payload, saved
171
205
 
172
206
  return False, None, 0
173
207
 
@@ -201,15 +235,23 @@ class AgentFirewall:
201
235
  now = int(time.time())
202
236
  content_hash = cls._file_content_hash(abs_path)
203
237
 
204
- with tracker._get_connection() as conn:
205
- conn.execute("""
206
- INSERT INTO subagent_file_cache (session_id, file_path, mtime, symbol, content, tokens, created_at, hit_count, content_hash)
207
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)
208
- ON CONFLICT(session_id, file_path, symbol) DO UPDATE SET
209
- mtime = excluded.mtime,
210
- content = excluded.content,
211
- tokens = excluded.tokens,
212
- created_at = excluded.created_at,
213
- content_hash = excluded.content_hash;
214
- """, (session_id, abs_path, mtime, symbol_key, content, tokens, now, content_hash))
238
+ def _insert():
239
+ with tracker._get_connection() as conn:
240
+ conn.execute("""
241
+ INSERT INTO subagent_file_cache (session_id, file_path, mtime, symbol, content, tokens, created_at, hit_count, content_hash)
242
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)
243
+ ON CONFLICT(session_id, file_path, symbol) DO UPDATE SET
244
+ mtime = excluded.mtime,
245
+ content = excluded.content,
246
+ tokens = excluded.tokens,
247
+ created_at = excluded.created_at,
248
+ content_hash = excluded.content_hash;
249
+ """, (session_id, abs_path, mtime, symbol_key, content, tokens, now, content_hash))
250
+
251
+ try:
252
+ _insert()
253
+ except sqlite3.OperationalError:
254
+ cls._INITIALIZED_DBS.discard(tracker.db_path)
255
+ cls._ensure_table(tracker)
256
+ _insert()
215
257
  cls._maybe_prune(tracker)