tzero-mcp 11.15.3 → 12.2.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.
Files changed (71) hide show
  1. package/CONTRIBUTING.md +4 -4
  2. package/README.md +5 -5
  3. package/bin/postinstall.js +10 -2
  4. package/bin/tzero-mcp.js +1 -1
  5. package/bin/tzero.js +17 -0
  6. package/package.json +1 -1
  7. package/src/addmcp.py +34 -23
  8. package/src/app.py +1 -1
  9. package/src/main.py +6 -0
  10. package/src/tzero/__init__.py +10 -0
  11. package/src/tzero/anti_rea/__init__.py +70 -0
  12. package/src/tzero/anti_rea/algebraic_mutator.py +86 -0
  13. package/src/tzero/anti_rea/anti_agent_guard.py +96 -0
  14. package/src/tzero/anti_rea/anti_debugger.py +239 -0
  15. package/src/tzero/anti_rea/anti_vm.py +160 -0
  16. package/src/tzero/anti_rea/asar_shield.py +99 -0
  17. package/src/tzero/anti_rea/auditor.py +158 -0
  18. package/src/tzero/anti_rea/bpe_disrupter.py +48 -0
  19. package/src/tzero/anti_rea/bytecode_trap.py +85 -0
  20. package/src/tzero/anti_rea/canary_beacon.py +187 -0
  21. package/src/tzero/anti_rea/cli.py +102 -0
  22. package/src/tzero/anti_rea/confusables.py +86 -0
  23. package/src/tzero/anti_rea/engine.py +204 -0
  24. package/src/tzero/anti_rea/extractor_shield.py +102 -0
  25. package/src/tzero/anti_rea/flattener.py +136 -0
  26. package/src/tzero/anti_rea/gui.py +267 -0
  27. package/src/tzero/anti_rea/honeypot.py +58 -0
  28. package/src/tzero/anti_rea/integrity_guard.py +66 -0
  29. package/src/tzero/anti_rea/jailbreak_decoy.py +77 -0
  30. package/src/tzero/anti_rea/mcp_poison.py +41 -0
  31. package/src/tzero/anti_rea/native_bridge.py +169 -0
  32. package/src/tzero/anti_rea/rdtsc_guard.py +64 -0
  33. package/src/tzero/anti_rea/string_vault.py +94 -0
  34. package/src/tzero/anti_rea/sybil_network.py +53 -0
  35. package/src/tzero/anti_rea/timing_guard.py +46 -0
  36. package/src/tzero/anti_rea/token_bomb.py +65 -0
  37. package/src/tzero/anti_rea/traps.py +76 -0
  38. package/src/tzero/anti_rea/vm_obfuscator.py +182 -0
  39. package/src/tzero/siber_akademi.ico +0 -0
  40. package/src/tzero/siber_akademi_icon.py +1 -1
  41. package/src/tzero/tzero_armor.py +165 -0
  42. package/src/tzero/tzero_bridge.py +28 -15
  43. package/src/tzero/tzero_budget.py +10 -3
  44. package/src/tzero/tzero_card.py +7 -5
  45. package/src/tzero/tzero_ci.py +1 -0
  46. package/src/tzero/tzero_contracts.py +30 -11
  47. package/src/tzero/tzero_dashboard.py +34 -14
  48. package/src/tzero/tzero_debt.py +14 -5
  49. package/src/tzero/tzero_federation.py +11 -6
  50. package/src/tzero/tzero_fixer/security_zero_leak.py +21 -3
  51. package/src/tzero/tzero_golden.py +11 -6
  52. package/src/tzero/tzero_graph_hud.html +1 -1
  53. package/src/tzero/tzero_growth.py +10 -10
  54. package/src/tzero/tzero_jarvis/agent_guard.py +16 -10
  55. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +34 -23
  56. package/src/tzero/tzero_lsp.py +1 -1
  57. package/src/tzero/tzero_mcp.py +89 -31
  58. package/src/tzero/tzero_mutation.py +44 -16
  59. package/src/tzero/tzero_neural_cortex.py +1 -1
  60. package/src/tzero/tzero_pc_fixer.py +21 -3
  61. package/src/tzero/tzero_promo.py +196 -36
  62. package/src/tzero/tzero_rust_bridge.py +1086 -42
  63. package/src/tzero/tzero_scip.py +15 -2
  64. package/src/tzero/tzero_semantic_merge.py +34 -10
  65. package/src/tzero/tzero_task_benchmark.py +2 -2
  66. package/src/tzero/tzero_telemetry.py +146 -0
  67. package/src/tzero/tzero_terminal.py +366 -0
  68. package/src/tzero/tzero_traffic.py +350 -0
  69. package/src/tzero/tzero_tui.py +342 -133
  70. package/src/tzero/tzero_v3.py +652 -29
  71. package/src/tzero/tzero_welcome.py +72 -12
