tokensafe 4.16.1 → 4.16.3

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/mcp_server.py CHANGED
@@ -48,7 +48,7 @@ from src.session_context import current_root, current_session_id
48
48
 
49
49
  SERVER_INFO = {
50
50
  "name": "tokensafe-mcp",
51
- "version": "4.16.1"
51
+ "version": "4.16.3"
52
52
  }
53
53
 
54
54
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -915,6 +915,13 @@ TOOLS = [{'name': 'smart_read_file',
915
915
  'if_modified_since': {'type': 'string',
916
916
  'description': 'ISO timestamp or nanosecond mtime from a previous '
917
917
  'response; an unchanged file returns a one-line stub'},
918
+ 'diff_since': {'type': 'string',
919
+ 'description': 'ISO timestamp, ns mtime, or sha256 version from a '
920
+ 'previous read; a changed file returns only the hunks'},
921
+ 'include_image': {'type': 'boolean',
922
+ 'description': 'For image paths: attach a downscaled preview'},
923
+ 'max_edge': {'type': 'integer',
924
+ 'description': 'Image preview max edge (256-1024, default 1024)'},
918
925
  'targets': {'type': 'array',
919
926
  'maxItems': 8,
920
927
  'items': {'type': 'object',
@@ -1001,11 +1008,13 @@ TOOLS = [{'name': 'smart_read_file',
1001
1008
  'description': "Context hygiene: 'budget' (score S-F), 'compact' (fold transcript), 'prune' (drop "
1002
1009
  "superseded reads), 'mistakes', 'metrics', 'remember' (store a decision/note/preference), "
1003
1010
  "'recall' (read project memory), 'forget' (remove one entry by id), "
1004
- "'recall_transcript' (BM25 search over prior session transcripts).",
1011
+ "'recall_transcript' (BM25 search over prior session transcripts), "
1012
+ "'ingress_show' (exact section of a staged long prompt), 'ingress_stats'.",
1005
1013
  'inputSchema': {'type': 'object',
1006
1014
  'properties': {'action': {'type': 'string',
1007
1015
  'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics',
1008
- 'remember', 'recall', 'forget', 'recall_transcript']},
1016
+ 'remember', 'recall', 'forget', 'recall_transcript',
1017
+ 'ingress_show', 'ingress_stats']},
1009
1018
  'model': {'type': 'string'},
1010
1019
  'transcript_path': {'type': 'string'},
1011
1020
  'kind': {'type': 'string',
@@ -1018,6 +1027,12 @@ TOOLS = [{'name': 'smart_read_file',
1018
1027
  'description': 'remember: files this decision touches'},
1019
1028
  'id': {'type': 'string',
1020
1029
  'description': 'forget: entry id; recall_transcript: <session>:<index> drill-down'},
1030
+ 'hash': {'type': 'string',
1031
+ 'description': 'ingress_show: staged prompt handle (e.g. a1b2c3d4)'},
1032
+ 'section': {'type': 'integer',
1033
+ 'description': 'ingress_show: section index (omit for the index list)'},
1034
+ 'max_tokens': {'type': 'integer',
1035
+ 'description': 'ingress_show: section budget (default 1500, max 6000)'},
1021
1036
  'query': {'type': 'string',
1022
1037
  'description': 'recall: optional filter; recall_transcript: search terms'},
1023
1038
  'scope': {'type': 'string',
@@ -1088,8 +1103,8 @@ TOOLS = [{'name': 'smart_read_file',
1088
1103
  'also accepted as path'}}}},
1089
1104
  {'name': 'run_helper',
1090
1105
  'annotations': {'readOnlyHint': False},
1091
- 'description': "Utilities: 'sanitize','guard','diff','deps','web','expand','image','compress','dict','bundle-probe' "
1092
- "(live entry + hashed chunks + expect/reject table).",
1106
+ 'description': "Utilities: 'sanitize','guard','diff','deps','web','expand','image','compress','dict','bundle-probe',"
1107
+ "'compute' (restricted Python over repo files; inputs stay out of context).",
1093
1108
  'inputSchema': {'type': 'object',
1094
1109
  'properties': {'action': {'type': 'string',
1095
1110
  'enum': ['sanitize',
@@ -1101,9 +1116,17 @@ TOOLS = [{'name': 'smart_read_file',
1101
1116
  'image',
1102
1117
  'compress',
1103
1118
  'dict',
1104
- 'bundle-probe']},
1119
+ 'bundle-probe',
1120
+ 'compute']},
1105
1121
  'command': {'type': 'string'},
1106
1122
  'code': {'type': 'string'},
1123
+ 'program': {'type': 'string',
1124
+ 'description': 'compute: restricted Python source; set RESULT'},
1125
+ 'paths': {'type': 'array',
1126
+ 'items': {'type': 'string'},
1127
+ 'description': 'compute: repo-relative globs/files (max 200)'},
1128
+ 'max_result_bytes': {'type': 'integer',
1129
+ 'description': 'compute: JSON result cap (default 64 KiB)'},
1107
1130
  'file_path': {'type': 'string'},
1108
1131
  'diff': {'type': 'string'},
1109
1132
  'package_name': {'type': 'string'},
@@ -1123,7 +1146,7 @@ TOOLS = [{'name': 'smart_read_file',
1123
1146
  'items': {'type': 'string'},
1124
1147
  'description': 'bundle-probe: explicit chunk URLs (default: auto-discover from the entry)'},
1125
1148
  'timeout_ms': {'type': 'integer',
1126
- 'description': 'bundle-probe: total budget (default 6000, max 15000)'}}}}]
1149
+ 'description': 'bundle-probe/compute: total budget (default 6000/5000, max 15000)'}}}}]
1127
1150
 
1128
1151
 
1129
1152
  def _tighten_apply_edits_schema() -> None:
@@ -2293,6 +2316,153 @@ def _transcript_recall_action(args: dict) -> dict:
2293
2316
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
2294
2317
 
2295
2318
 
2319
+ def _ingress_action(args: dict) -> dict:
2320
+ """`session_context(ingress_show|ingress_stats)` for staged long prompts."""
2321
+ from src.ingress_staging import show, stats
2322
+
2323
+ action = str(args.get("action") or "").strip().lower()
2324
+ if action == "ingress_stats":
2325
+ payload = stats()
2326
+ payload["ok"] = True
2327
+ else:
2328
+ hash_ref = str(args.get("hash") or args.get("id") or "").strip()
2329
+ if not hash_ref:
2330
+ return _fallback_error("session_context", "ingress_show needs `hash`")
2331
+ try:
2332
+ max_tokens = int(args.get("max_tokens") or 1500)
2333
+ except (TypeError, ValueError):
2334
+ max_tokens = 1500
2335
+ payload = show(
2336
+ hash_ref,
2337
+ section=args.get("section"),
2338
+ query=str(args.get("query") or ""),
2339
+ max_tokens=max_tokens,
2340
+ session_id=_mcp_session_id(),
2341
+ )
2342
+ return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
2343
+
2344
+
2345
+ def _run_compute_action(args: dict) -> dict:
2346
+ """`run_helper(compute)` — restricted compute over repo files."""
2347
+ from src.repo_compute import run as _run_compute
2348
+
2349
+ root = str(
2350
+ args.get("root")
2351
+ or args.get("cwd")
2352
+ or args.get("project_path")
2353
+ or _workspace_root()
2354
+ or os.getcwd()
2355
+ )
2356
+ program = str(args.get("program") or args.get("code") or "")
2357
+ paths = args.get("paths") or args.get("path") or []
2358
+ result = _run_compute(
2359
+ program,
2360
+ paths,
2361
+ root=root,
2362
+ timeout_ms=args.get("timeout_ms") or 5000,
2363
+ max_result_bytes=args.get("max_result_bytes") or 65536,
2364
+ )
2365
+ try:
2366
+ tracker = _get_safe_tracker()
2367
+ input_bytes = int(result.get("input_bytes") or 0)
2368
+ result_bytes = int(result.get("result_bytes") or 0)
2369
+ tracker.record_event(
2370
+ session_id=_mcp_session_id(),
2371
+ event_type="REPO_COMPUTE",
2372
+ original_tokens=max(0, input_bytes // 4),
2373
+ optimized_tokens=max(0, result_bytes // 4),
2374
+ details={
2375
+ "files": int(result.get("files_read") or 0),
2376
+ "error": result.get("error") or "",
2377
+ "elapsed_ms": int(result.get("elapsed_ms") or 0),
2378
+ },
2379
+ )
2380
+ except Exception:
2381
+ pass
2382
+ return {"content": [{"type": "text", "text": json.dumps(result, indent=2, ensure_ascii=False)}]}
2383
+
2384
+
2385
+ _IMAGE_MIME = {
2386
+ ".png": "image/png",
2387
+ ".jpg": "image/jpeg",
2388
+ ".jpeg": "image/jpeg",
2389
+ ".webp": "image/webp",
2390
+ ".bmp": "image/bmp",
2391
+ ".gif": "image/gif",
2392
+ }
2393
+ _MAX_IMAGE_BASE64_BYTES = 512 * 1024
2394
+
2395
+
2396
+ def _render_image_peek(path: str, args: dict, tracker=None) -> dict:
2397
+ """Return a text metadata block plus a downscaled MCP image block."""
2398
+ import base64
2399
+
2400
+ from src.image_downscale import ImageDownscaler
2401
+
2402
+ try:
2403
+ max_edge = int(args.get("max_edge") or 1024)
2404
+ except (TypeError, ValueError):
2405
+ max_edge = 1024
2406
+ max_edge = max(256, min(max_edge, 1024))
2407
+ meta = ImageDownscaler.optimize(path, max_edge=max_edge)
2408
+ if not meta.get("success"):
2409
+ return _fallback_error("smart_read_file", str(meta.get("error") or "image optimization failed"))
2410
+ optimized = str(meta.get("optimized_path") or path)
2411
+ dims = meta.get("dimensions") or meta.get("new_dimensions") or (0, 0)
2412
+ width, height = (int(dims[0]), int(dims[1])) if isinstance(dims, (list, tuple)) and len(dims) >= 2 else (0, 0)
2413
+ tokens = int(meta.get("estimated_tokens") or meta.get("new_tokens") or 0)
2414
+ blob = b""
2415
+ for edge in (max_edge, 768, 512):
2416
+ candidate_meta = meta if edge == max_edge else ImageDownscaler.optimize(path, max_edge=edge)
2417
+ candidate = str(candidate_meta.get("optimized_path") or path)
2418
+ try:
2419
+ with open(candidate, "rb") as fh:
2420
+ blob = fh.read()
2421
+ except OSError:
2422
+ blob = b""
2423
+ if blob and len(base64.b64encode(blob)) <= _MAX_IMAGE_BASE64_BYTES:
2424
+ optimized = candidate
2425
+ if edge != max_edge:
2426
+ dims = candidate_meta.get("dimensions") or candidate_meta.get("new_dimensions") or dims
2427
+ tokens = int(candidate_meta.get("estimated_tokens") or candidate_meta.get("new_tokens") or tokens)
2428
+ break
2429
+ if not blob:
2430
+ return _fallback_error("smart_read_file", "image could not be read")
2431
+ ext = os.path.splitext(optimized)[1].lower() or os.path.splitext(path)[1].lower()
2432
+ mime = _IMAGE_MIME.get(ext, "application/octet-stream")
2433
+ text = (
2434
+ f"// [TS image] {os.path.basename(path)} "
2435
+ f"({width}x{height}, {mime}, {len(blob):,} bytes, ~{tokens} vision tokens)"
2436
+ )
2437
+ encoded = base64.b64encode(blob).decode("ascii")
2438
+ if len(encoded) <= _MAX_IMAGE_BASE64_BYTES:
2439
+ payload = {
2440
+ "content": [
2441
+ {"type": "text", "text": text},
2442
+ {"type": "image", "data": encoded, "mimeType": mime},
2443
+ ]
2444
+ }
2445
+ else:
2446
+ payload = {
2447
+ "content": [{
2448
+ "type": "text",
2449
+ "text": f"{text}\nPreview omitted: encoded image exceeds 512 KiB.",
2450
+ }]
2451
+ }
2452
+ try:
2453
+ if tracker is not None:
2454
+ tracker.record_event(
2455
+ session_id=_mcp_session_id(),
2456
+ event_type="IMAGE_PEEK",
2457
+ original_tokens=tokens,
2458
+ optimized_tokens=tokens,
2459
+ details={"file": os.path.basename(path), "bytes": len(blob), "mime": mime},
2460
+ )
2461
+ except Exception:
2462
+ pass
2463
+ return payload
2464
+
2465
+
2296
2466
  def handle_tool_call(name: str, args: dict) -> dict:
2297
2467
  if args is None or not isinstance(args, dict):
2298
2468
  args = {}
@@ -2318,19 +2488,43 @@ def handle_tool_call(name: str, args: dict) -> dict:
2318
2488
  else:
2319
2489
  abs_path = os.path.abspath(path)
2320
2490
  cur_hash = AgentFirewall._file_content_hash(abs_path)
2321
- _remember_delivered(abs_path, symbol, eff_dep_mode, cur_hash)
2322
- # Never overwrite cached skeleton with a firewall header or pointer hit
2323
- if not text_out.startswith("// [TokenSafe Subagent Firewall:"):
2324
- try:
2325
- AgentFirewall.record_cache(
2326
- session_id=_mcp_session_id(),
2327
- file_path=abs_path,
2328
- content=text_out,
2329
- symbol=cache_sym,
2330
- tracker=_get_safe_tracker()
2331
- )
2332
- except Exception:
2333
- pass
2491
+ # `// [TS: unchanged]` and `// [TS diff ...]` are delta views, not
2492
+ # the file body: recording them as delivered content poisons both
2493
+ # the pointer cache and the diff baseline.
2494
+ is_ts_payload = text_out.startswith("// [TS:")
2495
+ if not is_ts_payload:
2496
+ _remember_delivered(abs_path, symbol, eff_dep_mode, cur_hash)
2497
+ # Never overwrite cached skeleton with a firewall header or pointer hit
2498
+ if not text_out.startswith("// [TokenSafe Subagent Firewall:"):
2499
+ try:
2500
+ AgentFirewall.record_cache(
2501
+ session_id=_mcp_session_id(),
2502
+ file_path=abs_path,
2503
+ content=text_out,
2504
+ symbol=cache_sym,
2505
+ tracker=_get_safe_tracker()
2506
+ )
2507
+ except Exception:
2508
+ pass
2509
+ # Raw baseline for the next diff_since read. Only plain
2510
+ # reads qualify; symbol/range responses are not full bodies.
2511
+ if not symbol:
2512
+ try:
2513
+ from src.read_baseline import store as _store_baseline
2514
+ st = os.stat(abs_path)
2515
+ if st.st_size <= 128 * 1024:
2516
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as fh:
2517
+ raw_text = fh.read()
2518
+ _store_baseline(
2519
+ _mcp_session_id(),
2520
+ abs_path,
2521
+ raw_text,
2522
+ mtime_ns=st.st_mtime_ns,
2523
+ sha256=cur_hash,
2524
+ tracker=_get_safe_tracker(),
2525
+ )
2526
+ except Exception:
2527
+ pass
2334
2528
  try:
2335
2529
  from src.adapter_core import get_oumv_read_edit_advisory
2336
2530
  oumv_note = get_oumv_read_edit_advisory(active_ws or os.path.dirname(abs_path), abs_path, _mcp_session_id())
@@ -2425,6 +2619,70 @@ def _parse_if_modified_since(value: Any) -> Optional[int]:
2425
2619
  return None
2426
2620
 
2427
2621
 
2622
+ def _parse_diff_since(value: Any) -> Optional[tuple]:
2623
+ """Parse `diff_since` into ('time', ns) or ('hash', hex)."""
2624
+ if value is None:
2625
+ return None
2626
+ raw = str(value).strip()
2627
+ if not raw:
2628
+ return None
2629
+ lower = raw.lower()
2630
+ if lower.startswith("sha256:"):
2631
+ return ("hash", lower[7:])
2632
+ if lower.startswith("ver="):
2633
+ return ("hash", lower[4:])
2634
+ if raw.isdigit():
2635
+ parsed = _parse_if_modified_since(raw)
2636
+ return ("time", parsed) if parsed is not None else None
2637
+ if re.fullmatch(r"[0-9a-fA-F]{8,64}", raw):
2638
+ return ("hash", lower)
2639
+ parsed = _parse_if_modified_since(raw)
2640
+ return ("time", parsed) if parsed is not None else None
2641
+
2642
+
2643
+ def _render_diff_read(
2644
+ baseline: str,
2645
+ current: str,
2646
+ rel: str,
2647
+ stamp: str,
2648
+ max_hunks: int = 5,
2649
+ max_lines: int = 400,
2650
+ ) -> tuple:
2651
+ """Render a bounded unified diff, or (None, stats) when it would not pay off."""
2652
+ import difflib
2653
+
2654
+ old_lines = baseline.splitlines()
2655
+ new_lines = current.splitlines()
2656
+ diff_lines = list(
2657
+ difflib.unified_diff(
2658
+ old_lines,
2659
+ new_lines,
2660
+ fromfile=f"a/{rel}",
2661
+ tofile=f"b/{rel}",
2662
+ n=3,
2663
+ lineterm="",
2664
+ )
2665
+ )
2666
+ hunks = sum(1 for line in diff_lines if line.startswith("@@"))
2667
+ added = sum(1 for line in diff_lines if line.startswith("+") and not line.startswith("+++"))
2668
+ removed = sum(1 for line in diff_lines if line.startswith("-") and not line.startswith("---"))
2669
+ changed = added + removed
2670
+ stats = {"hunks": hunks, "added": added, "removed": removed, "lines": len(diff_lines)}
2671
+ if not diff_lines:
2672
+ return "", stats
2673
+ # A diff that touches most of the file is not a delta view; the caller is
2674
+ # better served by a normal (skeleton) read.
2675
+ if changed > max(20, int(len(new_lines) * 0.4)):
2676
+ return None, stats
2677
+ if hunks > max_hunks or len(diff_lines) > max_lines:
2678
+ return None, stats
2679
+ header = (
2680
+ f"// [TS diff since {stamp}] {rel} "
2681
+ f"(+{added}/-{removed}, {hunks} hunk{'s' if hunks != 1 else ''})\n"
2682
+ )
2683
+ return header + "\n".join(diff_lines), stats
2684
+
2685
+
2428
2686
  def _dispatch_tool_call(name: str, args: dict) -> dict:
2429
2687
  global _EPOCH_GEN
2430
2688
  # Route consolidated tools to canonical internal handlers (zero logic duplication).
@@ -2496,6 +2754,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2496
2754
  return _project_memory_action(action, args)
2497
2755
  if action == "recall_transcript":
2498
2756
  return _transcript_recall_action(args)
2757
+ if action in ("ingress_show", "ingress_stats"):
2758
+ return _ingress_action(args)
2499
2759
  if action not in _SESSION_CONTEXT_ACTIONS:
2500
2760
  return _fallback_error("session_context", f"unknown action '{action}'")
2501
2761
  name = _SESSION_CONTEXT_ACTIONS[action]
@@ -2545,6 +2805,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2545
2805
  name = mapped
2546
2806
  elif name == "run_helper":
2547
2807
  action = str(args.get("action") or "").strip().lower()
2808
+ if action == "compute":
2809
+ return _run_compute_action(args)
2548
2810
  if action not in _HELPER_ACTIONS:
2549
2811
  return _fallback_error("run_helper", f"unknown action '{action}'")
2550
2812
  name = _HELPER_ACTIONS[action]
@@ -2661,6 +2923,101 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2661
2923
  }]
2662
2924
  }
