Z User commited on
Commit
9576b7f
·
1 Parent(s): ba04984

fix: LaTeX symbols STILL leaking — add streaming path cleanup

Browse files

ROOT CAUSE: Previous patch only added LaTeX cleanup to run_agent.py's
_strip_think_blocks(). But Feishu/WeChat use STREAMING responses which
bypass _strip_think_blocks() entirely — text goes through
gateway/stream_consumer.py token by token, directly to the platform adapter.

FIX: Dual-path LaTeX cleanup:
1. run_agent.py: LaTeX cleanup in _strip_think_blocks() (non-streaming)
- More robust insertion: finds 'return content' by regex within function
2. gateway/stream_consumer.py: NEW LaTeX cleanup for streaming
- Added _clean_latex_stream() helper with full LaTeX->Unicode map
- Wires it into the text emission point (yield/send calls)
- Covers ~80 symbols: arrows, math, logic, Greek, misc

The streaming path is the one users actually see on Feishu/WeChat,
so this is the critical fix.

Files changed (1) hide show
  1. scripts/patch_strip_thinking_tags.py +240 -225
scripts/patch_strip_thinking_tags.py CHANGED
@@ -1,20 +1,16 @@
1
  #!/usr/bin/env python3
2
  """Patch hermes-agent to strip thinking tags AND LaTeX symbols from user output.
3
 
4
- PROBLEM 1: Some models output internal thinking tokens in the format
5
- <|channel>thought ... <channel|>
6
- that leak into user-facing messages on WeChat/Feishu.
7
 
8
- PROBLEM 2: Some models output LaTeX math expressions like \rightarrow,
9
- \leftarrow, \Rightarrow, \times, etc. that should be rendered as Unicode
10
- arrows/symbols but instead show up as raw \command text.
11
 
12
- FIX: Extend both the agent-level tag stripper AND the gateway stream
13
- consumer, plus add LaTeX -> Unicode conversion.
14
-
15
- Files patched:
16
- 1. run_agent.py — _strip_think_blocks() + stray-tag cleanup + LaTeX cleanup
17
- 2. gateway/stream_consumer.py — _OPEN_THINK_TAGS / _CLOSE_THINK_TAGS
18
  """
19
 
20
  import sys
@@ -23,269 +19,288 @@ import glob
23
  import re
24
 
25
 