@@ -338,9 +338,22 @@ class ScipIndexImporter:
338
338
 
339
339
  @classmethod
340
340
  def load(cls, path: str) -> ScipIndexGraph:
341
- if not os.path.isfile(path):
341
+ if not path or "\x00" in path:
342
+ raise ValueError("Invalid SCIP/LSIF index path.")
343
+ import tempfile
344
+ ws_root = os.path.realpath(".")
345
+ tmp_root = os.path.realpath(tempfile.gettempdir())
346
+ home_root = os.path.realpath(os.path.expanduser("~"))
347
+ real_path = os.path.normpath(os.path.realpath(os.path.abspath(path)))
348
+ if (
349
+ not real_path.startswith(ws_root + os.sep)
350
+ and not real_path.startswith(tmp_root + os.sep)
351
+ and not real_path.startswith(home_root + os.sep)
352
+ ):
353
+ raise ValueError(f"SCIP/LSIF path outside allowed scope: {path}")
354
+ if not os.path.isfile(real_path):
342
355
  raise FileNotFoundError(f"SCIP/LSIF index file not found: {path}")
343
- with open(path, "rb") as f:
356
+ with open(real_path, "rb") as f:
344
357
  raw = f.read()
345
358
  if not raw.strip():
346
359
  return ScipIndexGraph(format_name="empty", document_count=0)
@@ -32,15 +32,42 @@ class MergeResult:
32
32
  class ASTSemanticMerger:
33
33
  """Semantic AST-aware 3-way merger and git conflict block healer."""
34
34
 
35
- CONFLICT_PATTERN = re.compile(
36
- r'<<<<<<<[^\n]*\n(.*?)=======\n(.*?)>>>>>>>[^\n]*\n',
37
- re.DOTALL
38
- )
35
+ CONFLICT_PATTERN = re.compile(r'^<<<<<<<[^\n]*$', re.MULTILINE)
36
+
37
+ @classmethod
38
+ def _find_conflict_blocks(cls, text: str) -> List[Tuple[str, str, str]]:
39
+ """Scans text linearly O(N) for git conflict blocks without regex backtracking."""
40
+ blocks: List[Tuple[str, str, str]] = []
41
+ lines = text.splitlines(keepends=True)
42
+ i = 0
43
+ n = len(lines)
44
+ while i < n:
45
+ if lines[i].startswith("<<<<<<<"):
46
+ start = i
47
+ sep = -1
48
+ end = -1
49
+ j = i + 1
50
+ while j < n:
51
+ if sep == -1 and lines[j].startswith("======="):
52
+ sep = j
53
+ elif sep != -1 and lines[j].startswith(">>>>>>>"):
54
+ end = j
55
+ break
56
+ j += 1
57
+ if sep != -1 and end != -1:
58
+ full_match = "".join(lines[start:end + 1])
59
+ ours_block = "".join(lines[start + 1:sep])
60
+ theirs_block = "".join(lines[sep + 1:end])
61
+ blocks.append((full_match, ours_block, theirs_block))
62
+ i = end + 1
63
+ continue
64
+ i += 1
65
+ return blocks
39
66
 
40
67
  @classmethod
41
68
  def has_conflict_markers(cls, text: str) -> bool:
42
69
  """Returns True if file contains standard git conflict markers."""
43
- return bool(cls.CONFLICT_PATTERN.search(text))
70
+ return len(cls._find_conflict_blocks(text)) > 0
44
71
 
45
72
  @classmethod