2663
2925
 
2926
+ # Diff-on-change: when a raw baseline exists for this session, a changed
2927
+ # file returns only the unified-diff hunks instead of a full body.
2928
+ diff_raw = args.get("diff_since")
2929
+ if diff_raw and not symbol and start_line is None and end_line is None and not force_full:
2930
+ parsed_diff = _parse_diff_since(diff_raw)
2931
+ if parsed_diff:
2932
+ try:
2933
+ rel = os.path.relpath(path, active_ws) if active_ws else path
2934
+ except ValueError:
2935
+ rel = path
2936
+ if rel.startswith(".."):
2937
+ rel = os.path.basename(path)
2938
+ kind, diff_value = parsed_diff
2939
+ raw_diff = str(diff_raw).strip()
2940
+ second_precision = (
2941
+ ("T" in raw_diff and "." not in raw_diff)
2942
+ or (raw_diff.isdigit() and len(raw_diff) <= 10)
2943
+ )
2944
+ if kind == "time":
2945
+ unchanged = (
2946
+ st.st_mtime_ns // 1_000_000_000 <= diff_value // 1_000_000_000
2947
+ if second_precision
2948
+ else st.st_mtime_ns <= diff_value
2949
+ )
2950
+ current_hash = ""
2951
+ else:
2952
+ current_hash = AgentFirewall._file_content_hash(path)
2953
+ unchanged = bool(diff_value) and current_hash.startswith(diff_value)
2954
+ if unchanged:
2955
+ from datetime import datetime
2956
+
2957
+ mtime_iso = datetime.fromtimestamp(st.st_mtime_ns / 1_000_000_000).isoformat(timespec="seconds")
2958
+ return {
2959
+ "content": [{
2960
+ "type": "text",
2961
+ "text": (
2962
+ f"// [TS: unchanged] {rel} (mtime {mtime_iso}, size {st.st_size:,})\n"
2963
+ "No diff: the file matches the version you already have."
2964
+ ),
2965
+ }]
2966
+ }
2967
+ from src.read_baseline import get as _get_read_baseline
2968
+
2969
+ baseline = _get_read_baseline(_mcp_session_id(), path, tracker=tracker)
2970
+ hash_matches = (
2971
+ kind != "hash"
2972
+ or str((baseline or {}).get("sha256") or "").startswith(diff_value)
2973
+ )
2974
+ if baseline and baseline.get("content") is not None and hash_matches:
2975
+ try:
2976
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
2977
+ current_text = fh.read()
2978
+ except OSError:
2979
+ current_text = ""
2980
+ if current_text:
2981
+ rendered_diff, diff_stats = _render_diff_read(
2982
+ str(baseline.get("content") or ""),
2983
+ current_text,
2984
+ rel,
2985
+ raw_diff,
2986
+ )
2987
+ if rendered_diff is not None:
2988
+ tracker.record_event(
2989
+ session_id=_mcp_session_id(),
2990
+ event_type="DIFF_READ",
2991
+ original_tokens=count_tokens(current_text),
2992
+ optimized_tokens=count_tokens(rendered_diff),
2993
+ details={"file": rel, **diff_stats},
2994
+ )
2995
+ if rendered_diff == "":
2996
+ return {
2997
+ "content": [{
2998
+ "type": "text",
2999
+ "text": f"// [TS: unchanged] {rel} (no textual diff)",
3000
+ }]
3001
+ }
3002
+ return {"content": [{"type": "text", "text": rendered_diff}]}
3003
+ tracker.record_event(
3004
+ session_id=_mcp_session_id(),
3005
+ event_type="DIFF_READ_FALLBACK",
3006
+ original_tokens=count_tokens(current_text),
3007
+ optimized_tokens=0,
3008
+ details={"file": rel, **diff_stats},
3009
+ )
3010
+
3011
+ from src.image_downscale import IMAGE_EXTENSIONS as _IMAGE_EXTENSIONS
3012
+
3013
+ if os.path.splitext(path)[1].lower() in _IMAGE_EXTENSIONS:
3014
+ if not args.get("include_image"):
3015
+ return _fallback_error(
3016
+ "smart_read_file",
3017
+ f"'{os.path.basename(path)}' is an image; pass include_image=true to attach a downscaled preview",
3018
+ )
3019
+ return _render_image_peek(path, args, tracker)
3020
+
2664
3021
  if _is_binary_file(path):