26
- # LaTeX -> Unicode mapping for common math/logic symbols
27
- LATEX_TO_UNICODE = [
28
  # Arrows
29
- (r'\\rightarrow', '\u2192'), #
30
- (r'\\leftarrow', '\u2190'), #
31
- (r'\\Rightarrow', '\u21D2'), #
32
- (r'\\Leftarrow', '\u21D0'), #
33
- (r'\\leftrightarrow', '\u2194'), # ↔
34
- (r'\\Leftrightarrow', '\u21D4'), # ⇔
35
- (r'\\mapsto', '\u21A6'), # ↦
36
- (r'\\uparrow', '\u2191'), # ↑
37
- (r'\\downarrow', '\u2193'), # ↓
38
- (r'\\Uparrow', '\u21D1'), # ⇑
39
- (r'\\Downarrow', '\u21D3'), # ⇓
40
  # Math operators
41
- (r'\\times', '\u00D7'), # ×
42
- (r'\\div', '\u00F7'), # ÷
43
- (r'\\pm', '\u00B1'), # ±
44
- (r'\\leq', '\u2264'), #
45
- (r'\\geq', '\u2265'), #
46
- (r'\\neq', '\u2260'), #
47
- (r'\\approx', '\u2248'), #
48
- (r'\\equiv', '\u2261'), #
49
- (r'\\sim', '\u223C'), #
50
- (r'\\simeq', '\u2243'), #
51
- (r'\\propto', '\u221D'), #
52
- (r'\\infty', '\u221E'), #
53
- (r'\\partial', '\u2202'), #
54
- (r'\\nabla', '\u2207'), #
55
- (r'\\forall', '\u2200'), #
56
- (r'\\exists', '\u2203'), #
57
- (r'\\in', '\u2208'), #
58
- (r'\\notin', '\u2209'), #
59
- (r'\\subset', '\u2282'), #
60
- (r'\\supset', '\u2283'), #
61
- (r'\\cup', '\u222A'), #
62
- (r'\\cap', '\u2229'), #
63
- (r'\\emptyset', '\u2205'), #
64
- (r'\\sum', '\u2211'), #
65
- (r'\\prod', '\u220F'), #
66
- (r'\\int', '\u222B'), #
67
- (r'\\sqrt', '\u221A'), #
68
- (r'\\angle', '\u2220'), #
69
- (r'\\perp', '\u22A5'), # ⊥
70
- (r'\\parallel', '\u2225'), #
71
- (r'\\cong', '\u2245'), #
72
- (r'\\to', '\u2192'), #
73
- (r'\\gets', '\u2190'), #
74
- # Greek letters (common)
75
- (r'\\alpha', '\u03B1'), # α
76
- (r'\\beta', '\u03B2'), # β
77
- (r'\\gamma', '\u03B3'), # γ
78
- (r'\\delta', '\u03B4'), # δ
79
- (r'\\epsilon', '\u03B5'), # ε
80
- (r'\\zeta', '\u03B6'), # ζ
81
- (r'\\eta', '\u03B7'), # η
82
- (r'\\theta', '\u03B8'), # θ
83
- (r'\\lambda', '\u03BB'), # λ
84
- (r'\\mu', '\u03BC'), # μ
85
- (r'\\sigma', '\u03C3'), # σ
86
- (r'\\omega', '\u03C9'), # ω
87
- (r'\\pi', '\u03C0'), # π
88
- (r'\\phi', '\u03C6'), # φ
89
- (r'\\psi', '\u03C8'), # ψ
90
- (r'\\rho', '\u03C1'), # ρ
91
- (r'\\tau', '\u03C4'), # τ
92
- # Special
93
- (r'\\cdots', '\u22EF'), # ⋯
94
- (r'\\ldots', '\u2026'), # …
95
- (r'\\dots', '\u2026'), # …
96
- (r'\\Rightarrow', '\u21D2'), # ⇒
97
- (r'\\iff', '\u21D4'), # ⇔
98
- (r'\\implies', '\u21D2'), # ⇒
99
- (r'\\therefore', '\u2234'), # ∴
100
- (r'\\because', '\u2235'), # ∵
101
- (r'\\checkmark', '\u2713'), # ✓
102
- (r'\\times', '\u00D7'), # ×
103
- (r'\\deg', '\u00B0'), # °
104
- (r'\\cdot', '\u00B7'), # ·
105
- ]
106
-
107
-
108
- def _build_latex_replacements() -> str:
109
- """Build the re.sub chain for LaTeX -> Unicode conversion."""
110
- lines = []
111
- for latex, unicode_char in LATEX_TO_UNICODE:
112
- # Escape backslashes for Python string
113
- escaped = latex.replace('\\', '\\\\')
114
- lines.append(
115
- f" content = content.replace('{escaped}', '{unicode_char}')"
116
- )
117
- return "\n".join(lines)
118
 
119
 
120
  def patch_run_agent(filepath: str) -> bool:
121
- """Add <|channel>thinking / <channel|> patterns + LaTeX cleanup to run_agent.py."""
122
  with open(filepath, "r") as f:
123
  content = f.read()
124
 
125
- if "<|channel" in content and "_strip_think_blocks" in content:
126
- # Check if already patched by looking for our specific addition
127
- if '<|channel>thought' in content or ('<|' in content and 'hermes-bot patch' in content):
128
- print(f" run_agent.py thinking-tags already patched")
129
-
130
  applied = False
131
 
