Skip to content

The agent that grows with you

fix(bot-mode): DM protocol no longer shell-interpolates message bodies

Teknium1190825652e9
diff --git a/hermes_cli/_parser.py b/hermes_cli/_parser.py
index 88a0eb49f1e..b587ac10e02 100644
--- a/hermes_cli/_parser.py
+++ b/hermes_cli/_parser.py
@@ -303,6 +303,16 @@ def build_top_level_parser():
chat_parser.add_argument(
"-q", "--query", help="Single query (non-interactive mode)"
)
+ chat_parser.add_argument(
+ "--query-file",
+ metavar="PATH",
+ help=(
+ "Read the single query from a file instead of the command line "
+ "('-' reads stdin). Safe for arbitrary text: nothing is shell-"
+ "interpreted, so quotes, $(...), and backticks are preserved "
+ "verbatim. Mutually exclusive with -q."
+ ),
+ )
chat_parser.add_argument(
"--image", help="Optional local image path to attach to a single query"
)
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index bb0dc3fcd70..9ca5388c711 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -3179,6 +3179,29 @@ def cmd_chat(args):
# Import and run the CLI
from cli import main as cli_main
+ # --query-file: read the single query from a file (or stdin via '-') so
+ # callers never have to shell-quote message bodies. This is the transport
+ # the Bot Mode DM protocol uses — interpolating arbitrary text into a
+ # double-quoted shell argument truncates on quotes and executes $(...)
+ # (see tools/bot_mode_probe.py).
+ _qfile = getattr(args, "query_file", None)
+ if _qfile:
+ if args.query:
+ print("Error: -q/--query and --query-file are mutually exclusive", file=sys.stderr)
+ sys.exit(2)
+ try:
+ if _qfile == "-":
+ args.query = sys.stdin.read()
+ else:
+ with open(_qfile, "r", encoding="utf-8", errors="replace") as _fh:
+ args.query = _fh.read()
+ except OSError as _e:
+ print(f"Error: cannot read --query-file {_qfile}: {_e}", file=sys.stderr)
+ sys.exit(2)
+ if not (args.query or "").strip():
+ print(f"Error: --query-file {_qfile} is empty", file=sys.stderr)
+ sys.exit(2)
+
# Build kwargs from args
kwargs = {
"model": args.model,
diff --git a/tests/hermes_cli/test_chat_query_file.py b/tests/hermes_cli/test_chat_query_file.py
new file mode 100644
index 00000000000..469bd16e0ee
--- /dev/null
+++ b/tests/hermes_cli/test_chat_query_file.py
@@ -0,0 +1,78 @@
+"""--query-file: single-query text arrives verbatim, never shell-interpreted.
+
+Regression tests for the Bot Mode DM injection fix: the DM protocol used to
+tell agents to interpolate message bodies into a double-quoted shell command,
+so quotes truncated the message and $(...) executed on the sender's machine.
+The transport is now a file (--query-file) / stdin, and the protocol text
+must never regress to inlining the body into -q.
+"""
+
+import subprocess
+import sys
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[2]
+
+HOSTILE = 'hi "there" $(touch /tmp/pwned_by_dm_test) `id` \\ and a\nsecond line'
+
+
+def _parse(argv):
+ sys.path.insert(0, str(REPO))
+ try:
+ from hermes_cli._parser import build_top_level_parser
+
+ built = build_top_level_parser()
+ parser = built[0] if isinstance(built, tuple) else built
+ return parser.parse_args(argv)
+ finally:
+ sys.path.remove(str(REPO))
+
+
+def test_chat_parser_accepts_query_file():
+ args = _parse(["chat", "--query-file", "/tmp/x.txt"])
+ assert args.query_file == "/tmp/x.txt"
+ assert args.query is None
+
+
+def test_query_file_reads_hostile_text_verbatim(tmp_path, monkeypatch):
+ """The file body must reach args.query byte-identical — no shell pass."""
+ f = tmp_path / "dm.txt"
+ f.write_text(HOSTILE, encoding="utf-8")
+
+ # Exercise the exact resolution block in hermes_cli.main by simulating it:
+ # the block reads the file into args.query before dispatch.
+ args = _parse(["chat", "--query-file", str(f)])
+ assert args.query_file is not None
+ body = Path(args.query_file).read_text(encoding="utf-8")
+ assert body == HOSTILE
+ assert "$(touch" in body # preserved, not executed
+ assert not Path("/tmp/pwned_by_dm_test").exists()
+
+
+def test_query_and_query_file_mutually_exclusive(tmp_path):
+ f = tmp_path / "dm.txt"
+ f.write_text("hello", encoding="utf-8")
+ proc = subprocess.run(
+ [sys.executable, "-c",
+ "import sys; sys.path.insert(0, %r); "
+ "from hermes_cli.main import main; sys.argv=['hermes','chat','-q','x','--query-file',%r]; main()"
+ % (str(REPO), str(f))],
+ capture_output=True, text=True, timeout=120,
+ )
+ assert proc.returncode == 2
+ assert "mutually exclusive" in proc.stderr
+
+
+def test_bot_mode_protocol_never_inlines_message_into_shell():
+ """The DM protocol must use --query-file / stdin, not -q "…" inlining."""
+ sys.path.insert(0, str(REPO))
+ try:
+ import importlib
+
+ probe = importlib.import_module("tools.bot_mode_probe")
+ src = Path(probe.__file__).read_text(encoding="utf-8")
+ finally:
+ sys.path.remove(str(REPO))
+ assert "--query-file" in src
+ assert '-q "Message from' not in src
+ assert 'dm <peer>/<agent-name> "Message from' not in src
diff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.py
index 0ae74c5ff15..b8a588d9921 100644
--- a/tools/bot_mode_probe.py
+++ b/tools/bot_mode_probe.py
@@ -137,11 +137,12 @@ def _peer_paragraph(root: Path) -> str:
listed = ", ".join(f"`{p}`" for p in peers)
return (
"\n\nTeammates on OTHER machines: this install also has peer gateways "
- f"registered ({listed}). Message an agent on a peer the same way, via "
- "`hermes peer dm` (same terminal-tool pattern: background=true, "
- "notify_on_complete=true; the reply prints on stdout when it completes):\n"
+ f"registered ({listed}). Message an agent on a peer the same way — write "
+ "the message to a temp file first, then pipe it on stdin (same terminal-"
+ "tool pattern: background=true, notify_on_complete=true; the reply prints "
+ "on stdout when it completes):\n"
"```\n"
- 'hermes peer dm <peer>/<agent-name> "Message from 🤖 <you> (@<you>): your message"\n'
+ "hermes peer dm <peer>/<agent-name> < /tmp/dm.txt\n"
"```\n"
"Use `<peer>` alone for the peer's main agent. Run `hermes peer list` "
"for the live peer list."
@@ -168,13 +169,15 @@ def _build_section(home: Path) -> str:
return (
f"{_PROTOCOL_HEADING}\n"
"This install runs Bot Mode: each Hermes profile is an agent teammate with "
- 'one canonical "Bot Chat" conversation. To message a teammate, run on the '
- "terminal tool (background=true, notify_on_complete=true), then finish your "
+ 'one canonical "Bot Chat" conversation. To message a teammate: write the '
+ "message to a temp file with the file tool FIRST (never inline it into the "
+ "command — quotes truncate it and $( ) would execute), then run on the "
+ "terminal tool (background=true, notify_on_complete=true) and finish your "
"turn — the reply arrives later as a new message:\n"
"```\n"
- f'hermes -p <agent-name> chat --in ~ -c "Bot Chat" --create-if-missing -Q -q "Message from 🤖 {handle} (@{handle}): your message"\n'
+ f'hermes -p <agent-name> chat --in ~ -c "Bot Chat" --create-if-missing -Q --query-file /tmp/dm.txt\n'
"```\n"
- f'Always open with the "Message from 🤖 {handle} (@{handle}):" prefix so they '
+ f'The file must open with the "Message from 🤖 {handle} (@{handle}):" prefix so they '
"know who is talking. When YOU receive a message with that prefix, you are "
"being messaged by a teammate agent — address them (not the user) and reply "
"concisely. When the user says \"ask <name>\" or \"tell <name> ...\", that is a "