2665
3022
  return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
2666
3023
 
@@ -4326,6 +4683,58 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4326
4683
  elif v.get("error"):
4327
4684
  lines.append(f"Error: {v['error']}")
4328
4685
 
4686
+ # Static blast radius (warm graph only): one advisory line, no crawl
4687
+ # and no mandatory follow-up call.
4688
+ try:
4689
+ if res.get("success") and applied_files and not res.get("dry_run"):
4690
+ warm = GraphEngine.get_cached(cwd)
4691
+ if warm is not None:
4692
+ session_id = _mcp_session_id()
4693
+ total_importers = 0
4694
+ total_callers = 0
4695
+ examples = []
4696
+ unread = []
4697
+ for item in applied_files[:5]:
4698
+ rel_file = str(item.get("path") or "").strip()
4699
+ if not rel_file:
4700
+ continue
4701
+ summary = warm.get_file_impact_summary(rel_file, limit=3)
4702
+ counts = summary.get("counts") or {}
4703
+ total_importers += int(counts.get("importers") or 0)
4704
+ total_callers += int(counts.get("callers") or 0)
4705
+ for importer in summary.get("importers") or []:
4706
+ examples.append(importer)
4707
+ if not AgentFirewall.was_delivered(session_id, os.path.join(cwd, importer)):
4708
+ unread.append(importer)
4709
+ if total_importers or total_callers:
4710
+ parts = []
4711
+ if total_importers:
4712
+ parts.append(f"{total_importers} importer(s)")
4713
+ if total_callers:
4714
+ parts.append(f"{total_callers} static caller(s)")
4715
+ impact_line = f" ↳ impact (static): {', '.join(parts)}"
4716
+ if examples:
4717
+ impact_line += f" — e.g. {', '.join(sorted(set(examples))[:3])}"
4718
+ if unread:
4719
+ impact_line += (
4720
+ "; importers not read this session — "
4721
+ "repo_map(view='importers', path=...)"
4722
+ )
4723
+ lines.append(impact_line)
4724
+ tracker.record_event(
4725
+ session_id=session_id,
4726
+ event_type="IMPACT_HINT",
4727
+ original_tokens=0,
4728
+ optimized_tokens=0,
4729
+ details={
4730
+ "files": [str(i.get("path")) for i in applied_files[:5]],
4731
+ "importers": total_importers,
4732
+ "callers": total_callers,
4733
+ },
4734
+ )
4735
+ except Exception:
4736
+ pass
4737
+
4329
4738
  out_msg = {"content": [{"type": "text", "text": "\n".join(lines)}]}