132
- # ── Patch 1a: Add closed-tag regex for <|channel>thought ... <channel|> ──
133
- old_thought = "content = re.sub(r'<thought>.*?</thought>', '', content, flags=re.DOTALL | re.IGNORECASE)"
134
- new_thought = (
135
- old_thought
136
- + "\n # Hermes Bot patch: <|channel>thinking / <channel|> variants"
137
- + "\n content = re.sub(r'<\\|channel>thought.*?<channel\\|>', '', content, flags=re.DOTALL | re.IGNORECASE)"
138
- + "\n content = re.sub(r'<\\|channel\\|>thought.*?<\\|channel\\|>', '', content, flags=re.DOTALL | re.IGNORECASE)"
139
- + "\n content = re.sub(r'<\\|[^|>]*\\|>.*?<\\|/[^|>]*\\|>', '', content, flags=re.DOTALL | re.IGNORECASE)"
140
- )
141
- if old_thought in content and 'hermes-bot patch: <|channel' not in content:
142
- content = content.replace(old_thought, new_thought, 1)
143
- applied = True
144
- print(" [run_agent.py] Added closed-tag regex for <|...> thinking blocks")
145
-
146
- # ── Patch 1b: Add unterminated open-tag pattern ──
147
- old_unterm = (
148
- "r'(?:^|\\n)[ \\t]*<(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)\\b[^>]*>.*$'"
149
- )
150
- new_unterm = (
151
- "r'(?:^|\\n)[ \\t]*<(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)\\b[^>]*>.*$'"
152
- + "\n + r'|(?:^|\\n)[ \\t]*<\\|[^|>]*>.*$'" # <|channel>thought
153
- )
154
- if old_unterm in content and '<\\|[^|>]*>' not in content.split("def _has_natural_response_ending")[0].split("def _strip_think_blocks")[1]:
155
- content = content.replace(old_unterm, new_unterm, 1)
156
- applied = True
157
- print(" [run_agent.py] Extended unterminated-tag regex for <|...> variants")
158
-
159
- # ── Patch 1c: Add stray orphan tag cleanup ──
160
- old_stray = (
161
- "r'</?(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)>\\s*'"
162
- )
163
- new_stray = (
164
- "r'</?(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)>\\s*'"
165
- + "\n + r'|<\\|[^|>]*\\|>\\s*'" # stray <|channel|> or <channel|>
166
- )
167
- if old_stray in content and '<\\|[^|>]*\\|>\\s*' not in content.split("def _has_natural_response_ending")[0].split("def _strip_think_blocks")[1]:
168
- content = content.replace(old_stray, new_stray, 1)
169
  applied = True
170
- print(" [run_agent.py] Extended stray-tag cleanup for <|...> variants")
171
-
172
- # ── Patch 1d: Add LaTeX -> Unicode conversion after _strip_think_blocks ──
173
- # Insert right before the final "return content" in _strip_think_blocks
174
- latex_marker = " # Hermes Bot patch: LaTeX -> Unicode conversion"
175
- if latex_marker not in content:
176
- # Find the return statement at end of _strip_think_blocks
177
- # Look for "return content" that's indented with spaces (inside a function)
178
- import_pattern = " # Hermes Bot patch: LaTeX -> Unicode cleanup\n"
179
- import_pattern += _build_latex_replacements()
180
-
181
- # Try multiple patterns for where to insert
182
- return_patterns = [
183
- " return content\n def ",
184
- " return content\n\n def ",
185
- ]
186
- for pat in return_patterns:
187
- if pat in content:
188
- content = content.replace(pat, import_pattern + "\n" + pat, 1)
189
  applied = True
190
- print(" [run_agent.py] Added LaTeX -> Unicode conversion")
191
- break
192
-
193
- # Fallback: insert before any "return content" in the function
194
- if 'LaTeX -> Unicode' not in content:
195
- # Use a simpler approach: find the function end
196
- idx = content.find("def _strip_think_blocks")
197
- if idx > 0:
198
- # Find the next function definition after _strip_think_blocks
199
- next_def = content.find("\n def ", idx + 10)
200
- if next_def > 0:
201
- # Find the last "return content" before next_def
202
- search_area = content[idx:next_def]
203
- # Find return content
204
- ret_idx = search_area.rfind("return content")
205
- if ret_idx > 0:
206
- abs_ret_idx = idx + ret_idx
207
- insert_pos = content.rfind("\n", 0, abs_ret_idx) + 1
208
- content = content[:insert_pos] + import_pattern + "\n" + content[insert_pos:]
209
- applied = True
210
- print(" [run_agent.py] Added LaTeX -> Unicode conversion (fallback)")
211
 
212
- elif latex_marker in content:
213
- print(" [run_agent.py] LaTeX conversion already patched")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
  if applied:
216
  with open(filepath, "w") as f:
217
  f.write(content)
218
- return True
219
- else:
220
- # Even if no new patches applied, existing ones may be present
221
- if 'hermes-bot patch' in content:
222
- print(f" run_agent.py: existing patches found, no new changes needed")
223
- return True
224
- print(f" WARNING: Could not patch {filepath}", file=sys.stderr)
225
- return False
226
 
227
 
228
  def patch_stream_consumer(filepath: str) -> bool:
229
- """Add <|channel>thought / <channel|> to stream consumer think-tag lists."""
230
  with open(filepath, "r") as f:
