Skip to content

Windows: Hermes plugin decodes rtk output as ANSI (cp936), UnicodeDecodeError leaves stdout=None and silently disables rewriting for non-GBK commands #4525

Open

Description

@laolitongxue

Summary

The official Hermes plugin (hooks/hermes/__init__.py, installed via rtk init --agent hermes) calls subprocess.run(["rtk", "rewrite", command], capture_output=True, text=True) without an explicit encoding=. On Windows, text=True decodes the child's output with the ANSI code page (cp936/GBK on zh-CN systems) — but rtk rewrite emits UTF-8. Any command containing characters that don't round-trip through GBK (non-ASCII paths, curly quotes, emoji — i.e. most real-world commands on CJK Windows) makes the reader thread throw UnicodeDecodeError, so result.stdout is left as None, and the plugin then crashes on result.stdout.strip().

The exception is swallowed by the plugin's wide except, so the command fails open and runs unrewritten. No data is corrupted, but the plugin silently loses 100% of its rewriting benefit for those commands, plus emits one stderr noise line per call. The user sees nothing except "rtk gain never goes up".

Environment

  • rtk 0.50.0 (winget rtk-ai.rtk); same defect confirmed on 0.48.0
  • Windows 11, locale zh-CN (locale.getpreferredencoding() → cp936)
  • Python 3.14.7 / 3.13 (both affected); plugin as shipped by rtk init --agent hermes (upstream file, sha256 f687dcfd…, no local modification)

Minimal repro (outside the plugin, same call the plugin makes)

import subprocess, locale
print(locale.getpreferredencoding(False))   # cp936
r = subprocess.run(["rtk", "rewrite", "cat 中文测试.md"],
                   shell=False, capture_output=True, text=True, timeout=2)
print(r.returncode, repr(r.stdout))

Actual output:

cp936
Exception in thread Thread-1 (_readerthread):
Traceback (most recent call last):
  File "...\\Lib\\threading.py", line 1082, in _bootstrap_inner
    ...
  File "...\\Lib\\subprocess.py", line 1614, in _readerthread
    buffer.append(fh.read())
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 11: illegal multibyte sequence

3 None

Then inside the plugin (0.50 file, line 71): rewritten = result.stdout.strip() →

AttributeError: 'NoneType' object has no attribute 'strip'

→ caught by the plugin's except Exception → hook returns None → command runs as-is.

Note the NoneType error points at result.stdout, not result.stderr — on the rc=3 rewrite path the stderr.strip() line is never reached, so any fix limited to stderr does not help.

Suggested fix (3 lines, working locally since September)

RTK's output is always UTF-8 regardless of console code page, so decode it as UTF-8 and guard both streams:

result = subprocess.run(
    ["rtk", "rewrite", command],
    shell=False, timeout=2, capture_output=True, text=True,
    encoding="utf-8", errors="replace",      # RTK emits UTF-8; Windows otherwise decodes as cp936
)
...
rewritten = (result.stdout or "").strip()
...
stderr = (result.stderr or "").strip()

Verified on this machine after the patch: rtk rewrite "cat 中文测试.md" → rc=3, stdout = 'rtk read 中文测试.md', rewrite chain end-to-end confirmed via rtk gain counters.

Happy to send a PR if you'll take one — the same one-line encoding= consideration may apply to the other hook adapters that capture subprocess output on Windows.

Activity

  1. added
    bug
    good first issue
    help wanted
    on Oct 12, 2026
  2. rtk-wshm-sync-bot commented on Oct 12, 2026

    @rtk-wshm-sync-bot

    wshm · Automated triage by AI

    🔍 Automated Triage

    🐛 Category bug
    🟠 Priority high
    🎯 Confidence 95%

    Summary

    Hermes plugin's subprocess.run uses text=True without encoding=utf-8 on Windows, so non-GBK output triggers UnicodeDecodeError, leaving stdout=None and silently disabling rewriting.

    This looks like a simple fix that could be auto-resolved. Repo maintainers can use /wshm fix to attempt it.

    📁 Relevant files
    • hooks/hermes/__init__.py

    Suggested Actions

    1. Apply the reporter's 3-line patch: add encoding="utf-8", errors="replace" and guard stdout/stderr with or ""
    2. Accept the offered PR from laolitongxue for hooks/hermes/init.py
    3. Audit other hook adapters (OpenCode, Copilot, etc.) for the same missing encoding= on Windows subprocess calls
    4. Check relation to prior Windows encoding bug Windows Encoding Bug: RTK Decodes GBK Output as UTF-8 #2452 for shared root cause

    Triaged automatically by wshm · This is an automated analysis, not a human review.

  3. laolitongxue commented on Nov 23, 2026

    @laolitongxue
    Author

    Still reproduces on every current ref — could this be fixed upstream?

    ref hooks/hermes/rtk-rewrite/__init__.py
    v1.2.1 (latest stable, 2026-11-19) 3059 B, sha256 0b39e5a4…
    develop HEAD same
    dev-1.2.2-rc.670 same

    subprocess.run(..., text=True) still passes no encoding=, so on a zh-CN Windows (ANSI codepage 936) Python decodes rtk's UTF-8 stdout as GBK. Two silent outcomes:

    1. The mangled rewrite is applied anyway. When the bytes happen to be valid GBK, the corrupted command is still handed to the agent:

    ls 文档                        ->  rtk ls 鏂囨。
    cat C:\…\文档\a.md             ->  rtk read C:\…\鏂囨。\a.md
    

    rtk rewrite still exits 0/3, so nothing is reported. The command then fails with "file not found", or — if the mangled name happens to exist — operates on the wrong path.

    2. Fail-open. When the bytes are not valid GBK: UnicodeDecodeError in the reader thread → stdout is None → result.stdout.strip() raises AttributeError → the wide except swallows it and no rewrite happens. Observed as rtk: hermes plugin warning: 'NoneType' object has no attribute 'strip' and a flat rtk gain.

    Either way, on a zh-CN machine any command with non-ASCII paths loses the savings silently, and a subset gets corrupted.

    The fix is three lines and is already proposed in #4527 (which now shows as conflicting):

                     text=True,
    +                encoding="utf-8",
    +                errors="replace",
     ...
    -                stderr = result.stderr.strip()
    +                stderr = (result.stderr or "").strip()
    -        rewritten = result.stdout.strip()
    +        rewritten = (result.stdout or "").strip()

    The or "" guards are needed even after the encoding fix: stdout / stderr can still be None when the reader thread dies, and the plugin otherwise raises a second error while trying to report the first.

    Repro without Hermes (run under a cp936 interpreter, e.g. PYTHONUTF8=0):

    import importlib.util
    spec = importlib.util.spec_from_file_location("p", r"<HERMES_HOME>\plugins\rtk-rewrite\__init__.py")
    mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
    args = {"command": "ls 文档"}
    mod._pre_tool_call(tool_name="terminal", args=args)
    print(args)   # official: {'command': 'rtk ls 鏂囨。'}   fixed: {'command': 'rtk ls 文档'}

    Happy to open a rebased PR against develop with those three lines plus the two tests from #4527, if that is easier than reviving #4527.

    Environment: rtk 1.2.1, Windows 11 zh-CN (codepage 936), Python 3.14 as bundled with Hermes.

  4. acalexanderac commented on Nov 24, 2026

    @acalexanderac

    I can work on this one
    let's take a look

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:clibuggood first issuehelp wantedplatform:windowspriority:high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions