tokensafe 2.6.1 → 2.7.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.
Files changed (45) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +144 -91
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +66 -41
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +74 -47
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +653 -140
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +200 -60
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/skeletonizer.py +68 -13
  39. package/src/slicer.py +25 -7
  40. package/src/team_cache.py +10 -3
  41. package/src/telemetry_sync.py +110 -39
  42. package/src/tokenizer.py +24 -13
  43. package/src/treesitter_backend.py +539 -0
  44. package/src/version_checker.py +67 -32
  45. package/src/weekly_digest.py +6 -3
@@ -0,0 +1,539 @@
1
+ """
2
+ Optional Tree-sitter Backend for TokenSafe GraphEngine and Skeletonizer.
3
+
4
+ Strictly optional: all imports of `tree_sitter` and `tree_sitter_*` grammars are
5
+ lazy and fail-safe. When unavailable (or disabled via TOKENSAFE_TREESITTER=0),
6
+ callers fall back seamlessly to TokenSafe's zero-dependency stdlib AST/BraceLexer
7
+ engines.
8
+ """
9
+
10
+ import importlib
11
+ import os
12
+ import re
13
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
14
+
15
+ # Extension -> (module_name, loader_attr)
16
+ _LANGUAGE_SPECS: Dict[str, Tuple[str, str]] = {
17
+ ".py": ("tree_sitter_python", "language"),
18
+ ".js": ("tree_sitter_javascript", "language"),
19
+ ".jsx": ("tree_sitter_javascript", "language"),
20
+ ".mjs": ("tree_sitter_javascript", "language"),
21
+ ".cjs": ("tree_sitter_javascript", "language"),
22
+ ".ts": ("tree_sitter_typescript", "language_typescript"),
23
+ ".tsx": ("tree_sitter_typescript", "language_tsx"),
24
+ ".go": ("tree_sitter_go", "language"),
25
+ ".rs": ("tree_sitter_rust", "language"),
26
+ ".java": ("tree_sitter_java", "language"),
27
+ ".cs": ("tree_sitter_c_sharp", "language"),
28
+ ".c": ("tree_sitter_c", "language"),
29
+ ".h": ("tree_sitter_c", "language"),
30
+ ".cpp": ("tree_sitter_cpp", "language"),
31
+ ".cc": ("tree_sitter_cpp", "language"),
32
+ ".cxx": ("tree_sitter_cpp", "language"),
33
+ ".hpp": ("tree_sitter_cpp", "language"),
34
+ ".php": ("tree_sitter_php", "language_php"),
35
+ ".kt": ("tree_sitter_kotlin", "language"),
36
+ ".kts": ("tree_sitter_kotlin", "language"),
37
+ ".swift": ("tree_sitter_swift", "language"),
38
+ }
39
+
40
+ _CONTAINER_NODE_TYPES = {
41
+ "class_definition",
42
+ "class_declaration",
43
+ "class_specifier",
44
+ "struct_item",
45
+ "struct_specifier",
46
+ "struct_declaration",
47
+ "impl_item",
48
+ "trait_item",
49
+ "trait_declaration",
50
+ "interface_declaration",
51
+ "type_alias_declaration",
52
+ "record_declaration",
53
+ "enum_declaration",
54
+ "enum_item",
55
+ "protocol_declaration",
56
+ "extension_declaration",
57
+ "namespace_definition",
58
+ "namespace_declaration",
59
+ }
60
+
61
+ _FUNC_NODE_TYPES = {
62
+ "function_definition",
63
+ "function_declaration",
64
+ "function_item",
65
+ "method_definition",
66
+ "method_declaration",
67
+ "constructor_declaration",
68
+ "destructor_declaration",
69
+ "arrow_function",
70
+ "function_expression",
71
+ "function",
72
+ "operator_declaration",
73
+ "init_declaration",
74
+ "deinit_declaration",
75
+ "secondary_constructor",
76
+ "anonymous_function",
77
+ }
78
+
79
+ _IMPORT_NODE_TYPES = {
80
+ "import_statement",
81
+ "import_from_statement",
82
+ "import_declaration",
83
+ "use_declaration",
84
+ "using_directive",
85
+ "preproc_include",
86
+ "namespace_use_declaration",
87
+ "import",
88
+ }
89
+
90
+ _CALL_NODE_TYPES = {
91
+ "call",
92
+ "call_expression",
93
+ "method_invocation",
94
+ "invocation_expression",
95
+ "function_call_expression",
96
+ "member_call_expression",
97
+ "scoped_call_expression",
98
+ "macro_invocation",
99
+ "object_creation_expression",
100
+ "new_expression",
101
+ }
102
+
103
+ _SKIP_CALL_NAMES = {
104
+ "if", "for", "while", "switch", "catch", "return", "throw", "sizeof",
105
+ "typeof", "instanceof", "new", "delete", "await", "yield", "import",
106
+ "require", "print", "len", "str", "int", "float", "bool", "list",
107
+ "dict", "set", "tuple", "div", "span", "button", "input", "label",
108
+ "form", "svg", "path", "true", "false", "null", "undefined", "None",
109
+ "True", "False",
110
+ }
111
+
112
+
113
+ class TreeSitterBackend:
114
+ """Lazy, cached wrapper around optional `tree_sitter` language parsers."""
115
+
116
+ _ts_mod: Any = None
117
+ _ts_checked: bool = False
118
+ _parsers: Dict[str, Any] = {}
119
+ _unavailable_exts: Set[str] = set()
120
+
121
+ @classmethod
122
+ def is_enabled(cls) -> bool:
123
+ flag = os.environ.get("TOKENSAFE_TREESITTER", "auto").strip().lower()
124
+ return flag not in ("0", "false", "off", "no", "disabled")
125
+
126
+ @classmethod
127
+ def is_available(cls) -> bool:
128
+ if not cls.is_enabled():
129
+ return False
130
+ if not cls._ts_checked:
131
+ cls._ts_checked = True
132
+ try:
133
+ cls._ts_mod = importlib.import_module("tree_sitter")
134
+ except Exception:
135
+ cls._ts_mod = None
136
+ return cls._ts_mod is not None
137
+
138
+ @classmethod
139
+ def get_parser(cls, ext: str) -> Optional[Any]:
140
+ ext = ext.lower()
141
+ if not ext.startswith("."):
142
+ ext = f".{ext}" if ext else ""
143
+ if not cls.is_available() or ext not in _LANGUAGE_SPECS or ext in cls._unavailable_exts:
144
+ return None
145
+ if ext in cls._parsers:
146
+ return cls._parsers[ext]
147
+
148
+ mod_name, fn_name = _LANGUAGE_SPECS[ext]
149
+ try:
150
+ lang_mod = importlib.import_module(mod_name)
151
+ lang_ptr = getattr(lang_mod, fn_name)()
152
+ lang_obj = cls._ts_mod.Language(lang_ptr)
153
+ parser = cls._ts_mod.Parser(lang_obj)
154
+ cls._parsers[ext] = parser
155
+ return parser
156
+ except Exception:
157
+ cls._unavailable_exts.add(ext)
158
+ return None
159
+
160
+ @classmethod
161
+ def supports_ext(cls, ext: str) -> bool:
162
+ return cls.get_parser(ext) is not None
163
+
164
+ @classmethod
165
+ def supported_languages(cls) -> Set[str]:
166
+ if not cls.is_available():
167
+ return set()
168
+ return {ext for ext in _LANGUAGE_SPECS if cls.get_parser(ext) is not None}
169
+
170
+ @staticmethod
171
+ def _node_text(node: Any, code_bytes: bytes) -> str:
172
+ return code_bytes[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
173
+
174
+ @classmethod
175
+ def _find_identifier_in_declarator(cls, node: Any, code_bytes: bytes) -> Optional[str]:
176
+ if node is None:
177
+ return None
178
+ if node.type in (
179
+ "identifier", "type_identifier", "field_identifier",
180
+ "property_identifier", "simple_identifier", "name",
181
+ ):
182
+ return cls._node_text(node, code_bytes)
183
+ if node.type == "qualified_identifier":
184
+ # e.g. C++ ClassName::method -> take last identifier or full
185
+ parts = [cls._find_identifier_in_declarator(c, code_bytes) for c in node.children]
186
+ parts = [p for p in parts if p]
187
+ return parts[-1] if parts else None
188
+ if node.type in ("function_declarator", "pointer_declarator", "reference_declarator"):
189
+ decl = node.child_by_field_name("declarator")
190
+ if decl is not None:
191
+ res = cls._find_identifier_in_declarator(decl, code_bytes)
192
+ if res:
193
+ return res
194
+ for child in node.children:
195
+ if child.type in (
196
+ "identifier", "type_identifier", "field_identifier",
197
+ "property_identifier", "simple_identifier", "name",
198
+ "function_declarator", "qualified_identifier",
199
+ ):
200
+ res = cls._find_identifier_in_declarator(child, code_bytes)
201
+ if res:
202
+ return res
203
+ return None
204
+
205
+ @classmethod
206
+ def _extract_symbol_name(cls, node: Any, code_bytes: bytes) -> Optional[str]:
207
+ # Rust impl Foo / impl Trait for Foo
208
+ if node.type == "impl_item":
209
+ type_node = node.child_by_field_name("type")
210
+ if type_node is not None:
211
+ return cls._find_identifier_in_declarator(type_node, code_bytes)
212
+ for c in node.children:
213
+ if c.type in ("type_identifier", "generic_type"):
214
+ return cls._find_identifier_in_declarator(c, code_bytes)
215
+
216
+ # Go type_declaration -> type_spec
217
+ if node.type == "type_declaration":
218
+ for c in node.children:
219
+ if c.type == "type_spec":
220
+ name_n = c.child_by_field_name("name")
221
+ if name_n is not None:
222
+ return cls._node_text(name_n, code_bytes)
223
+
224
+ # Arrow/function assigned to variable_declarator: const Foo = (...) => {}
225
+ if node.type in ("arrow_function", "function_expression", "function"):
226
+ parent = node.parent
227
+ while parent is not None and parent.type in ("call_expression", "arguments", "parenthesized_expression"):
228
+ # Handle React.memo((...) => ...) or useCallback((...) => ...)
229
+ parent = parent.parent
230
+ if parent is not None and parent.type == "variable_declarator":
231
+ name_n = parent.child_by_field_name("name")
232
+ if name_n is not None:
233
+ return cls._node_text(name_n, code_bytes)
234
+ if parent is not None and parent.type == "pair":
235
+ key_n = parent.child_by_field_name("key")
236
+ if key_n is not None:
237
+ return cls._node_text(key_n, code_bytes).strip("\"'")
238
+
239
+ # Standard named field (`name`)
240
+ name_node = node.child_by_field_name("name")
241
+ if name_node is not None:
242
+ return cls._find_identifier_in_declarator(name_node, code_bytes)
243
+
244
+ # C/C++ declarator
245
+ decl_node = node.child_by_field_name("declarator")
246
+ if decl_node is not None:
247
+ return cls._find_identifier_in_declarator(decl_node, code_bytes)
248
+
249
+ # Fallback: first direct identifier/name child
250
+ for child in node.children:
251
+ if child.type in (
252
+ "identifier", "type_identifier", "field_identifier",
253
+ "property_identifier", "simple_identifier", "name",
254
+ ):
255
+ return cls._node_text(child, code_bytes)
256
+ return None
257
+
258
+ @classmethod
259
+ def _find_body_node(cls, node: Any) -> Optional[Any]:
260
+ body = node.child_by_field_name("body")
261
+ if body is not None:
262
+ return body
263
+ for child in node.children:
264
+ if child.type in (
265
+ "block", "statement_block", "compound_statement",
266
+ "function_body", "declaration_list",
267
+ ):
268
+ return child
269
+ return None
270
+
271
+ @classmethod
272
+ def _extract_call_name(cls, node: Any, code_bytes: bytes) -> Optional[str]:
273
+ if node.type == "method_invocation":
274
+ name_n = node.child_by_field_name("name")
275
+ if name_n is not None:
276
+ return cls._node_text(name_n, code_bytes)
277
+ if node.type == "member_call_expression":
278
+ name_n = node.child_by_field_name("name")
279
+ if name_n is not None:
280
+ return cls._node_text(name_n, code_bytes)
281
+
282
+ fn_node = node.child_by_field_name("function") or node.child_by_field_name("name")
283
+ if fn_node is None and node.children:
284
+ fn_node = node.children[0]
285
+ if fn_node is None:
286
+ return None
287
+
288
+ text = cls._node_text(fn_node, code_bytes).strip()
289
+ # Strip trailing generics/arguments and take leaf identifier after ., ::, ->
290
+ text = re.sub(r"<[^>]*>$", "", text)
291
+ leaf = re.split(r"(?:\.|::|->|\?\.)", text)[-1].strip()
292
+ if re.match(r"^[A-Za-z_$][A-Za-z0-9_$]*$", leaf) and leaf not in _SKIP_CALL_NAMES:
293
+ return leaf
294
+ return None
295
+
296
+ @classmethod
297
+ def _extract_imports_from_node(cls, node: Any, code_bytes: bytes, ext: str) -> Tuple[List[str], List[str]]:
298
+ mods: List[str] = []
299
+ syms: List[str] = []
300
+ raw = cls._node_text(node, code_bytes).strip()
301
+
302
+ if ext == ".py":
303
+ if node.type == "import_statement":
304
+ for c in node.children:
305
+ if c.type in ("dotted_name", "aliased_import"):
306
+ t = cls._node_text(c, code_bytes).split(" as ")[0].strip()
307
+ if t:
308
+ mods.append(t)
309
+ elif node.type == "import_from_statement":
310
+ m = re.match(r"^from\s+([A-Za-z0-9_.]+)\s+import\s+(.+)$", raw, re.DOTALL)
311
+ if m:
312
+ mods.append(m.group(1).strip())
313
+ for item in m.group(2).replace("(", "").replace(")", "").split(","):
314
+ sym = item.strip().split(" as ")[0].strip()
315
+ if sym and sym != "*":
316
+ syms.append(sym)
317
+ elif ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
318
+ for m in re.finditer(r"""['"]([^'"]+)['"]""", raw):
319
+ mods.append(m.group(1))
320
+ m_named = re.search(r"\{([^}]+)\}", raw)
321
+ if m_named:
322
+ for item in m_named.group(1).split(","):
323
+ s = item.strip().split(" as ")[0].strip()
324
+ if s:
325
+ syms.append(s)
326
+ elif ext == ".go":
327
+ for m in re.finditer(r'"([^"]+)"', raw):
328
+ mods.append(m.group(1))
329
+ elif ext in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp"):
330
+ m = re.search(r'[<"]([^>"]+)[>"]', raw)
331
+ if m:
332
+ mods.append(m.group(1))
333
+ else:
334
+ # Rust use, Java/Kotlin import, C# using, PHP use, Swift import
335
+ cleaned = re.sub(r"^(?:pub\s+)?(?:use|import|using|namespace)\s+", "", raw)
336
+ cleaned = cleaned.rstrip(";").strip()
337
+ if cleaned:
338
+ mods.append(cleaned)
339
+ return mods, syms
340
+
341
+ @classmethod
342
+ def extract_graph_data(cls, code: str, ext: str, rel_path: str) -> Optional[Dict[str, Any]]:
343
+ parser = cls.get_parser(ext)
344
+ if parser is None:
345
+ return None
346
+
347
+ code_bytes = code.encode("utf-8", errors="replace")
348
+ try:
349
+ tree = parser.parse(code_bytes)
350
+ except Exception:
351
+ return None
352
+
353
+ lines = code.splitlines()
354
+ imports: List[str] = []
355
+ imported_symbols: List[str] = []
356
+ symbols: List[Dict[str, Any]] = []
357
+ seen_keys: Set[str] = set()
358
+ calls: List[Tuple[str, str]] = []
359
+
360
+ def walk(node: Any, container_stack: List[str], current_fn_key: Optional[str]):
361
+ ntype = node.type
362
+
363
+ if ntype in _IMPORT_NODE_TYPES:
364
+ mods, syms = cls._extract_imports_from_node(node, code_bytes, ext)
365
+ imports.extend(mods)
366
+ imported_symbols.extend(syms)
367
+ return
368
+
369
+ # Go `type Foo struct { ... }` / `type Foo interface { ... }`
370
+ is_go_type = (
371
+ ext == ".go"
372
+ and ntype == "type_declaration"
373
+ and any(c.type == "type_spec" for c in node.children)
374
+ )
375
+
376
+ if ntype in _CONTAINER_NODE_TYPES or is_go_type:
377
+ name = cls._extract_symbol_name(node, code_bytes)
378
+ if name:
379
+ qual = "::".join(container_stack + [name]) if container_stack else name
380
+ sym_key = f"{rel_path}::{qual}"
381
+ if sym_key not in seen_keys:
382
+ seen_keys.add(sym_key)
383
+ l_start = node.start_point[0] + 1
384
+ l_end = max(l_start, node.end_point[0] + 1)
385
+ sig = lines[l_start - 1].strip() if 0 < l_start <= len(lines) else name
386
+ symbols.append({
387
+ "sym_key": sym_key,
388
+ "name": name,
389
+ "qualified_name": qual,
390
+ "kind": "class",
391
+ "line_start": l_start,
392
+ "line_end": l_end,
393
+ "signature": sig,
394
+ })
395
+ next_stack = container_stack + [name]
396
+ else:
397
+ next_stack = container_stack
398
+
399
+ for child in node.children:
400
+ walk(child, next_stack, current_fn_key)
401
+ return
402
+
403
+ if ntype in _FUNC_NODE_TYPES:
404
+ name = cls._extract_symbol_name(node, code_bytes)
405
+ next_fn_key = current_fn_key
406
+ if name:
407
+ qual = "::".join(container_stack + [name]) if container_stack else name
408
+ sym_key = f"{rel_path}::{qual}"
409
+ if sym_key not in seen_keys:
410
+ seen_keys.add(sym_key)
411
+ l_start = node.start_point[0] + 1
412
+ l_end = max(l_start, node.end_point[0] + 1)
413
+ # Use the variable declaration line for arrow functions if applicable
414
+ sig_line = l_start
415
+ if ntype in ("arrow_function", "function_expression") and node.parent is not None:
416
+ sig_line = min(l_start, node.parent.start_point[0] + 1)
417
+ sig = lines[sig_line - 1].strip() if 0 < sig_line <= len(lines) else name
418
+ symbols.append({
419
+ "sym_key": sym_key,
420
+ "name": name,
421
+ "qualified_name": qual,
422
+ "kind": "function",
423
+ "line_start": l_start,
424
+ "line_end": l_end,
425
+ "signature": sig,
426
+ })
427
+ next_fn_key = sym_key
428
+
429
+ for child in node.children:
430
+ walk(child, container_stack, next_fn_key)
431
+ return
432
+
433
+ if ntype in _CALL_NODE_TYPES and current_fn_key:
434
+ callee = cls._extract_call_name(node, code_bytes)
435
+ if callee:
436
+ calls.append((current_fn_key, callee))
437
+
438
+ for child in node.children:
439
+ walk(child, container_stack, current_fn_key)
440
+
441
+ walk(tree.root_node, [], None)
442
+ return {
443
+ "imports": imports,
444
+ "imported_symbols": imported_symbols,
445
+ "symbols": symbols,
446
+ "calls": calls,
447
+ }
448
+
449
+ @classmethod
450
+ def skeletonize_braces(
451
+ cls,
452
+ code: str,
453
+ ext: str,
454
+ keep_symbols: Optional[Set[str]] = None,
455
+ ) -> Optional[str]:
456
+ """
457
+ Tree-sitter brace-language skeletonizer: replaces non-kept function/method
458
+ bodies with `{ /* ... */ }` while preserving multi-line signatures,
459
+ Allman-style braces, classes/structs/impls, and control-flow blocks.
460
+ """
461
+ ext = ext.lower()
462
+ if not ext.startswith("."):
463
+ ext = f".{ext}" if ext else ""
464
+ if ext == ".py":
465
+ return None
466
+ parser = cls.get_parser(ext)
467
+ if parser is None:
468
+ return None
469
+
470
+ code_bytes = code.encode("utf-8", errors="replace")
471
+ try:
472
+ tree = parser.parse(code_bytes)
473
+ except Exception:
474
+ return None
475
+
476
+ replacements: List[Tuple[int, int, bytes]] = []
477
+ comment_token = "# ..." if ext == ".py" else "/* ... */"
478
+ folded_body = f"{{ {comment_token} }}".encode("utf-8")
479
+
480
+ def walk(node: Any, container_stack: List[str], in_kept_scope: bool = False):
481
+ ntype = node.type
482
+
483
+ if ntype in _CONTAINER_NODE_TYPES:
484
+ cname = cls._extract_symbol_name(node, code_bytes)
485
+ next_stack = container_stack + [cname] if cname else container_stack
486
+ for child in node.children:
487
+ walk(child, next_stack, in_kept_scope)
488
+ return
489
+
490
+ if ntype in _FUNC_NODE_TYPES:
491
+ name = cls._extract_symbol_name(node, code_bytes)
492
+ qual_dot = ".".join(container_stack + [name]) if (container_stack and name) else name
493
+ qual_col = "::".join(container_stack + [name]) if (container_stack and name) else name
494
+ body = cls._find_body_node(node)
495
+ is_target_kept = (
496
+ keep_symbols is not None
497
+ and (
498
+ (name and name in keep_symbols)
499
+ or (qual_dot and qual_dot in keep_symbols)
500
+ or (qual_col and qual_col in keep_symbols)
501
+ )
502
+ )
503
+ if body is not None:
504
+ body_bytes = code_bytes[body.start_byte:body.end_byte]
505
+ if body_bytes.startswith(b"{") and body_bytes.endswith(b"}"):
506
+ if is_target_kept:
507
+ for child in node.children:
508
+ walk(child, container_stack, True)
509
+ return
510
+ # Inside a kept function, leave unnamed inline callbacks intact
511
+ if in_kept_scope and not name:
512
+ for child in node.children:
513
+ walk(child, container_stack, True)
514
+ return
515
+ replacements.append((body.start_byte, body.end_byte, folded_body))
516
+ return
517
+ for child in node.children:
518
+ walk(child, container_stack, in_kept_scope or is_target_kept)
519
+ return
520
+
521
+ for child in node.children:
522
+ walk(child, container_stack, in_kept_scope)
523
+
524
+ walk(tree.root_node, [], False)
525
+ if not replacements:
526
+ return code
527
+
528
+ # Sort and deduplicate non-overlapping spans
529
+ replacements.sort(key=lambda r: (r[0], -r[1]))
530
+ out_parts: List[bytes] = []
531
+ cursor = 0
532
+ for start, end, rep in replacements:
533
+ if start < cursor:
534
+ continue
535
+ out_parts.append(code_bytes[cursor:start])
536
+ out_parts.append(rep)
537
+ cursor = end
538
+ out_parts.append(code_bytes[cursor:])
539
+ return b"".join(out_parts).decode("utf-8", errors="replace")