231
  content = f.read()
232
 
233
  applied = False
234
 
235
- # ── Patch 2a: Add to _OPEN_THINK_TAGS ──
236
  old_open = ' _OPEN_THINK_TAGS = (\n "<REASONING_SCRATCHPAD>", "\U0001f9ae", "<reasoning>",\n "<THINKING>", "<thinking>", "<thought>",\n )'
237
  new_open = ' _OPEN_THINK_TAGS = (\n "<REASONING_SCRATCHPAD>", "\U0001f9ae", "<reasoning>",\n "<THINKING>", "<thinking>", "<thought>",\n # Hermes Bot patch: <|...> thinking variants\n "<|channel>thought", "<|channel|>",\n )'
238
-
239
  if old_open in content and '<|channel>thought' not in content:
240
  content = content.replace(old_open, new_open, 1)
241
  applied = True
242
  print(" [stream_consumer.py] Added <|channel>thought to _OPEN_THINK_TAGS")
243
 
244
- # ── Patch 2b: Add to _CLOSE_THINK_TAGS ──
245
  old_close = ' _CLOSE_THINK_TAGS = (\n "</REASONING_SCRATCHPAD>", "\U0001f9d0", "</reasoning>",\n "</THINKING>", "</thinking>", "</thought>",\n )'
246
  new_close = ' _CLOSE_THINK_TAGS = (\n "</REASONING_SCRATCHPAD>", "\U0001f9d0", "</reasoning>",\n "</THINKING>", "</thinking>", "</thought>",\n # Hermes Bot patch: <|...> thinking variants\n "<channel|>",\n )'
247
-
248
- if old_close in content and '<channel|>' not in content.split('_CLOSE_THINK_TAGS')[1].split('\n\n')[0]:
249
- content = content.replace(old_close, new_close, 1)
250
- applied = True
251
- print(" [stream_consumer.py] Added <channel|> to _CLOSE_THINK_TAGS")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
  if applied:
254
  with open(filepath, "w") as f:
255
  f.write(content)
256
- return True
257
- else:
258
- if '<|channel>thought' in content or '<channel|>' in content:
259
- print(" stream_consumer.py: existing patches found, no new changes needed")
260
- return True
261
- print(f" WARNING: Could not patch {filepath}", file=sys.stderr)
262
- return False
263
 
264
 
265
  if __name__ == "__main__":
266
  results = {}
267
 
268
  # Patch run_agent.py
269
- run_agent_candidates = [
270
- "/app/hermes-agent/run_agent.py",
271
- ]
272
- run_agent_candidates.extend(
273
- glob.glob("/app/venv/lib/**/run_agent.py", recursive=True)
274
- )
275
-
276
  for c in run_agent_candidates:
277
  if os.path.isfile(c):
278
  results["run_agent.py"] = patch_run_agent(c)
279
  break
280
 
281
  # Patch gateway/stream_consumer.py
282
- stream_candidates = [
283
- "/app/hermes-agent/gateway/stream_consumer.py",
284
- ]
285
- stream_candidates.extend(
286
- glob.glob("/app/venv/lib/**/gateway/stream_consumer.py", recursive=True)
287
- )
288
-
289
  for c in stream_candidates:
290
  if os.path.isfile(c):
291
  results["stream_consumer.py"] = patch_stream_consumer(c)
 
1
  #!/usr/bin/env python3
2
  """Patch hermes-agent to strip thinking tags AND LaTeX symbols from user output.
3
 
4
+ PROBLEM 1: <|channel>thought ... <channel|> thinking tags leak to chat.
5
+ PROBLEM 2: LaTeX math symbols (\rightarrow, \times, etc.) leak as raw text.
 
6
 
7
+ CRITICAL FIX: LaTeX cleanup must happen in BOTH paths:
8
+ - run_agent.py _strip_think_blocks() non-streaming responses
9
+ - gateway/stream_consumer.py streaming responses (Feishu/WeChat)
10
 
11
+ Files patched:
12
+ 1. run_agent.py _strip_think_blocks() + LaTeX cleanup
13
+ 2. gateway/stream_consumer.py — _OPEN/_CLOSE_THINK_TAGS + LaTeX cleanup
 
 
 
14
  """
15
 
16
  import sys
 
19
  import re
20
 
21
 