4330
4739
  if applied_files:
4331
4740
  # Dashboards must see batch edits: without this the batch editor is
@@ -4539,6 +4948,10 @@ def _redact_result_secrets(result):
4539
4948
  total += n
4540
4949
  return red
4541
4950
  if isinstance(node, dict):
4951
+ # Image payloads are base64: a regex pass can corrupt them by
4952
+ # accident, and they never carry textual secrets.
4953
+ if node.get("type") == "image":
4954
+ return node
4542
4955
  return {k: _walk(v) for k, v in node.items()}
4543
4956
  if isinstance(node, list):
4544
4957
  return [_walk(v) for v in node]
package/src/proxy.py CHANGED
@@ -1313,21 +1313,29 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1313
1313
  msg = messages[-1]
1314
1314
  if isinstance(msg.get("content"), str):
1315
1315
  raw_user = msg["content"]
1316
- compaction = PromptCompactor.compact(raw_user, enable_distill=False)
1317
- if compaction["saved_tokens"] > 5:
1318
- msg["content"] = compaction["compact_text"]
1316
+ staged = None
1317
+ try:
1318
+ from src.ingress_staging import stage as _stage_ingress
1319
+
1320
+ staged = _stage_ingress(raw_user, agent="proxy", session_id="proxy_session")
1321
+ except Exception:
1322
+ staged = None
1323
+ if staged:
1324
+ # The proxy is the one ingress path that discards the original
1325
+ # in place; the handle is what keeps it recoverable.
1326
+ msg["content"] = staged["context_text"]
1319
1327
  prompt_mutated = True
