tokensafe 4.16.3 → 5.0.1
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/bin/agy-tokens +1 -1
- package/bin/tokensafe +1 -1
- package/bin/tokensafe-acp.js +1 -1
- package/bin/tokensafe-mcp +1 -1
- package/bin/tokensafe.js +1 -1
- package/hooks/claude_code_hook.py +49 -45
- package/hooks/cursor_hook.py +8 -8
- package/hooks/kimi_hook.py +23 -23
- package/hooks/post_tool_use.py +6 -6
- package/hooks/pre_invocation.py +21 -17
- package/hooks/pre_tool_use.py +27 -27
- package/hooks/session_start.py +17 -17
- package/hooks/stop_hook.py +3 -3
- package/hooks/zcode_hook.py +2 -2
- package/kimi.plugin.json +2 -2
- package/mcp_config.json +1 -1
- package/package.json +5 -4
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/__init__.py +9 -5
- package/src/cli.py +11 -2487
- package/src/mcp_server.py +11 -5437
- package/src/proxy.py +11 -1834
- package/tokensafe/__init__.py +6 -0
- package/{src → tokensafe}/acp/__init__.py +2 -2
- package/{src → tokensafe}/acp/server.py +5 -5
- package/{src → tokensafe}/adapter_core.py +21 -18
- package/{src → tokensafe}/agent/__init__.py +1 -1
- package/{src → tokensafe}/agent/context.py +4 -4
- package/{src → tokensafe}/agent/loop.py +4 -4
- package/{src → tokensafe}/agent/providers.py +2 -2
- package/{src → tokensafe}/agent/tools.py +2 -2
- package/{src → tokensafe}/agent_firewall.py +51 -10
- package/{src → tokensafe}/angular_cli.py +4 -4
- package/{src → tokensafe}/auto_inject.py +37 -5
- package/{src → tokensafe}/batch_editor.py +185 -28
- package/tokensafe/batch_search.py +1191 -0
- package/{src → tokensafe}/bench/go_target.py +1 -1
- package/{src → tokensafe}/bench/mechanics.py +1 -1
- package/{src → tokensafe}/bench/react_target.py +1 -1
- package/{src → tokensafe}/bench/runner.py +4 -4
- package/{src → tokensafe}/benchmark.py +12 -12
- package/{src → tokensafe}/benchmark_real.py +18 -18
- package/{src → tokensafe}/build_parsers.py +3 -3
- package/{src → tokensafe}/bundle_probe.py +1 -1
- package/{src → tokensafe}/burn_monitor.py +3 -3
- package/{src → tokensafe}/cache_normalizer.py +1 -1
- package/tokensafe/cli.py +2490 -0
- package/{src → tokensafe}/command_sanitizer.py +94 -26
- package/{src → tokensafe}/compaction_recovery.py +5 -5
- package/{src → tokensafe}/compactor.py +148 -95
- package/{src → tokensafe}/context_index.py +194 -28
- package/{src → tokensafe}/cross_stack.py +2 -2
- package/{src → tokensafe}/dashboard.py +3 -3
- package/{src → tokensafe}/delegation.py +4 -4
- package/{src → tokensafe}/dependency_prefetcher.py +1 -1
- package/{src → tokensafe}/diff_slicer.py +2 -2
- package/{src → tokensafe}/distiller.py +7 -7
- package/{src → tokensafe}/distiller_cache.py +3 -3
- package/{src → tokensafe}/egress_counter.py +1 -1
- package/{src → tokensafe}/environment_auditor.py +7 -7
- package/{src → tokensafe}/file_state.py +2 -2
- package/{src → tokensafe}/format_invariants.py +1 -1
- package/tokensafe/format_parsers/__init__.py +20 -0
- package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
- package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
- package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
- package/{src → tokensafe}/format_parsers/json_log.py +1 -1
- package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
- package/{src → tokensafe}/format_parsers/tabular.py +1 -1
- package/{src → tokensafe}/fts_index.py +20 -11
- package/{src → tokensafe}/governor.py +143 -31
- package/{src → tokensafe}/graph_engine.py +729 -126
- package/{src → tokensafe}/guard.py +80 -25
- package/{src → tokensafe}/history_compactor.py +407 -133
- package/{src → tokensafe}/i18n_catalog.py +39 -14
- package/{src → tokensafe}/image_downscale.py +1 -1
- package/{src → tokensafe}/ingress_staging.py +9 -9
- package/{src → tokensafe}/installer.py +118 -61
- package/{src → tokensafe}/license_manager.py +9 -67
- package/{src → tokensafe}/live_relay.py +2 -2
- package/{src → tokensafe}/loop_detector.py +2 -2
- package/{src → tokensafe}/mcp_config_manager.py +2 -2
- package/{src → tokensafe}/mcp_proxy.py +4 -4
- package/tokensafe/mcp_server.py +5668 -0
- package/{src → tokensafe}/metrics.py +56 -21
- package/{src → tokensafe}/mistakes.py +4 -4
- package/{src → tokensafe}/oumv_brief.py +21 -3
- package/{src → tokensafe}/oumv_gateway.py +146 -49
- package/{src → tokensafe}/oumv_policy.py +1 -1
- package/{src → tokensafe}/paths.py +1 -1
- package/{src → tokensafe}/project_memory.py +4 -4
- package/tokensafe/proxy.py +2075 -0
- package/{src → tokensafe}/quality_score.py +4 -4
- package/{src → tokensafe}/read_baseline.py +1 -1
- package/{src → tokensafe}/repo_compute.py +1 -1
- package/{src → tokensafe}/result_ledger.py +19 -19
- package/{src → tokensafe}/retrofit.py +6 -6
- package/{src → tokensafe}/savings.py +3 -3
- package/tokensafe/schema_slicer.py +1087 -0
- package/{src → tokensafe}/scoped_search.py +144 -6
- package/{src → tokensafe}/secret_redactor.py +22 -0
- package/{src → tokensafe}/session_brief.py +8 -8
- package/{src → tokensafe}/skeletonizer.py +89 -26
- package/{src → tokensafe}/slicer.py +3 -2
- package/{src → tokensafe}/snapshot.py +1 -1
- package/{src → tokensafe}/stash.py +1 -1
- package/{src → tokensafe}/statusline.py +1 -1
- package/{src → tokensafe}/superseded.py +22 -4
- package/{src → tokensafe}/team_cache.py +3 -3
- package/{src → tokensafe}/telemetry_sync.py +63 -11
- package/{src → tokensafe}/test_parsers.py +3 -3
- package/{src → tokensafe}/thinking_fold.py +3 -3
- package/{src → tokensafe}/tokenizer.py +37 -1
- package/{src → tokensafe}/tool_pruner.py +3 -3
- package/{src → tokensafe}/transcript_analyzer.py +1 -1
- package/{src → tokensafe}/transcript_recall.py +8 -8
- package/{src → tokensafe}/type_slicer.py +3 -3
- package/{src → tokensafe}/usage_ledger.py +4 -4
- package/{src → tokensafe}/version_checker.py +6 -6
- package/{src → tokensafe}/web_reader.py +86 -8
- package/{src → tokensafe}/workspace_roots.py +2 -2
- package/src/batch_search.py +0 -589
- package/src/format_parsers/__init__.py +0 -20
- package/src/schema_slicer.py +0 -578
- /package/{src → tokensafe}/agent/pricing.py +0 -0
- /package/{src → tokensafe}/atomic_io.py +0 -0
- /package/{src → tokensafe}/backend_release.py +0 -0
- /package/{src → tokensafe}/bench/__init__.py +0 -0
- /package/{src → tokensafe}/bench/driver.py +0 -0
- /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
- /package/{src → tokensafe}/bench_scenarios.json +0 -0
- /package/{src → tokensafe}/competitors.py +0 -0
- /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
- /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
- /package/{src → tokensafe}/globmatch.py +0 -0
- /package/{src → tokensafe}/host_capabilities.py +0 -0
- /package/{src → tokensafe}/json_repair.py +0 -0
- /package/{src → tokensafe}/route_index.py +0 -0
- /package/{src → tokensafe}/scaffold.py +0 -0
- /package/{src → tokensafe}/session_context.py +0 -0
- /package/{src → tokensafe}/ssl_context.py +0 -0
- /package/{src → tokensafe}/stdio_io.py +0 -0
- /package/{src → tokensafe}/syntax_guard.py +0 -0
- /package/{src → tokensafe}/toml_mcp_config.py +0 -0
- /package/{src → tokensafe}/treesitter_backend.py +0 -0
- /package/{src → tokensafe}/win_paths.py +0 -0
|
@@ -193,7 +193,7 @@ class ScopedSearch:
|
|
|
193
193
|
``observe`` / ``status`` warm it) and the on-disk cache otherwise.
|
|
194
194
|
"""
|
|
195
195
|
try:
|
|
196
|
-
from
|
|
196
|
+
from tokensafe.graph_engine import GraphEngine
|
|
197
197
|
return GraphEngine.get_cached(root_dir)
|
|
198
198
|
except Exception:
|
|
199
199
|
return None
|
|
@@ -355,16 +355,45 @@ class ScopedSearch:
|
|
|
355
355
|
|
|
356
356
|
# Identifier queries are lookups: ask the AST index before the text
|
|
357
357
|
# corpus, so a graph written moments ago cannot be shadowed by an FTS
|
|
358
|
-
# generation that is a scan behind.
|
|
358
|
+
# generation that is a scan behind. The declaration leads the answer,
|
|
359
|
+
# but usages and string mentions still follow it (see _merge_symbol_text).
|
|
360
|
+
symbol_result = None
|
|
359
361
|
if not regex_mode and not case_sensitive:
|
|
360
362
|
symbol_result = cls._symbol_lookup(query, root_dir, scope, max_results, per_file)
|
|
361
|
-
|
|
362
|
-
|
|
363
|
+
if symbol_result is None:
|
|
364
|
+
return cls._text_search(
|
|
365
|
+
query, root_dir, scope, pattern, regex_mode, auto_regex,
|
|
366
|
+
case_sensitive, max_results, per_file,
|
|
367
|
+
)
|
|
368
|
+
if len(symbol_result["matches"]) >= max_results:
|
|
369
|
+
return symbol_result
|
|
370
|
+
# The declaration already answers the lookup, so the text pass gets a
|
|
371
|
+
# shorter disk budget and the whole call stays inside the MCP timeout.
|
|
372
|
+
text_result = cls._text_search(
|
|
373
|
+
query, root_dir, scope, pattern, regex_mode, auto_regex,
|
|
374
|
+
case_sensitive, max_results, per_file, timeout_seconds=2.5,
|
|
375
|
+
)
|
|
376
|
+
return cls._merge_symbol_text(symbol_result, text_result, root_dir, scope, max_results, per_file)
|
|
363
377
|
|
|
378
|
+
@classmethod
|
|
379
|
+
def _text_search(
|
|
380
|
+
cls,
|
|
381
|
+
query: str,
|
|
382
|
+
root_dir: str,
|
|
383
|
+
scope: str,
|
|
384
|
+
pattern: Any,
|
|
385
|
+
regex_mode: bool,
|
|
386
|
+
auto_regex: bool,
|
|
387
|
+
case_sensitive: bool,
|
|
388
|
+
max_results: int,
|
|
389
|
+
per_file: int,
|
|
390
|
+
timeout_seconds: float = 4.0,
|
|
391
|
+
) -> Dict[str, Any]:
|
|
392
|
+
"""Plain-text answer: the FTS trigram index first, then the bounded disk walk."""
|
|
364
393
|
# Fast-path: SQLite FTS5 trigram BM25 search for plain case-insensitive queries
|
|
365
394
|
if not regex_mode and not case_sensitive and len(query) >= 3 and not any(c in query for c in "*?[]{}()^$+\\|"):
|
|
366
395
|
try:
|
|
367
|
-
from
|
|
396
|
+
from tokensafe.fts_index import CodeFTSIndex
|
|
368
397
|
fts = CodeFTSIndex(root_dir)
|
|
369
398
|
fts_results = fts.search(query, limit=max_results)
|
|
370
399
|
if fts_results:
|
|
@@ -407,6 +436,7 @@ class ScopedSearch:
|
|
|
407
436
|
"total_files": coverage_files,
|
|
408
437
|
"total_matches": len(fts_matches),
|
|
409
438
|
"overflow_matches": sum(overflow.values()),
|
|
439
|
+
"overflow_by_file": dict(overflow),
|
|
410
440
|
"per_file_cap": per_file_cap,
|
|
411
441
|
"timed_out": False,
|
|
412
442
|
"partial": False,
|
|
@@ -442,7 +472,6 @@ class ScopedSearch:
|
|
|
442
472
|
per_file_counts: Dict[str, int] = {}
|
|
443
473
|
overflow: Dict[str, int] = {}
|
|
444
474
|
start_time = time.monotonic()
|
|
445
|
-
timeout_seconds = 4.0
|
|
446
475
|
max_scanned_files = 2500
|
|
447
476
|
timed_out = False
|
|
448
477
|
stopped_reason = "complete"
|
|
@@ -577,6 +606,7 @@ class ScopedSearch:
|
|
|
577
606
|
"path_is_file": False,
|
|
578
607
|
"total_matches": len(matches),
|
|
579
608
|
"overflow_matches": sum(overflow.values()),
|
|
609
|
+
"overflow_by_file": dict(overflow),
|
|
580
610
|
"per_file_cap": per_file_cap,
|
|
581
611
|
"files_matched": len(hit_files),
|
|
582
612
|
"scanned_files": total_scanned_files,
|
|
@@ -595,6 +625,114 @@ class ScopedSearch:
|
|
|
595
625
|
"markdown": markdown,
|
|
596
626
|
}
|
|
597
627
|
|
|
628
|
+
@classmethod
|
|
629
|
+
def _merge_symbol_text(
|
|
630
|
+
cls,
|
|
631
|
+
symbol_result: Dict[str, Any],
|
|
632
|
+
text_result: Dict[str, Any],
|
|
633
|
+
root_dir: str,
|
|
634
|
+
scope: str,
|
|
635
|
+
max_results: int,
|
|
636
|
+
per_file: int,
|
|
637
|
+
) -> Dict[str, Any]:
|
|
638
|
+
"""Declarations first, then the remaining plain-text matches.
|
|
639
|
+
|
|
640
|
+
A found declaration used to hide every usage and string mention. Now the
|
|
641
|
+
text hits follow it: hits on a declaration line are dropped (they would
|
|
642
|
+
repeat it), and the rest share max_results and the per-file cap with
|
|
643
|
+
the declarations. Keeps `source` = graph_symbol_index for callers.
|
|
644
|
+
"""
|
|
645
|
+
def _key(rel: str, line: Any) -> Tuple[str, int]:
|
|
646
|
+
path = rel if os.path.isabs(rel) else os.path.join(root_dir, rel)
|
|
647
|
+
try:
|
|
648
|
+
line_no = int(line or 0)
|
|
649
|
+
except (TypeError, ValueError):
|
|
650
|
+
line_no = 0
|
|
651
|
+
return os.path.normcase(os.path.normpath(path)), line_no
|
|
652
|
+
|
|
653
|
+
per_file_cap = cls._resolve_per_file(per_file, max_results)
|
|
654
|
+
decls = [dict(m, declaration=True) for m in symbol_result.get("matches") or []]
|
|
655
|
+
decl_lines = {_key(m["file"], m.get("line")) for m in decls}
|
|
656
|
+
counts: Dict[str, int] = {}
|
|
657
|
+
for m in decls:
|
|
658
|
+
fkey = _key(m["file"], 0)[0]
|
|
659
|
+
counts[fkey] = counts.get(fkey, 0) + 1
|
|
660
|
+
|
|
661
|
+
merged: List[Dict[str, Any]] = list(decls)
|
|
662
|
+
overflow: Dict[str, int] = dict(text_result.get("overflow_by_file") or {})
|
|
663
|
+
dropped = 0
|
|
664
|
+
for m in text_result.get("matches") or []:
|
|
665
|
+
key = _key(m.get("file", ""), m.get("line"))
|
|
666
|
+
if key in decl_lines:
|
|
667
|
+
continue
|
|
668
|
+
if len(merged) >= max_results:
|
|
669
|
+
dropped += 1
|
|
670
|
+
continue
|
|
671
|
+
seen = counts.get(key[0], 0)
|
|
672
|
+
if seen >= per_file_cap:
|
|
673
|
+
overflow[m.get("file", "")] = overflow.get(m.get("file", ""), 0) + 1
|
|
674
|
+
continue
|
|
675
|
+
counts[key[0]] = seen + 1
|
|
676
|
+
merged.append(m)
|
|
677
|
+
|
|
678
|
+
text_source = str(text_result.get("source") or "disk_scan")
|
|
679
|
+
text_cov = text_result.get("coverage") or {}
|
|
680
|
+
hit_files = {m["file"] for m in merged}
|
|
681
|
+
n_text = len(merged) - len(decls)
|
|
682
|
+
coverage = dict(symbol_result.get("coverage") or {})
|
|
683
|
+
coverage["index_only"] = text_source != "disk_scan"
|
|
684
|
+
coverage["text"] = {
|
|
685
|
+
"source": text_source,
|
|
686
|
+
"complete": bool(text_cov.get("complete")),
|
|
687
|
+
"stopped_reason": text_cov.get("stopped_reason"),
|
|
688
|
+
"scanned_files": text_result.get("scanned_files"),
|
|
689
|
+
"total_files": text_result.get("total_files"),
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
scanned = int(text_result.get("scanned_files") or 0)
|
|
693
|
+
total_files = text_result.get("total_files")
|
|
694
|
+
markdown = cls._render_markdown(
|
|
695
|
+
symbol_result.get("query", ""), merged, scanned,
|
|
696
|
+
bool(text_result.get("timed_out")), max_results,
|
|
697
|
+
hit_files=hit_files, scope=scope, root_dir=root_dir,
|
|
698
|
+
overflow=overflow, per_file_cap=per_file_cap,
|
|
699
|
+
total_files=total_files,
|
|
700
|
+
stopped_reason=str(text_cov.get("stopped_reason") or "complete"),
|
|
701
|
+
coverage_complete=bool(text_cov.get("complete")),
|
|
702
|
+
coverage_source="graph_symbol_index" if text_source != "disk_scan" else "graph_symbol_index+disk_scan",
|
|
703
|
+
)
|
|
704
|
+
indexed = int(coverage.get("indexed_files") or 0)
|
|
705
|
+
age = symbol_result.get("index_age_s")
|
|
706
|
+
age_note = f", index age {int(age)}s" if age is not None else ""
|
|
707
|
+
if symbol_result.get("stale"):
|
|
708
|
+
age_note += " — stale, refresh with any graph tool"
|
|
709
|
+
markdown += (
|
|
710
|
+
f"\n_{len(decls)} declaration(s) first, from the AST symbol index"
|
|
711
|
+
f"{f' ({indexed} indexed files{age_note})' if indexed else ''}; "
|
|
712
|
+
f"then {n_text} text match(es) from {text_source}._"
|
|
713
|
+
)
|
|
714
|
+
|
|
715
|
+
result = dict(symbol_result)
|
|
716
|
+
result.update({
|
|
717
|
+
"matches": merged,
|
|
718
|
+
"total_matches": len(merged),
|
|
719
|
+
"declaration_matches": len(decls),
|
|
720
|
+
"text_matches": n_text,
|
|
721
|
+
"text_source": text_source,
|
|
722
|
+
"files_matched": len(hit_files),
|
|
723
|
+
"scanned_files": scanned or symbol_result.get("scanned_files"),
|
|
724
|
+
"total_files": total_files if total_files is not None else symbol_result.get("total_files"),
|
|
725
|
+
"overflow_matches": sum(overflow.values()),
|
|
726
|
+
"overflow_by_file": overflow,
|
|
727
|
+
"per_file_cap": per_file_cap,
|
|
728
|
+
"timed_out": bool(text_result.get("timed_out")),
|
|
729
|
+
"partial": bool(text_result.get("partial")),
|
|
730
|
+
"truncated": len(merged) >= max_results or bool(dropped) or bool(text_result.get("truncated")),
|
|
731
|
+
"coverage": coverage,
|
|
732
|
+
"markdown": markdown,
|
|
733
|
+
})
|
|
734
|
+
return result
|
|
735
|
+
|
|
598
736
|
@classmethod
|
|
599
737
|
def _search_single_file(
|
|
600
738
|
cls,
|
|
@@ -56,6 +56,16 @@ class SecretRedactor:
|
|
|
56
56
|
),
|
|
57
57
|
|
|
58
58
|
# AI Provider Keys
|
|
59
|
+
(
|
|
60
|
+
"openai_service_key",
|
|
61
|
+
re.compile(r"\bsk-(?:svcacct|admin)-[A-Za-z0-9_-]{40,}\b"),
|
|
62
|
+
"sk-svcacct-MOCK"
|
|
63
|
+
),
|
|
64
|
+
(
|
|
65
|
+
"google_api_key",
|
|
66
|
+
re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b"),
|
|
67
|
+
"AIza_MOCK"
|
|
68
|
+
),
|
|
59
69
|
(
|
|
60
70
|
"openai_key",
|
|
61
71
|
re.compile(r"\bsk-proj-[A-Za-z0-9_-]{40,}\b"),
|
|
@@ -78,6 +88,11 @@ class SecretRedactor:
|
|
|
78
88
|
re.compile(r"\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{22,})\b"),
|
|
79
89
|
"ghp_MOCK_GITHUB_TOKEN_ANCHOR"
|
|
80
90
|
),
|
|
91
|
+
(
|
|
92
|
+
"gitlab_token",
|
|
93
|
+
re.compile(r"\bglpat-[0-9A-Za-z_-]{20,}\b"),
|
|
94
|
+
"glpat-MOCK"
|
|
95
|
+
),
|
|
81
96
|
(
|
|
82
97
|
"slack_token",
|
|
83
98
|
re.compile(r"\bxox[baprs]-[0-9a-zA-Z-]{24,}\b"),
|
|
@@ -135,6 +150,13 @@ class SecretRedactor:
|
|
|
135
150
|
(re.compile(r"\bsk-ant-[A-Za-z0-9_-]{40,}\b"), "Detected live Anthropic API key hardcoded in code"),
|
|
136
151
|
(re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b"), "Detected GitHub personal access token hardcoded in code"),
|
|
137
152
|
(re.compile(r"\bxox[baprs]-[0-9a-zA-Z-]{24,}\b"), "Detected Slack API token hardcoded in code"),
|
|
153
|
+
(re.compile(r"\bsk-(?:svcacct|admin)-[A-Za-z0-9_-]{40,}\b"), "Detected OpenAI service-account/admin key hardcoded in code"),
|
|
154
|
+
(re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b"), "Detected Google API key hardcoded in code"),
|
|
155
|
+
(re.compile(r"\bglpat-[0-9A-Za-z_-]{20,}\b"), "Detected GitLab personal access token hardcoded in code"),
|
|
156
|
+
(
|
|
157
|
+
re.compile(r"""(?i)['"]?(?:aws_secret_access_key|aws_secret_key)['"]?\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])"""),
|
|
158
|
+
"Detected AWS secret access key hardcoded in code",
|
|
159
|
+
),
|
|
138
160
|
)
|
|
139
161
|
|
|
140
162
|
@classmethod
|
|
@@ -16,7 +16,7 @@ import json
|
|
|
16
16
|
import os
|
|
17
17
|
from typing import Any, Dict, List, Optional
|
|
18
18
|
|
|
19
|
-
from
|
|
19
|
+
from tokensafe.backend_release import BACKEND_RELEASE_TAG
|
|
20
20
|
|
|
21
21
|
MAX_BRIEF_CHARS = 1200
|
|
22
22
|
|
|
@@ -235,7 +235,7 @@ def _stack_labels(stack: Dict[str, Any]) -> List[tuple]:
|
|
|
235
235
|
|
|
236
236
|
def _is_root(path: str) -> bool:
|
|
237
237
|
try:
|
|
238
|
-
from
|
|
238
|
+
from tokensafe.paths import is_project_root
|
|
239
239
|
return bool(is_project_root(path))
|
|
240
240
|
except Exception:
|
|
241
241
|
return False
|
|
@@ -244,7 +244,7 @@ def _is_root(path: str) -> bool:
|
|
|
244
244
|
def _extra_root_lines(roots: List[str], seen: set) -> List[str]:
|
|
245
245
|
"""One compact line per non-primary root: ready → exact call, else fallback."""
|
|
246
246
|
try:
|
|
247
|
-
from
|
|
247
|
+
from tokensafe.retrofit import detect_project_stack
|
|
248
248
|
except Exception:
|
|
249
249
|
return []
|
|
250
250
|
lines: List[str] = []
|
|
@@ -282,7 +282,7 @@ def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
|
|
|
282
282
|
"""Exact next command(s) when an adapter is missing — no guessing."""
|
|
283
283
|
hints: List[str] = []
|
|
284
284
|
try:
|
|
285
|
-
from
|
|
285
|
+
from tokensafe.retrofit import run_doctor
|
|
286
286
|
doctor = run_doctor(workspace)
|
|
287
287
|
except Exception:
|
|
288
288
|
return hints
|
|
@@ -372,7 +372,7 @@ def build_workspace_brief(
|
|
|
372
372
|
return ""
|
|
373
373
|
|
|
374
374
|
try:
|
|
375
|
-
from
|
|
375
|
+
from tokensafe.retrofit import detect_project_stack_cached
|
|
376
376
|
stack = detect_project_stack_cached(workspace)
|
|
377
377
|
except Exception:
|
|
378
378
|
return ""
|
|
@@ -422,7 +422,7 @@ def build_workspace_brief(
|
|
|
422
422
|
# Machine-local project memory: decisions, known-good commands, notes.
|
|
423
423
|
# One line, capped, and only when memory actually exists.
|
|
424
424
|
try:
|
|
425
|
-
from
|
|
425
|
+
from tokensafe.project_memory import memory_summary
|
|
426
426
|
|
|
427
427
|
memory_line = memory_summary(workspace, max_chars=300)
|
|
428
428
|
if memory_line:
|
|
@@ -432,7 +432,7 @@ def build_workspace_brief(
|
|
|
432
432
|
|
|
433
433
|
if include_live:
|
|
434
434
|
try:
|
|
435
|
-
from
|
|
435
|
+
from tokensafe.oumv_gateway import OUMVGateway
|
|
436
436
|
status = OUMVGateway.status(workspace_dir=workspace, warm_graph=False)
|
|
437
437
|
live = []
|
|
438
438
|
for profile in ("frontend", "backend"):
|
|
@@ -451,7 +451,7 @@ def build_workspace_brief(
|
|
|
451
451
|
# String catalogs: only mention `dict` where a catalog actually exists, so
|
|
452
452
|
# projects without i18n never pay for the line.
|
|
453
453
|
try:
|
|
454
|
-
from
|
|
454
|
+
from tokensafe.i18n_catalog import resolve_messages_dir
|
|
455
455
|
if resolve_messages_dir(workspace):
|
|
456
456
|
entries.append((
|
|
457
457
|
9,
|
|
@@ -9,9 +9,9 @@ import re
|
|
|
9
9
|
import ast
|
|
10
10
|
import hashlib
|
|
11
11
|
import json
|
|
12
|
-
from typing import Optional, Tuple, Set
|
|
13
|
-
from
|
|
14
|
-
from
|
|
12
|
+
from typing import List, Optional, Tuple, Set
|
|
13
|
+
from tokensafe.tokenizer import count_tokens
|
|
14
|
+
from tokensafe.paths import resolve_data_dir
|
|
15
15
|
|
|
16
16
|
CONTROL_KEYWORDS = {
|
|
17
17
|
'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'default',
|
|
@@ -184,6 +184,27 @@ class Skeletonizer:
|
|
|
184
184
|
return out
|
|
185
185
|
|
|
186
186
|
CACHE_DIR = os.path.join(resolve_data_dir(), "skeletons")
|
|
187
|
+
_CODE_VERSION: Optional[str] = None
|
|
188
|
+
|
|
189
|
+
@classmethod
|
|
190
|
+
def _code_version(cls) -> str:
|
|
191
|
+
"""Fingerprint of the code that produces skeletons.
|
|
192
|
+
|
|
193
|
+
The on-disk cache was keyed on the source file's mtime and size only,
|
|
194
|
+
so a parser fix (e.g. tab-indented GDScript) kept serving the broken
|
|
195
|
+
skeleton until each file happened to change.
|
|
196
|
+
"""
|
|
197
|
+
if cls._CODE_VERSION is None:
|
|
198
|
+
digest = hashlib.md5()
|
|
199
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
200
|
+
for name in ("skeletonizer.py", "graph_engine.py"):
|
|
201
|
+
try:
|
|
202
|
+
with open(os.path.join(here, name), "rb") as fh:
|
|
203
|
+
digest.update(fh.read())
|
|
204
|
+
except OSError:
|
|
205
|
+
digest.update(name.encode("utf-8"))
|
|
206
|
+
cls._CODE_VERSION = digest.hexdigest()[:12]
|
|
207
|
+
return cls._CODE_VERSION
|
|
187
208
|
|
|
188
209
|
@classmethod
|
|
189
210
|
def _collapse_import_lines(cls, skeleton: str, ext: str) -> str:
|
|
@@ -268,7 +289,7 @@ class Skeletonizer:
|
|
|
268
289
|
):
|
|
269
290
|
res = None
|
|
270
291
|
try:
|
|
271
|
-
from
|
|
292
|
+
from tokensafe.treesitter_backend import TreeSitterBackend
|
|
272
293
|
res = TreeSitterBackend.skeletonize_braces(code, ext, keep_symbols=keep_symbols)
|
|
273
294
|
except Exception:
|
|
274
295
|
res = None
|
|
@@ -279,52 +300,92 @@ class Skeletonizer:
|
|
|
279
300
|
return cls._skeletonize_css(code, ext, keep_symbols=keep_symbols)
|
|
280
301
|
return code
|
|
281
302
|
|
|
282
|
-
_GD_FUNC_RE = re.compile(r"^(?:static\s+)?func\s+([A-Za-z_]\w*)")
|
|
303
|
+
_GD_FUNC_RE = re.compile(r"^(?:@\w+(?:\([^)]*\))?\s+)*(?:static\s+)?func\s+([A-Za-z_]\w*)")
|
|
283
304
|
_GD_CLASS_RE = re.compile(r"^(?:class|inner\s+class)\s+([A-Za-z_]\w*)")
|
|
284
305
|
_GD_DECL_RE = re.compile(
|
|
285
|
-
r"^(?:@?\w+\s*)*(?:class_name|extends|signal|enum|const|var)\b
|
|
306
|
+
r"^(?:@?\w+\s*)*(?:class_name|extends|signal|enum|const|var)\b|^@\w+"
|
|
286
307
|
)
|
|
308
|
+
_GD_TAB_WIDTH = 4 # Godot's default; only used to compare mixed tab/space indents
|
|
287
309
|
|
|
288
310
|
@classmethod
|
|
289
311
|
def _skeletonize_gdscript(cls, code: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
|
290
312
|
"""GDScript skeleton: declarations and signatures, folded function bodies.
|
|
291
313
|
|
|
292
314
|
GDScript is indentation-scoped (like Python), so the brace fallback would
|
|
293
|
-
mangle it.
|
|
294
|
-
|
|
315
|
+
mangle it. Indentation is measured on the leading whitespace with tabs
|
|
316
|
+
expanded (Godot indents with tabs by default), so tab-, space- and
|
|
317
|
+
consistently mixed-indented files fold the same way. Inner classes stay
|
|
318
|
+
open: their members and method signatures are listed, method bodies fold.
|
|
319
|
+
With `keep_symbols` the named functions (or `Class.method`, or a whole
|
|
320
|
+
class) keep their bodies; every other body folds to a single `# ...` line.
|
|
295
321
|
"""
|
|
296
322
|
keep = {str(s).strip() for s in (keep_symbols or set())}
|
|
297
|
-
out = []
|
|
298
|
-
|
|
323
|
+
out: List[str] = []
|
|
324
|
+
classes: List[Tuple[int, str]] = [] # open inner classes: (indent width, name)
|
|
325
|
+
block_width: Optional[int] = None # indent width of the open func (or kept class) header
|
|
299
326
|
keep_block = False
|
|
300
327
|
folded = 0
|
|
328
|
+
marker_ws = ""
|
|
329
|
+
sig_depth = 0 # unbalanced '(' of a signature that spans several lines
|
|
330
|
+
|
|
331
|
+
def width(ws: str) -> int:
|
|
332
|
+
return len(ws.expandtabs(cls._GD_TAB_WIDTH))
|
|
333
|
+
|
|
334
|
+
def paren_balance(text: str) -> int:
|
|
335
|
+
text = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'", "", text.split("#", 1)[0])
|
|
336
|
+
return text.count("(") + text.count("[") - text.count(")") - text.count("]")
|
|
337
|
+
|
|
338
|
+
def close_block() -> None:
|
|
339
|
+
if folded and not keep_block:
|
|
340
|
+
out.append(marker_ws + "# ...")
|
|
341
|
+
|
|
301
342
|
for raw in code.splitlines():
|
|
302
343
|
if not raw.strip():
|
|
303
344
|
continue
|
|
304
|
-
indent = len(raw) - len(raw.lstrip(" "))
|
|
305
345
|
stripped = raw.strip()
|
|
306
|
-
|
|
307
|
-
|
|
346
|
+
ws = raw[:len(raw) - len(raw.lstrip(" \t"))]
|
|
347
|
+
w = width(ws)
|
|
348
|
+
if sig_depth > 0:
|
|
349
|
+
out.append(raw.rstrip())
|
|
350
|
+
sig_depth = max(0, sig_depth + paren_balance(stripped))
|
|
351
|
+
continue
|
|
352
|
+
if block_width is not None:
|
|
353
|
+
if w > block_width:
|
|
308
354
|
if keep_block:
|
|
309
355
|
out.append(raw.rstrip())
|
|
310
356
|
else:
|
|
357
|
+
if not folded:
|
|
358
|
+
marker_ws = ws
|
|
311
359
|
folded += 1
|
|
312
360
|
continue
|
|
313
|
-
|
|
314
|
-
out.append(" " * block_indent + " # ...")
|
|
361
|
+
close_block()
|
|
315
362
|
folded = 0
|
|
316
|
-
|
|
363
|
+
block_width = None
|
|
317
364
|
keep_block = False
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
365
|
+
while classes and w <= classes[-1][0]:
|
|
366
|
+
classes.pop()
|
|
367
|
+
qual_prefix = ".".join(name for _, name in classes)
|
|
368
|
+
fm = cls._GD_FUNC_RE.match(stripped)
|
|
369
|
+
cm = None if fm else cls._GD_CLASS_RE.match(stripped)
|
|
370
|
+
if fm or cm:
|
|
371
|
+
name = (fm or cm).group(1)
|
|
372
|
+
qual = f"{qual_prefix}.{name}" if qual_prefix else name
|
|
373
|
+
wanted = bool(keep) and (name in keep or qual in keep)
|
|
322
374
|
out.append(raw.rstrip())
|
|
375
|
+
if cm and not wanted:
|
|
376
|
+
classes.append((w, name)) # stay open: list members, fold method bodies
|
|
377
|
+
continue
|
|
378
|
+
block_width = w
|
|
379
|
+
keep_block = wanted
|
|
380
|
+
folded = 0
|
|
381
|
+
marker_ws = ws + " " # replaced by the first folded body line's own indent
|
|
382
|
+
if fm:
|
|
383
|
+
sig_depth = max(0, paren_balance(stripped))
|
|
323
384
|
continue
|
|
324
385
|
if stripped.startswith("#") or cls._GD_DECL_RE.match(stripped):
|
|
325
386
|
out.append(raw.rstrip())
|
|
326
|
-
if
|
|
327
|
-
|
|
387
|
+
if block_width is not None:
|
|
388
|
+
close_block()
|
|
328
389
|
return "\n".join(out)
|
|
329
390
|
|
|
330
391
|
@classmethod
|
|
@@ -845,7 +906,7 @@ class Skeletonizer:
|
|
|
845
906
|
|
|
846
907
|
# Ensure cache directory exists
|
|
847
908
|
os.makedirs(cls.CACHE_DIR, exist_ok=True)
|
|
848
|
-
from
|
|
909
|
+
from tokensafe.win_paths import state_key
|
|
849
910
|
|
|
850
911
|
# Windows forbids reserved device names, trailing dots/spaces and
|
|
851
912
|
# punctuation in file names; a repo basename must never abort a read.
|
|
@@ -867,7 +928,8 @@ class Skeletonizer:
|
|
|
867
928
|
with open(meta_path, "r", encoding="utf-8") as mf:
|
|
868
929
|
meta = json.load(mf)
|
|
869
930
|
# mtime alone can miss a same-tick rewrite; size guards against it
|
|
870
|
-
if meta.get("mtime") == current_mtime and meta.get("size") == file_size
|
|
931
|
+
if (meta.get("mtime") == current_mtime and meta.get("size") == file_size
|
|
932
|
+
and meta.get("code") == cls._code_version()):
|
|
871
933
|
# Cache hit! Return immediately in 0.05ms
|
|
872
934
|
return skeleton_path, meta.get("orig_tokens", 0), meta.get("skel_tokens", 0)
|
|
873
935
|
except Exception:
|
|
@@ -889,7 +951,7 @@ class Skeletonizer:
|
|
|
889
951
|
# If target symbol specified, use Graph-Guided skeletonization only if symbol is present
|
|
890
952
|
if target_symbol:
|
|
891
953
|
try:
|
|
892
|
-
from
|
|
954
|
+
from tokensafe.graph_engine import GraphEngine
|
|
893
955
|
graph, _rel_path = GraphEngine.for_file(original_path)
|
|
894
956
|
has_sym = bool(re.search(rf"\b{re.escape(target_symbol)}\b", code))
|
|
895
957
|
if has_sym:
|
|
@@ -903,7 +965,7 @@ class Skeletonizer:
|
|
|
903
965
|
skeleton_content = cls.skeletonize_code(code, ext)
|
|
904
966
|
|
|
905
967
|
# Prefetch local dependency signatures
|
|
906
|
-
from
|
|
968
|
+
from tokensafe.dependency_prefetcher import DependencyPrefetcher
|
|
907
969
|
prefetch_block, saved_dep_tokens = DependencyPrefetcher.prefetch_for_file(original_path)
|
|
908
970
|
|
|
909
971
|
orig_tokens = count_tokens(code)
|
|
@@ -937,6 +999,7 @@ class Skeletonizer:
|
|
|
937
999
|
json.dump({
|
|
938
1000
|
"mtime": current_mtime,
|
|
939
1001
|
"size": file_size,
|
|
1002
|
+
"code": cls._code_version(),
|
|
940
1003
|
"orig_tokens": orig_tokens,
|
|
941
1004
|
"skel_tokens": skel_tokens,
|
|
942
1005
|
"lines_count": lines_count
|
|
@@ -7,7 +7,7 @@ import os
|
|
|
7
7
|
import re
|
|
8
8
|
import stat
|
|
9
9
|
from typing import Dict, Any, List, Optional, Tuple
|
|
10
|
-
from
|
|
10
|
+
from tokensafe.tokenizer import count_tokens
|
|
11
11
|
|
|
12
12
|
class ToolSlicer:
|
|
13
13
|
"""Optimizes tool execution parameters to minimize token consumption."""
|
|
@@ -69,7 +69,8 @@ class ToolSlicer:
|
|
|
69
69
|
elif ch == "}":
|
|
70
70
|
depth -= 1
|
|
71
71
|
if depth == 0:
|
|
72
|
-
|
|
72
|
+
# Runs once per call; count in place instead of slicing a copy.
|
|
73
|
+
return def_line_no + text.count("\n", 0, offset + i + 1)
|
|
73
74
|
# Unbalanced within the cap: report the cap boundary as the end
|
|
74
75
|
return window_end
|
|
75
76
|
|
|
@@ -175,7 +175,7 @@ def _get_layout_summary(workspace_dir: str, max_depth: int = 2) -> Optional[str]
|
|
|
175
175
|
# directory matching is done here.
|
|
176
176
|
is_ignored = None
|
|
177
177
|
try:
|
|
178
|
-
from
|
|
178
|
+
from tokensafe.guard import TokenSafeGuard
|
|
179
179
|
patterns = TokenSafeGuard._load_gitignore_patterns(workspace_dir)
|
|
180
180
|
|
|
181
181
|
def is_ignored(p: str) -> bool: # type: ignore[misc]
|
|
@@ -18,7 +18,7 @@ import hashlib
|
|
|
18
18
|
import threading
|
|
19
19
|
from typing import Tuple, Optional, Dict, Any
|
|
20
20
|
|
|
21
|
-
from
|
|
21
|
+
from tokensafe.paths import resolve_data_dir
|
|
22
22
|
|
|
23
23
|
STASH_DIRNAME = "stash"
|
|
24
24
|
MAX_STASH_CHARS = 5 * 1024 * 1024 # Cap single artifact at 5 MB
|
|
@@ -25,7 +25,7 @@ def _human(number: int) -> str:
|
|
|
25
25
|
def render_statusline() -> str:
|
|
26
26
|
"""One compact line, or an empty string when there is nothing to show."""
|
|
27
27
|
try:
|
|
28
|
-
from
|
|
28
|
+
from tokensafe.metrics import MetricsTracker
|
|
29
29
|
|
|
30
30
|
tracker = MetricsTracker()
|
|
31
31
|
start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).isoformat()
|
|
@@ -10,8 +10,8 @@ pointing to TokenSafe's local stash, recovering 30-50% context window mass.
|
|
|
10
10
|
import os
|
|
11
11
|
import json
|
|
12
12
|
from typing import List, Dict, Any, Tuple, Optional, Set
|
|
13
|
-
from
|
|
14
|
-
from
|
|
13
|
+
from tokensafe.stash import stash_block
|
|
14
|
+
from tokensafe.tokenizer import count_tokens
|
|
15
15
|
|
|
16
16
|
_READ_TOOLS = {
|
|
17
17
|
"read_file", "view_file", "Read", "smart_read_file",
|
|
@@ -23,14 +23,32 @@ _EDIT_TOOLS = {
|
|
|
23
23
|
_PATH_KEYS = ("Path", "path", "FilePath", "file_path", "TargetFile", "notebook_path")
|
|
24
24
|
|
|
25
25
|
|
|
26
|
+
def _call_base(args: Dict[str, Any]) -> str:
|
|
27
|
+
"""The root a relative path in this call resolves against (`root`/`cwd`)."""
|
|
28
|
+
for key in ("root", "cwd"):
|
|
29
|
+
val = args.get(key)
|
|
30
|
+
if isinstance(val, str) and val.strip():
|
|
31
|
+
return val.strip()
|
|
32
|
+
return ""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _abs_in(base: str, val: str) -> str:
|
|
36
|
+
# A relative path means a different file in each root: `app.py` read in
|
|
37
|
+
# worktree B is not superseded by an edit of `app.py` in worktree A.
|
|
38
|
+
if base and not os.path.isabs(val):
|
|
39
|
+
return os.path.abspath(os.path.join(base, val))
|
|
40
|
+
return os.path.abspath(val)
|
|
41
|
+
|
|
42
|
+
|
|
26
43
|
def _extract_paths_from_args(args: Any) -> List[str]:
|
|
27
44
|
if not isinstance(args, dict):
|
|
28
45
|
return []
|
|
29
46
|
found: List[str] = []
|
|
47
|
+
base = _call_base(args)
|
|
30
48
|
for k in _PATH_KEYS:
|
|
31
49
|
val = args.get(k)
|
|
32
50
|
if isinstance(val, str) and val.strip():
|
|
33
|
-
found.append(
|
|
51
|
+
found.append(_abs_in(base, val.strip()))
|
|
34
52
|
for list_key in ("edits", "targets"):
|
|
35
53
|
items = args.get(list_key)
|
|
36
54
|
if isinstance(items, list):
|
|
@@ -39,7 +57,7 @@ def _extract_paths_from_args(args: Any) -> List[str]:
|
|
|
39
57
|
for k in _PATH_KEYS:
|
|
40
58
|
val = item.get(k)
|
|
41
59
|
if isinstance(val, str) and val.strip():
|
|
42
|
-
found.append(
|
|
60
|
+
found.append(_abs_in(_call_base(item) or base, val.strip()))
|
|
43
61
|
break
|
|
44
62
|
return list(dict.fromkeys(found))
|
|
45
63
|
|
|
@@ -13,8 +13,8 @@ import urllib.request
|
|
|
13
13
|
import urllib.error
|
|
14
14
|
import urllib.parse
|
|
15
15
|
from typing import Optional, Dict, Any, Tuple, List
|
|
16
|
-
from
|
|
17
|
-
from
|
|
16
|
+
from tokensafe.license_manager import LicenseManager
|
|
17
|
+
from tokensafe.ssl_context import shared_ssl_context
|
|
18
18
|
|
|
19
19
|
class TeamCache:
|
|
20
20
|
"""Distributed cross-developer cache client for TokenSafe Team tier."""
|
|
@@ -168,7 +168,7 @@ class TeamCache:
|
|
|
168
168
|
|
|
169
169
|
safe_value = value
|
|
170
170
|
try:
|
|
171
|
-
from
|
|
171
|
+
from tokensafe.secret_redactor import SecretRedactor
|
|
172
172
|
safe_value, _, _ = SecretRedactor.redact_text(value)
|
|
173
173
|
except Exception:
|
|
174
174
|
pass
|