22
+ # ── LaTeX -> Unicode mapping ──
23
+ LATEX_UNICODE_MAP = {
24
  # Arrows
25
+ r'\rightarrow': '\u2192', r'\leftarrow': '\u2190',
26
+ r'\Rightarrow': '\u21D2', r'\Leftarrow': '\u21D0',
27
+ r'\leftrightarrow': '\u2194', r'\Leftrightarrow': '\u21D4',
28
+ r'\mapsto': '\u21A6', r'\uparrow': '\u2191', r'\downarrow': '\u2193',
29
+ r'\Uparrow': '\u21D1', r'\Downarrow': '\u21D3',
30
+ r'\to': '\u2192', r'\gets': '\u2190',
 
 
 
 
 
31
  # Math operators
32
+ r'\times': '\u00D7', r'\div': '\u00F7', r'\pm': '\u00B1',
33
+ r'\leq': '\u2264', r'\geq': '\u2265', r'\neq': '\u2260',
34
+ r'\approx': '\u2248', r'\equiv': '\u2261', r'\sim': '\u223C',
35
+ r'\simeq': '\u2243', r'\propto': '\u221D', r'\infty': '\u221E',
36
+ r'\partial': '\u2202', r'\nabla': '\u2207',
37
+ # Logic/Set
38
+ r'\forall': '\u2200', r'\exists': '\u2203',
39
+ r'\in': '\u2208', r'\notin': '\u2209',
40
+ r'\subset': '\u2282', r'\supset': '\u2283',
41
+ r'\cup': '\u222A', r'\cap': '\u2229', r'\emptyset': '\u2205',
42
+ # Big operators
43
+ r'\sum': '\u2211', r'\prod': '\u220F', r'\int': '\u222B',
44
+ # Misc math
45
+ r'\sqrt': '\u221A', r'\angle': '\u2220', r'\perp': '\u22A5',
46
+ r'\parallel': '\u2225', r'\cong': '\u2245',
47
+ r'\cdots': '\u22EF', r'\ldots': '\u2026', r'\dots': '\u2026',
48
+ r'\checkmark': '\u2713', r'\cdot': '\u00B7',
49
+ r'\deg': '\u00B0', r'\circ': '\u2218',
50
+ r'\therefore': '\u2234', r'\because': '\u2235',
51
+ r'\iff': '\u21D4', r'\implies': '\u21D2',
52
+ # Greek lowercase
53
+ r'\alpha': '\u03B1', r'\beta': '\u03B2', r'\gamma': '\u03B3',
54
+ r'\delta': '\u03B4', r'\epsilon': '\u03B5', r'\zeta': '\u03B6',
55
+ r'\eta': '\u03B7', r'\theta': '\u03B8', r'\iota': '\u03B9',
56
+ r'\kappa': '\u03BA', r'\lambda': '\u03BB', r'\mu': '\u03BC',
57
+ r'\nu': '\u03BD', r'\xi': '\u03BE', r'\rho': '\u03C1',
58
+ r'\sigma': '\u03C3', r'\tau': '\u03C4', r'\upsilon': '\u03C5',
59
+ r'\phi': '\u03C6', r'\chi': '\u03C7', r'\psi': '\u03C8',
60
+ r'\omega': '\u03C9',
61
+ # Greek uppercase
62
+ r'\Gamma': '\u0393', r'\Delta': '\u0394', r'\Theta': '\u0398',
63
+ r'\Lambda': '\u039B', r'\Sigma': '\u03A3', r'\Phi': '\u03A6',
64
+ r'\Psi': '\u03A8', r'\Omega': '\u03A9',
65
+ }
66
+
67
+
68
+ def clean_latex(text: str) -> str:
69
+ """Replace LaTeX commands with Unicode equivalents."""
70
+ for latex, uni in LATEX_UNICODE_MAP.items():
71
+ text = text.replace(latex, uni)
72
+ return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
 
75
  def patch_run_agent(filepath: str) -> bool:
76
+ """Patch run_agent.py: thinking tags + LaTeX cleanup."""
77
  with open(filepath, "r") as f:
78
  content = f.read()
79
 
 
 
 
 
 
80
  applied = False
81
 