1320
1328
  try:
1321
1329
  proxy_tracker.record_event(
1322
1330
  session_id="proxy_session",
1323
1331
  event_type="PROMPT",
1324
- original_tokens=compaction["original_tokens"],
1325
- optimized_tokens=compaction["compact_tokens"],
1332
+ original_tokens=staged["original_tokens"],
1333
+ optimized_tokens=staged["injected_tokens"],
1326
1334
  details={
1327
- "mode": "proxy_replace",
1328
- "action": compaction.get("action"),
1329
- "symbol": compaction.get("symbol"),
1330
- "tier": compaction.get("tier", "REGEX"),
1335
+ "mode": "proxy_ingress",
1336
+ "hash": staged["hash"],
1337
+ "sections": len(staged["sections"]),
1338
+ "tier": "INGRESS",
1331
1339
  },
1332
1340
  measurement="measured",
1333
1341
  )
@@ -1335,7 +1343,30 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1335
1343
  TelemetrySync.sync_background(throttle_seconds=5.0)
1336
1344
  except Exception:
1337
1345
  pass
1338
- target_symbol = compaction.get("symbol")
1346
+ else:
1347
+ compaction = PromptCompactor.compact(raw_user, enable_distill=False)
1348
+ if compaction["saved_tokens"] > 5:
1349
+ msg["content"] = compaction["compact_text"]
1350
+ prompt_mutated = True
1351
+ try:
1352
+ proxy_tracker.record_event(
1353
+ session_id="proxy_session",
1354
+ event_type="PROMPT",
1355
+ original_tokens=compaction["original_tokens"],
1356
+ optimized_tokens=compaction["compact_tokens"],
1357
+ details={
1358
+ "mode": "proxy_replace",
1359
+ "action": compaction.get("action"),
1360
+ "symbol": compaction.get("symbol"),
1361
+ "tier": compaction.get("tier", "REGEX"),
1362
+ },
1363
+ measurement="measured",
1364
+ )
1365
+ from src.telemetry_sync import TelemetrySync
1366
+ TelemetrySync.sync_background(throttle_seconds=5.0)
1367
+ except Exception:
1368
+ pass
1369
+ target_symbol = compaction.get("symbol")
1339
1370
 
1340
1371
  # 3. Automatic Architecture Awareness & OUMV Capability Matrix (deterministic
1341
1372
  # across turns for the active workspace so KV-cache prefixes stay identical).