46
73
  def extract_ast_symbols(cls, code: str) -> Dict[str, str]:
@@ -73,7 +100,7 @@ class ASTSemanticMerger:
73
100
  Scans content for git conflict blocks (<<<<<<< ... ======= ... >>>>>>>)
74
101
  and attempts semantic AST healing.
75
102
  """
76
- matches = list(cls.CONFLICT_PATTERN.finditer(content))
103
+ matches = cls._find_conflict_blocks(content)
77
104
  if not matches:
78
105
  return MergeResult(
79
106
  success=True,
@@ -91,10 +118,7 @@ class ASTSemanticMerger:
91
118
  added_theirs = []
92
119
 
93
120
  # Process each conflict block
94
- for idx, m in enumerate(matches, 1):
95
- full_match = m.group(0)
96
- ours_block = m.group(1)
97
- theirs_block = m.group(2)
121
+ for idx, (full_match, ours_block, theirs_block) in enumerate(matches, 1):
98
122
 
99
123
  ours_syms = cls.extract_ast_symbols(ours_block)
100
124
  theirs_syms = cls.extract_ast_symbols(theirs_block)
@@ -75,7 +75,7 @@ class TaskEvaluationResult:
75
75
 
76
76
  @dataclass
77
77
  class TaskBenchmarkReport:
78
- version: str = "11.15.2"
78
+ version: str = "12.2.0"
79
79
  tokenizer: str = "tiktoken (cl100k_base)" if TIKTOKEN_AVAILABLE else "character-ratio fallback"
80
80
  total_tasks: int = 0
81
81
  passed_tasks: int = 0
@@ -465,7 +465,7 @@ def analyze_symbol_impact(symbol_path: str, table: SymbolTable, dag: CallGraphDA
465
465
  """Formats ANSI-styled benchmark summary table."""
466
466
  lines = []
467
467
  lines.append("=" * 78)
468
- lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v11.15.2)")
468
+ lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v12.2.0)")
469
469
  lines.append(f" Tokenizer: {report.tokenizer} | Tasks Evaluated: {report.total_tasks}")
470
470
  lines.append("=" * 78)
471
471
  lines.append(f"{'Task ID':<10} | {'Raw BPE':<8} | {'T-Zero':<8} | {'Saved %':<8} | {'Contract %':<10} | {'Status'}")
@@ -0,0 +1,146 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Local SQLite Token Savings & ROI Telemetry Engine for T-Zero.
3
+
4
+ 100% offline, zero-network telemetry store persisted under `.tzero/telemetry.db`
5
+ (or `TZERO_TELEMETRY_DB` env override) so developers can measure cumulative
6
+ raw vs. pruned tokens, reduction ratio, and USD savings across local runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import sqlite3
13
+ import time
14
+ from typing import Any, Dict, List, Optional
15
+
16
+
17
+ DEFAULT_PRICE_PER_M_TOKENS = 3.00 # Conservative Sonnet-tier blended input rate
18
+
19
+
20
+ def _resolve_db_path(workspace_dir: str = ".") -> str:
21
+ env_override = os.environ.get("TZERO_TELEMETRY_DB")
22
+ if env_override:
23
+ db_dir = os.path.dirname(os.path.abspath(env_override))
24
+ if db_dir:
25
+ os.makedirs(db_dir, exist_ok=True)
26
+ return os.path.abspath(env_override)
27
+ ws_tzero = os.path.join(os.path.abspath(workspace_dir), ".tzero")
28
+ os.makedirs(ws_tzero, exist_ok=True)
29
+ return os.path.join(ws_tzero, "telemetry.db")
30
+
31
+
32
+ def _connect(db_path: str) -> sqlite3.Connection:
33
+ conn = sqlite3.connect(db_path, timeout=5.0)
34
+ conn.execute(
35
+ """
36
+ CREATE TABLE IF NOT EXISTS savings_events (
37
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
38
+ ts REAL NOT NULL,
39
+ command TEXT NOT NULL,
40
+ raw_tokens INTEGER NOT NULL,
41
+ pruned_tokens INTEGER NOT NULL,
42
+ saved_tokens INTEGER NOT NULL,
43
+ usd_saved REAL NOT NULL
44
+ )
45
+ """
46
+ )
47
+ conn.commit()
48
+ return conn
49
+
50
+
51
+ def record_event(
52
+ command: str,
53
+ raw_tokens: int,
54
+ pruned_tokens: int,
55
+ workspace_dir: str = ".",
56
+ price_per_million: float = DEFAULT_PRICE_PER_M_TOKENS,
57
+ ) -> Dict[str, Any]:
58
+ """Records a local compression/telemetry event into SQLite."""
59
+ raw = max(0, int(raw_tokens))
60
+ pruned = max(0, int(pruned_tokens))
61
+ saved = max(0, raw - pruned)
62
+ usd = (saved / 1_000_000.0) * float(price_per_million)
63
+ db_path = _resolve_db_path(workspace_dir)
64
+ conn = _connect(db_path)
65
+ try:
66
+ with conn:
67
+ conn.execute(
68
+ "INSERT INTO savings_events (ts, command, raw_tokens, pruned_tokens, saved_tokens, usd_saved) VALUES (?, ?, ?, ?, ?, ?)",
69
+ (time.time(), str(command)[:64], raw, pruned, saved, round(usd, 6)),
70
+ )
71
+ finally:
72
+ conn.close()
73
+ return {
74
+ "command": command,
75
+ "raw_tokens": raw,
76
+ "pruned_tokens": pruned,
77
+ "saved_tokens": saved,
78
+ "usd_saved": round(usd, 6),
79
+ "db_path": db_path,
80
+ }
81
+
82
+
83
+ def get_summary(workspace_dir: str = ".", days: int = 30) -> Dict[str, Any]:
84
+ """Returns aggregated local telemetry stats over the trailing `days` window."""
85
+ db_path = _resolve_db_path(workspace_dir)
86
+ since_ts = time.time() - (max(1, int(days)) * 86400.0)
87
+ conn = _connect(db_path)
88
+ try:
89
+ with conn:
90
+ row = conn.execute(
91
+ """
92
+ SELECT COUNT(*), COALESCE(SUM(raw_tokens), 0), COALESCE(SUM(pruned_tokens), 0),
93
+ COALESCE(SUM(saved_tokens), 0), COALESCE(SUM(usd_saved), 0.0)
94
+ FROM savings_events WHERE ts >= ?
95
+ """,
96
+ (since_ts,),
97
+ ).fetchone()
98
+ recent_rows = conn.execute(
99
+ """
100
+ SELECT command, COUNT(*), COALESCE(SUM(saved_tokens), 0), COALESCE(SUM(usd_saved), 0.0)
101
+ FROM savings_events WHERE ts >= ?
102
+ GROUP BY command ORDER BY SUM(saved_tokens) DESC LIMIT 8
103
+ """,
104
+ (since_ts,),
105
+ ).fetchall()
106
+ finally:
107
+ conn.close()
108
+
109
+ runs, total_raw, total_pruned, total_saved, total_usd = row
110
+ reduction_pct = round((total_saved / total_raw) * 100.0, 2) if total_raw > 0 else 0.0
111
+ by_command: List[Dict[str, Any]] = [
112
+ {"command": r[0], "runs": r[1], "saved_tokens": r[2], "usd_saved": round(float(r[3]), 4)}
113
+ for r in recent_rows
114
+ ]
115
+ return {
116
+ "days": days,
117
+ "db_path": db_path,
118
+ "runs": int(runs),
119
+ "raw_tokens": int(total_raw),
120
+ "pruned_tokens": int(total_pruned),
121
+ "saved_tokens": int(total_saved),
122
+ "reduction_pct": reduction_pct,
123
+ "usd_saved": round(float(total_usd), 4),
124
+ "by_command": by_command,
125
+ }
126
+
127
+
128
+ def render_report(workspace_dir: str = ".", days: int = 30) -> str:
129
+ """Formats a human-readable ASCII/Markdown telemetry summary."""
130
+ summary = get_summary(workspace_dir=workspace_dir, days=days)
131
+ lines = [
132
+ f"### 📊 T-Zero Offline SQLite Telemetry (Last {summary['days']} Days)",
133
+ f"- **Store:** `{summary['db_path']}` (100% Local / Zero Network)",
134
+ f"- **Recorded Runs:** `{summary['runs']}`",
135
+ f"- **Raw Tokens Scanned:** `{summary['raw_tokens']:,}`",
136
+ f"- **Pruned Tokens Emitted:** `{summary['pruned_tokens']:,}`",
137
+ f"- **Net Tokens Saved:** `{summary['saved_tokens']:,}` (`{summary['reduction_pct']}%`)",
138
+ f"- **Estimated Cost Avoided:** `${summary['usd_saved']:.4f}`",
139
+ ]
140
+ if summary["by_command"]:
141
+ lines.append("\n#### Top Commands:")
142
+ for item in summary["by_command"]:
143
+ lines.append(
144
+ f"- `{item['command']}`: {item['runs']} run(s), {item['saved_tokens']:,} tokens saved (`${item['usd_saved']:.4f}`)"
145
+ )
146
+ return "\n".join(lines)
@@ -0,0 +1,366 @@
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Universal Terminal & Console Output Manager.
3
+
4
+ Ensures crystal-clear console rendering across Windows CMD (cmd.exe),
5
+ PowerShell, Windows Terminal, macOS Terminal, Linux VT100/xterm, and IDE consoles.
6
+
7
+ Key Capabilities:
8
+ 1. Enables VT100 Virtual Terminal Processing (ENABLE_VIRTUAL_TERMINAL_PROCESSING)
9
+ on Windows conhost so ANSI escape sequences render colors rather than raw '←[1;36m'.
10
+ 2. Sets console code pages to UTF-8 (65001) on Windows.
11
+ 3. Transparently sanitizes Supplementary Multilingual Plane (SMP) emojis
12
+ (> U+FFFF, such as 👉, 💡, 🚀, 🐦, 🔴, etc.) into clean, beautiful BMP
13
+ or ASCII equivalents when running in legacy Windows CMD where standard fonts
14
+ fail to render them and show ''.
15
+ 4. Strips ANSI escape sequences cleanly when stdout is redirected to a pipe/file
16
+ or when ANSI color is not supported by the environment.
17
+
18
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
19
+ License: AGPL-3.0-only
20
+ Repository: https://github.com/toprakahmetaydogmus/TZeroAlgorithm
21
+ """
22
+
23
+ import io
24
+ import os
25
+ import re
26
+ import sys
27
+ from typing import Any, Dict, Optional, TextIO
28
+
29
+ # ANSI escape sequence regex (colors, formatting, cursor movements)
30
+ ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]|\033\[[0-9;]*[a-zA-Z]")
31
+
32
+ # Supplementary Multilingual Plane (SMP) regex (characters above U+FFFF)
33
+ SMP_CHAR_RE = re.compile(r"[\U00010000-\U0010ffff]")
34
+
35
+ # High-fidelity replacement dictionary for SMP emojis when console cannot render them
36
+ SMP_EMOJI_FALLBACKS: Dict[str, str] = {
37
+ # Hand pointers
38
+ "👉": "►",
39
+ "👈": "◄",
40
+ "👆": "▲",
41
+ "👇": "▼",
42
+ "👋": "*",
43
+ # Icons & Indicators
44
+ "💡": "•",
45
+ "🚀": "[T-Zero]",
46
+ "⭐": "★",
47
+ "🌟": "★",
48
+ "🎉": "★",
49
+ "✨": "*",
50
+ "🔥": "*",
51
+ "⚡": "*",
52
+ "🎯": "[Target]",
53
+ "📊": "[Stats]",
54
+ "📈": "[+]",
55
+ "📉": "[-]",
56
+ "📁": "[Dir]",
57
+ "📂": "[Dir]",
58
+ "📄": "[Doc]",
59
+ "📝": "[Note]",
60
+ "📋": "[List]",
61
+ "📌": "[Pin]",
62
+ "📚": "[Docs]",
63
+ "💾": "[Save]",
64
+ "🔒": "[Lock]",
65
+ "🛡": "[Shield]",
66
+ "🚨": "[Alert]",
67
+ "💉": "[Fix]",
68
+ "🩺": "[Doctor]",
69
+ "🩹": "[Patch]",
70
+ "🤖": "[AI]",
71
+ "🏆": "[Top]",
72
+ "🔍": "[Search]",
73
+ "🔧": "[Tool]",
74
+ "🛠": "[Tools]",
75
+ "📦": "[Pkg]",
76
+ "🌐": "[Web]",
77
+ "🏛": "[Arch]",
78
+ "🐝": "[Swarm]",
79
+ "👑": "[Master]",
80
+ "💸": "[$]",
81
+ "💰": "[$]",
82
+ "🏦": "[Bank]",
83
+ "🧬": "[AST]",
84
+ "🧠": "[Brain]",
85
+ "🕒": "[Time]",
86
+ "🚪": "[Exit]",
87
+ "🍎": "[Apple]",
88
+ "🐍": "[Py]",
89
+ "🐹": "[Go]",
90
+ "🌙": "[Night]",
91
+ "🏠": "[Home]",
92
+ "🏢": "[Work]",
93
+ "🏥": "[Health]",
94
+ "🎨": "[Art]",
95
+ "🎬": "[Media]",
96
+ "🎥": "[Video]",
97
+ "📢": "[Notice]",
98
+ "🔁": "[Loop]",
99
+ "🔗": "[Link]",
100
+ "💥": "[!]",
101
+ "🧩": "[Module]",
102
+ "🔌": "[Plugin]",
103
+ "🧹": "[Clean]",
104
+ "🗡": "[Test]",
105
+ # Social Platforms
106
+ "🐦": "[X]",
107
+ "🔴": "[Reddit]",
108
+ "🟠": "[HN]",
109
+ "💼": "[LinkedIn]",
110
+ "💬": "[WhatsApp]",
111
+ # Color indicators
112
+ "🟢": "(+)",
113
+ "🟡": "(!)",
114
+ "🔵": "(i)",
115
+ "🟣": "(*)",
116
+ "🔷": "[*]",
117
+ "🟨": "[!]",
118
+ }
119
+
120
+ _INITIALIZED = False
121
+ _VT100_ENABLED = False
122
+
123
+
124
+ def enable_windows_vt100() -> bool:
125
+ """Enables Virtual Terminal Processing (VT100) on Windows console handles."""
126
+ global _VT100_ENABLED
127
+ if not sys.platform.startswith("win"):
128
+ _VT100_ENABLED = True
129
+ return True
130
+
131
+ try:
132
+ import ctypes
133
+
134
+ kernel32 = ctypes.windll.kernel32
135
+
136
+ # 1. Enable on standard output and error handles
137
+ # STD_OUTPUT_HANDLE = -11, STD_ERROR_HANDLE = -12
138
+ for handle_id in (-11, -12):
139
+ h = kernel32.GetStdHandle(handle_id)
140
+ if h and h != -1:
141
+ mode = ctypes.c_ulong()
142
+ if kernel32.GetConsoleMode(h, ctypes.byref(mode)):
143
+ # ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
144
+ # DISABLE_NEWLINE_AUTO_RETURN = 0x0008
145
+ kernel32.SetConsoleMode(h, mode.value | 0x0004 | 0x0008)
146
+ _VT100_ENABLED = True
147
+
148
+ # 2. Also attempt directly on CONOUT$ (works even when stdout is redirected)
149
+ try:
150
+ GENERIC_READ = 0x80000000
151
+ GENERIC_WRITE = 0x40000000
152
+ FILE_SHARE_READ = 1
153
+ FILE_SHARE_WRITE = 2
154
+ OPEN_EXISTING = 3
155
+ h_con = kernel32.CreateFileW(
156
+ "CONOUT$",
157
+ GENERIC_READ | GENERIC_WRITE,
158
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
159
+ None,
160
+ OPEN_EXISTING,
161
+ 0,
162
+ 0,
163
+ )
164
+ if h_con != -1 and h_con != 0:
165
+ mode = ctypes.c_ulong()
166
+ if kernel32.GetConsoleMode(h_con, ctypes.byref(mode)):
167
+ kernel32.SetConsoleMode(h_con, mode.value | 0x0004 | 0x0008)
168
+ _VT100_ENABLED = True
169
+ kernel32.CloseHandle(h_con)
170
+ except Exception:
171
+ pass
172
+
173
+ # 3. Set Windows Console CodePage to UTF-8 (65001)
174
+ try:
175
+ kernel32.SetConsoleOutputCP(65001)
176
+ kernel32.SetConsoleCP(65001)
177
+ except Exception:
178
+ pass
179
+
180
+ return _VT100_ENABLED
181
+ except Exception:
182
+ return False
183
+
184
+
185
+ def supports_ansi(stream: Optional[TextIO] = None) -> bool:
186
+ """Determines whether the given stream supports ANSI escape sequences."""
187
+ target_stream = stream or sys.stdout
188
+
189
+ # Honor NO_COLOR standard (https://no-color.org)
190
+ if os.environ.get("NO_COLOR") is not None:
191
+ return False
192
+
193
+ # Force color if explicitly requested
194
+ if os.environ.get("FORCE_COLOR") in ("1", "true", "TRUE"):
195
+ return True
196
+
197
+ # If stdout is redirected / pipe, disable ANSI by default unless forced
198
+ is_tty = hasattr(target_stream, "isatty") and target_stream.isatty()
199
+ if not is_tty:
200
+ return False
201
+
202
+ if sys.platform.startswith("win"):
203
+ # Check for modern Windows terminals
204
+ if os.environ.get("WT_SESSION") or os.environ.get("VSCODE_PID"):
205
+ return True
206
+ if os.environ.get("TERM_PROGRAM") in ("vscode", "hyper", "warp", "mintty"):
207
+ return True
208
+ if os.environ.get("ConEmuANSI") == "ON" or "ANSICON" in os.environ:
209
+ return True
210
+ return _VT100_ENABLED
211
+
212
+ # Unix / Linux / macOS
213
+ term = os.environ.get("TERM", "")
214
+ if term == "dumb":
215
+ return False
216
+ return True
217
+
218
+
219
+ def supports_emojis() -> bool:
220
+ """Determines whether the active terminal can properly render SMP 4-byte emojis."""
221
+ if os.environ.get("TZERO_NO_EMOJI") in ("1", "true", "TRUE"):
222
+ return False
223
+
224
+ if sys.platform.startswith("win"):
225
+ # Windows Terminal, VS Code, Hyper, ConEmu have full SMP font fallbacks
226
+ if os.environ.get("WT_SESSION") or os.environ.get("VSCODE_PID"):
227
+ return True
228
+ if os.environ.get("TERM_PROGRAM") in ("vscode", "hyper", "warp", "mintty"):
229
+ return True
230
+ if os.environ.get("ConEmuANSI") == "ON":
231
+ return True
232
+ # Classic Windows cmd.exe / powershell.exe with standard fonts fails on SMP emojis
233
+ return False
234
+
235
+ # Unix/macOS: terminal encoding UTF-8 usually renders emojis fine
236
+ return True
237
+
238
+
239
+ def strip_ansi(text: str) -> str:
240
+ """Removes all ANSI escape codes from string."""
241
+ return ANSI_ESCAPE_RE.sub("", text)
242
+
243
+
244
+ def sanitize_terminal_text(
245
+ text: str,
246
+ allow_ansi: Optional[bool] = None,
247
+ allow_emojis: Optional[bool] = None,
248
+ ) -> str:
249
+ """Formats text for terminal display, falling back gracefully where unsupported."""
250
+ if not isinstance(text, str):
251
+ text = str(text)
252
+
253
+ check_ansi = supports_ansi() if allow_ansi is None else allow_ansi
254
+ if not check_ansi:
255
+ text = strip_ansi(text)
256
+
257
+ check_emojis = supports_emojis() if allow_emojis is None else allow_emojis
258
+ if not check_emojis:
259
+ # Replace known SMP emojis with clean BMP / ASCII representations
260
+ for emoji_char, fallback in SMP_EMOJI_FALLBACKS.items():
261
+ if emoji_char in text:
262
+ text = text.replace(emoji_char, fallback)
263
+ # Fall back any remaining SMP characters (above U+FFFF) to a clean bullet
264
+ text = SMP_CHAR_RE.sub("•", text)
265
+
266
+ return text
267
+
268
+
269
+ class TZeroTerminalStream(io.TextIOBase):
270
+ """Transparent TextIO proxy that filters ANSI sequences and SMP emojis on the fly."""
271
+
272
+ def __init__(self, wrapped_stream: TextIO, is_stderr: bool = False):
273
+ self._stream = wrapped_stream
274
+ self._is_stderr = is_stderr
275
+
276
+ def write(self, s: Any) -> int:
277
+ if not isinstance(s, str):
278
+ s = str(s)
279
+ clean_s = sanitize_terminal_text(s)
280
+ try:
281
+ return self._stream.write(clean_s)
282
+ except UnicodeEncodeError:
283
+ # Absolute fallback: encode with ascii replace
284
+ safe_ascii = clean_s.encode("ascii", errors="replace").decode("ascii")
285
+ return self._stream.write(safe_ascii)
286
+
287
+ def flush(self) -> None:
288
+ try:
289
+ self._stream.flush()
290
+ except Exception:
291
+ pass
292
+
293
+ def isatty(self) -> bool:
294
+ return hasattr(self._stream, "isatty") and self._stream.isatty()
295
+
296
+ def fileno(self) -> int:
297
+ return self._stream.fileno()
298
+
299
+ @property
300
+ def encoding(self) -> str:
301
+ return getattr(self._stream, "encoding", "utf-8") or "utf-8"
302
+
303
+ @property
304
+ def errors(self) -> str:
305
+ return getattr(self._stream, "errors", "replace") or "replace"
306
+
307
+ @property
308
+ def buffer(self) -> Any:
309
+ return getattr(self._stream, "buffer", self._stream)
310
+
311
+ def __getattr__(self, name: str) -> Any:
312
+ return getattr(self._stream, name)
313
+
314
+
315
+ def init_terminal(wrap_streams: bool = True) -> None:
316
+ """Initializes Windows VT100 mode and installs transparent terminal stream wrappers."""
317
+ global _INITIALIZED
318
+ if _INITIALIZED:
319
+ return
320
+
321
+ # Enable Windows VT100 Virtual Terminal Processing
322
+ if sys.platform.startswith("win"):
323
+ enable_windows_vt100()
324
+
325
+ # Reconfigure stdout/stderr with utf-8 if available
326
+ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
327
+ try:
328
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
329
+ except Exception:
330
+ pass
331
+ if sys.stderr and hasattr(sys.stderr, "reconfigure"):
332
+ try:
333
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
334
+ except Exception:
335
+ pass
336
+
337
+ # Wrap sys.stdout and sys.stderr with TZeroTerminalStream if requested
338
+ if wrap_streams:
339
+ # Check if running as JSON-RPC MCP server: don't alter stdout in MCP mode!
340
+ is_mcp = (
341
+ any("mcp" in a.lower() for a in sys.argv)
342
+ or os.environ.get("TZERO_MCP_ACTIVE") == "1"
343
+ )
344
+ if not is_mcp:
345
+ if sys.stdout and not isinstance(sys.stdout, TZeroTerminalStream):
346
+ sys.stdout = TZeroTerminalStream(sys.stdout, is_stderr=False) # type: ignore
347
+ if sys.stderr and not isinstance(sys.stderr, TZeroTerminalStream):
348
+ sys.stderr = TZeroTerminalStream(sys.stderr, is_stderr=True) # type: ignore
349
+
350
+ _INITIALIZED = True
351
+
352
+
353
+ def tzero_print(*args: Any, **kwargs: Any) -> None:
354
+ """Safe print helper that automatically formats text for the current terminal."""
355
+ file = kwargs.get("file", sys.stdout)
356
+ sep = kwargs.get("sep", " ")
357
+ end = kwargs.get("end", "\n")
358
+
359
+ text = sep.join(str(a) for a in args)
360
+ formatted = sanitize_terminal_text(text)
361
+ file.write(formatted + end)
362
+ file.flush()
363
+
364
+
365
+ # Auto-initialize terminal capabilities on module load
366
+ init_terminal(wrap_streams=True)