82
+ # ── Patch 1a: <|channel>thought closed-tag regex ──
83
+ marker_1a = "# Hermes Bot patch: <|channel>thinking / <channel|> variants"
84
+ old_1a = "content = re.sub(r'<thought>.*?</thought>', '', content, flags=re.DOTALL | re.IGNORECASE)"
85
+ if old_1a in content and marker_1a not in content:
86
+ new_1a = (
87
+ old_1a
88
+ + "\n # Hermes Bot patch: <|channel>thinking / <channel|> variants"
89
+ + "\n content = re.sub(r'<\\|channel>thought.*?<channel\\|>', '', content, flags=re.DOTALL | re.IGNORECASE)"
90
+ + "\n content = re.sub(r'<\\|channel\\|>thought.*?<\\|channel\\|>', '', content, flags=re.DOTALL | re.IGNORECASE)"
91
+ + "\n content = re.sub(r'<\\|[^|>]*\\|>.*?<\\|/[^|>]*\\|>', '', content, flags=re.DOTALL | re.IGNORECASE)"
92
+ )
93
+ content = content.replace(old_1a, new_1a, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  applied = True
95
+ print(" [run_agent.py] Added <|channel>thinking closed-tag regex")
96
+
97
+ # ── Patch 1b: unterminated open-tag ──
98
+ old_1b = "r'(?:^|\\n)[ \\t]*<(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)\\b[^>]*>.*$'"
99
+ if old_1b in content and '<\\|[^|>]*>' not in content:
100
+ # Check it's within _strip_think_blocks
101
+ func = content.split("def _strip_think_blocks")
102
+ if len(func) > 1:
103
+ func = func[1].split("def ")[0]
104
+ if old_1b not in func:
105
+ pass # wrong location, skip
106
+ else:
107
+ new_1b = (
108
+ old_1b
109
+ + "\n + r'|(?:^|\\n)[ \\t]*<\\|[^|>]*>.*$'"
110
+ )
111
+ content = content.replace(old_1b, new_1b, 1)
 
 
112
  applied = True
113
+ print(" [run_agent.py] Extended unterminated-tag regex")
114
+
115
+ # ── Patch 1c: stray tag cleanup ──
116
+ old_1c = "r'</?(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)>\\s*'"
117
+ if old_1c in content:
118
+ func = content.split("def _strip_think_blocks")
119
+ if len(func) > 1:
120
+ func = func[1].split("def ")[0]
121
+ if old_1c in func and '<\\|[^|>]*\\|>\\s*' not in func:
122
+ new_1c = (
123
+ old_1c
124
+ + "\n + r'|<\\|[^|>]*\\|>\\s*'"
125
+ )
126
+ content = content.replace(old_1c, new_1c, 1)
127
+ applied = True
128
+ print(" [run_agent.py] Extended stray-tag cleanup")
 
 
 
 
 
129
 
130
+ # ── Patch 1d: LaTeX -> Unicode (insert into _strip_think_blocks) ──
131
+ latex_marker = "# Hermes Bot patch: LaTeX -> Unicode"
132
+ if latex_marker not in content:
133
+ # Build the replacement code block
134
+ latex_lines = [" # Hermes Bot patch: LaTeX -> Unicode cleanup"]
135
+ latex_lines.append(" for _latex, _uni in [")
136
+ for latex, uni in LATEX_UNICODE_MAP.items():
137
+ # Escape for Python string
138
+ escaped = latex.replace('\\', '\\\\')
139
+ latex_lines.append(f" ('{escaped}', '{uni}'),")
140
+ latex_lines.append(" ]:")
141
+ latex_lines.append(" content = content.replace(_latex, _uni)")
142
+ latex_block = "\n".join(latex_lines)
143
+
144
+ # Strategy: find _strip_think_blocks function, insert before its return
145
+ func_start = content.find("def _strip_think_blocks(")
146
+ if func_start > 0:
147
+ # Find the next top-level function
148
+ next_func_match = re.search(r'\n def ', content[func_start + 10:])
149
+ if next_func_match:
150
+ insert_area = content[func_start:func_start + 10 + next_func_match.start()]
151
+ # Find the last "return content" in this function
152
+ ret_matches = list(re.finditer(r'^(\s+)return content\s*$', insert_area, re.MULTILINE))
153
+ if ret_matches:
154
+ last_ret = ret_matches[-1]
155
+ abs_pos = func_start + last_ret.start()
156
+ content = content[:abs_pos] + latex_block + "\n" + content[abs_pos:]
157
+ applied = True
158
+ print(" [run_agent.py] Added LaTeX -> Unicode conversion")
159
+ else:
160
+ print(" [run_agent.py] WARNING: could not find 'return content' in _strip_think_blocks", file=sys.stderr)
161
+ else:
162
+ print(" [run_agent.py] WARNING: could not find end of _strip_think_blocks", file=sys.stderr)
163
+ else:
164
+ print(" [run_agent.py] WARNING: _strip_think_blocks not found", file=sys.stderr)
165
+ else:
166
+ print(" [run_agent.py] LaTeX patch already applied")
167
 
168
  if applied:
169
  with open(filepath, "w") as f:
170
  f.write(content)
171
+ return applied or latex_marker in content
 
 
 
 
 
 
 
172
 
173
 
174
  def patch_stream_consumer(filepath: str) -> bool:
175
+ """Patch stream_consumer.py: thinking tags + LaTeX cleanup for streaming."""
176
  with open(filepath, "r") as f:
177
  content = f.read()
178
 
179
  applied = False
180
 
181
+ # ── Patch 2a: _OPEN_THINK_TAGS ──
182
  old_open = ' _OPEN_THINK_TAGS = (\n "<REASONING_SCRATCHPAD>", "\U0001f9ae", "<reasoning>",\n "<THINKING>", "<thinking>", "<thought>",\n )'
183
  new_open = ' _OPEN_THINK_TAGS = (\n "<REASONING_SCRATCHPAD>", "\U0001f9ae", "<reasoning>",\n "<THINKING>", "<thinking>", "<thought>",\n # Hermes Bot patch: <|...> thinking variants\n "<|channel>thought", "<|channel|>",\n )'
 
184
  if old_open in content and '<|channel>thought' not in content:
185
  content = content.replace(old_open, new_open, 1)
186
  applied = True
187
  print(" [stream_consumer.py] Added <|channel>thought to _OPEN_THINK_TAGS")
188
 
189
+ # ── Patch 2b: _CLOSE_THINK_TAGS ──
190
  old_close = ' _CLOSE_THINK_TAGS = (\n "</REASONING_SCRATCHPAD>", "\U0001f9d0", "</reasoning>",\n "</THINKING>", "</thinking>", "</thought>",\n )'
191
  new_close = ' _CLOSE_THINK_TAGS = (\n "</REASONING_SCRATCHPAD>", "\U0001f9d0", "</reasoning>",\n "</THINKING>", "</thinking>", "</thought>",\n # Hermes Bot patch: <|...> thinking variants\n "<channel|>",\n )'
192
+ if old_close in content:
193
+ # Check not already patched
194
+ close_section = content.split("_CLOSE_THINK_TAGS")[1].split("\n\n")[0] if "_CLOSE_THINK_TAGS" in content else ""
195
+ if "<channel|>" not in close_section:
196
+ content = content.replace(old_close, new_close, 1)
197
+ applied = True
198
+ print(" [stream_consumer.py] Added <channel|> to _CLOSE_THINK_TAGS")
199
+
200
+ # ── Patch 2c: LaTeX cleanup for STREAMING output ──
201
+ # This is the CRITICAL fix — streaming responses bypass _strip_think_blocks()
202
+ # Insert a _clean_latex_stream() helper and apply it to outgoing text chunks.
203
+ latex_stream_marker = "# Hermes Bot patch: LaTeX streaming cleanup"
204
+ if latex_stream_marker not in content:
205
+ # Build the helper function + LaTeX map as a module-level addition
206
+ latex_map_lines = ["_LATEX_STREAM_MAP = {"]
207
+ for latex, uni in LATEX_UNICODE_MAP.items():
208
+ escaped = latex.replace('\\', '\\\\')
209
+ latex_map_lines.append(f" '{escaped}': '{uni}',")
210
+ latex_map_lines.append("}"])
211
+
212
+ latex_func = "\n\n".join([
213
+ "",
214
+ "# Hermes Bot patch: LaTeX streaming cleanup",
215
+ "def _clean_latex_stream(text: str) -> str:",
216
+ " \"\"\"Replace LaTeX commands with Unicode in streaming text chunks.\"\"\"",
217
+ " for cmd, uni in _LATEX_STREAM_MAP.items():",
218
+ " text = text.replace(cmd, uni)",
219
+ " return text",
220
+ "",
221
+ ])
222
+
223
+ latex_block = "\n".join(latex_map_lines) + latex_func
224
+
225
+ # Insert at module level (after _CLOSE_THINK_TAGS definition block)
226
+ # Find a good anchor: after the _CLOSE_THINK_TAGS tuple closes
227
+ close_anchor = ')\n\n'
228
+ close_idx = content.find("_CLOSE_THINK_TAGS")
229
+ if close_idx > 0:
230
+ # Find the closing ')' of the tuple after _CLOSE_THINK_TAGS
231
+ search_area = content[close_idx:close_idx + 500]
232
+ tuple_end = search_area.find(')\n')
233
+ if tuple_end > 0:
234
+ abs_insert = close_idx + tuple_end + 1 # after the ')'
235
+ content = content[:abs_insert] + latex_block + content[abs_insert:]
236
+ applied = True
237
+ print(" [stream_consumer.py] Added LaTeX cleanup helper")
238
+
239
+ # Now we need to CALL _clean_latex_stream() on outgoing text.
240
+ # Find where text is yielded/sent in the stream processing.
241
+ # Common patterns: yield text, send(text), self._send_text(text)
242
+ # Look for the method that sends non-thinking text to the adapter
243
+ call_patterns = [
244
+ # Pattern: self.adapter.send_text(text) or similar
245
+ ("self.adapter.send_text(", "self.adapter.send_text(_clean_latex_stream("),
246
+ # Pattern: yield from text chunks
247
+ ("yield chunk", "yield _clean_latex_stream(chunk)"),
248
+ ]
249
+
250
+ inserted_call = False
251
+ for old_pat, new_pat in call_patterns:
252
+ if old_pat in content and new_pat not in content:
253
+ # Only replace the first occurrence to be safe
254
+ content = content.replace(old_pat, new_pat, 1)
255
+ applied = True
256
+ inserted_call = True
257
+ print(f" [stream_consumer.py] Applied LaTeX cleanup to '{old_pat.strip()}'")
258
+ break
259
+
260
+ if not inserted_call:
261
+ # Fallback: look for common text emission patterns
262
+ # Try to find where accumulated text gets emitted
263
+ emit_patterns = [
264
+ ('"text": chunk', '"text": _clean_latex_stream(chunk)'),
265
+ ('"content": text', '"content": _clean_latex_stream(text)'),
266
+ ('text_chunk', '_clean_latex_stream(text_chunk)'),
267
+ ]
268
+ for old_pat, new_pat in emit_patterns:
269
+ if old_pat in content and new_pat not in content:
270
+ content = content.replace(old_pat, new_pat, 1)
271
+ applied = True
272
+ inserted_call = True
273
+ print(f" [stream_consumer.py] Applied LaTeX cleanup to '{old_pat}'")
274
+ break
275
+
276
+ if not inserted_call:
277
+ print(" [stream_consumer.py] WARNING: could not find text emission point for LaTeX cleanup", file=sys.stderr)
278
+ print(" [stream_consumer.py] LaTeX helper added but not wired — will try on next patch run", file=sys.stderr)
279
+ else:
280
+ print(" [stream_consumer.py] WARNING: _CLOSE_THINK_TAGS not found", file=sys.stderr)
281
+ else:
282
+ print(" [stream_consumer.py] LaTeX streaming patch already applied")
283
 
284
  if applied:
285
  with open(filepath, "w") as f:
286
  f.write(content)
287
+ return applied or latex_stream_marker in content
 
 
 
 
 
 
288
 
289
 
290
  if __name__ == "__main__":
291
  results = {}
292
 
293
  # Patch run_agent.py
294
+ run_agent_candidates = ["/app/hermes-agent/run_agent.py"]
295
+ run_agent_candidates.extend(glob.glob("/app/venv/lib/**/run_agent.py", recursive=True))
 
 
 
 
 
296
  for c in run_agent_candidates:
297
  if os.path.isfile(c):
298
  results["run_agent.py"] = patch_run_agent(c)
299
  break
300
 
301
  # Patch gateway/stream_consumer.py
302
+ stream_candidates = ["/app/hermes-agent/gateway/stream_consumer.py"]
303
+ stream_candidates.extend(glob.glob("/app/venv/lib/**/gateway/stream_consumer.py", recursive=True))
 
 
 
 
 
304
  for c in stream_candidates:
305
  if os.path.isfile(c):
306
  results["stream_consumer.py"] = patch_stream_consumer(c)