2026-09-02 19:13:55 -07:00
|
|
|
"""Shared SKILL.md preprocessing helpers: ``${HERMES_*}`` template tokens and
|
|
|
|
|
inline ``!`cmd``` shell expansion."""
|
2026-04-24 12:59:28 -06:00
|
|
|
|
2026-10-09 14:34:51 -07:00
|
|
|
import json
|
2026-04-24 12:59:28 -06:00
|
|
|
import logging
|
|
|
|
|
import re
|
|
|
|
|
import subprocess
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
fix(agent): route every model-visible elision through the non-imitable compression marker (#121548)
The #83714 fix hardened only the tool-call args renderer; five other
renderers (plus three same-idiom siblings) still composed the bare
truncation marker, which the model imitated from replayed context into
new durable writes (#83435).
This routes all model-visible elision in agent/ through shared helpers
in agent/compression_marker.py:
- elide(text, limit): head + marker cap with accurate omitted/total counts
- elide_middle(text, head, tail): kept head/tail with the middle elided
The elision marker's first sentence is byte-identical to the args marker's,
so the existing _COMPRESSION_MARKER_RE (and the dispatch-boundary guard in
tool_dispatch_helpers) rejects a copied marker regardless of which renderer
leaked it; only the tool-call-specific second sentence is dropped so the
marker still fits small caps (the clarify summary cap is 199 chars).
Routed sites:
- context_compressor.py: static-fallback turn renderer, _sum_clarify(),
summarizer prompt builder (middle elision), active-task snapshot,
lean user-message quotes (2 sites)
- skill_preprocessing.py: inline-shell output embedded into skill bodies
- lsp/reporter.py: truncate() for <diagnostics> tool output
- verification_stop.py: verify-on-stop nudge output summary
Regression test asserts the imitable idiom appears nowhere in agent/
strings (comments excluded), so a new open-coded renderer cannot land
silently.
Fixes #121548
(cherry picked from commit 69c63d50b4ababedf4fb4ff88c08f5d1e144a79f)
2026-09-24 20:38:25 +07:00
|
|
|
from agent.compression_marker import elide
|
fix(windows): hide console-window flash on backend git/gh/wmic/bash subprocess spawns
The Windows desktop GUI runs its backend headless via pythonw.exe. Several
auxiliary subprocess sites that run inside that windowless backend spawned
console-subsystem children (git, gh, wmic, powershell, bash, rg, taskkill)
WITHOUT CREATE_NO_WINDOW, so Windows allocated a fresh conhost per call and
flashed a black window on screen — sometimes continuously (the dashboard
Projects-tree git probe alone fired ~118 spawns in 60s on startup).
The terminal tool, cron, browser, code_execution, and gateway-spawn paths
already carry windows_hide_flags(); these auxiliary probe/scan/launcher legs
were missed. Wire the existing helper into them:
- tui_gateway/git_probe.py: run_git (+ encoding=utf-8/errors=replace, fixes the
cp950 UnicodeDecodeError on CJK paths from the same site)
- agent/coding_context.py: _git (per-turn git status/log/diff)
- agent/context_references.py: _run_git + _rg_files (@file/@ref resolution)
- hermes_cli/copilot_auth.py: gh auth token probe (auxiliary provider:auto)
- hermes_cli/gateway.py: wmic + PowerShell Get-CimInstance PID scan
- hermes_cli/main.py: wmic stale-dashboard PID scan
- gateway/status.py: taskkill /T /F force-kill
windows_hide_flags() returns 0 on POSIX, so every changed call is a no-op on
Linux/macOS (verified: real git/rg probes still work; Windows-simulated calls
all pass creationflags=CREATE_NO_WINDOW).
Scoped to the windowless-backend paths that cause the reported flashing. The
Electron updater-handoff leg (main.cjs windowsHide:false) and the
interactive-CLI banner probes (cli.py) are intentionally NOT touched here —
the former needs a Windows-tested change of its own, the latter runs in a
visible console anyway.
Tracking: #54220
Refs: #53178 #53631 #53781 #53957 #49602 #52982 #53424 #53053 #53016
2026-06-28 05:01:59 -07:00
|
|
|
from hermes_cli._subprocess_compat import IS_WINDOWS, windows_hide_flags
|
|
|
|
|
|
2026-04-24 12:59:28 -06:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-09-02 19:13:55 -07:00
|
|
|
# ${HERMES_SKILL_DIR} / ${HERMES_SESSION_ID} tokens. Unresolvable ones (e.g. no
|
|
|
|
|
# session) are left as-is so the author can spot them.
|
2026-04-24 12:59:28 -06:00
|
|
|
_SKILL_TEMPLATE_RE = re.compile(r"\$\{(HERMES_SKILL_DIR|HERMES_SESSION_ID)\}")
|
2026-09-02 19:13:55 -07:00
|
|
|
# Inline shell snippets like !`date +%Y-%m-%d` — single-line only.
|
2026-04-24 12:59:28 -06:00
|
|
|
_INLINE_SHELL_RE = re.compile(r"!`([^`\n]+)`")
|
|
|
|
|
# Cap inline-shell output so a runaway command can't blow out the context.
|
|
|
|
|
_INLINE_SHELL_MAX_OUTPUT = 4000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_skills_config() -> dict:
|
|
|
|
|
"""Load the ``skills`` section of config.yaml (best-effort)."""
|
|
|
|
|
try:
|
2026-07-29 11:55:29 -07:00
|
|
|
from hermes_cli.config import load_config_readonly
|
2026-09-02 19:13:55 -07:00
|
|
|
skills_cfg = (load_config_readonly() or {}).get("skills")
|
2026-04-24 12:59:28 -06:00
|
|
|
if isinstance(skills_cfg, dict):
|
|
|
|
|
return skills_cfg
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.debug("Could not read skills config", exc_info=True)
|
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
|
|
2026-09-02 19:13:55 -07:00
|
|
|
def substitute_template_vars(content: str, skill_dir: Path | None, session_id: str | None) -> str:
|
|
|
|
|
"""Replace ${HERMES_SKILL_DIR} / ${HERMES_SESSION_ID}; tokens without a value stay in place."""
|
2026-04-24 12:59:28 -06:00
|
|
|
if not content:
|
|
|
|
|
return content
|
2026-09-02 19:13:55 -07:00
|
|
|
values = {
|
|
|
|
|
"HERMES_SKILL_DIR": str(skill_dir) if skill_dir else None,
|
|
|
|
|
"HERMES_SESSION_ID": str(session_id) if session_id else None,
|
|
|
|
|
}
|
|
|
|
|
return _SKILL_TEMPLATE_RE.sub(lambda m: values[m.group(1)] or m.group(0), content)
|
2026-04-24 12:59:28 -06:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def run_inline_shell(command: str, cwd: Path | None, timeout: int) -> str:
|
2026-09-02 19:13:55 -07:00
|
|
|
"""Run one inline-shell snippet and return its stdout (trimmed; stderr when
|
|
|
|
|
stdout is empty). Failures return an ``[inline-shell ...]`` marker instead
|
|
|
|
|
of raising, so one bad snippet can't wreck the whole skill message."""
|
fix(windows): hide console-window flash on backend git/gh/wmic/bash subprocess spawns
The Windows desktop GUI runs its backend headless via pythonw.exe. Several
auxiliary subprocess sites that run inside that windowless backend spawned
console-subsystem children (git, gh, wmic, powershell, bash, rg, taskkill)
WITHOUT CREATE_NO_WINDOW, so Windows allocated a fresh conhost per call and
flashed a black window on screen — sometimes continuously (the dashboard
Projects-tree git probe alone fired ~118 spawns in 60s on startup).
The terminal tool, cron, browser, code_execution, and gateway-spawn paths
already carry windows_hide_flags(); these auxiliary probe/scan/launcher legs
were missed. Wire the existing helper into them:
- tui_gateway/git_probe.py: run_git (+ encoding=utf-8/errors=replace, fixes the
cp950 UnicodeDecodeError on CJK paths from the same site)
- agent/coding_context.py: _git (per-turn git status/log/diff)
- agent/context_references.py: _run_git + _rg_files (@file/@ref resolution)
- hermes_cli/copilot_auth.py: gh auth token probe (auxiliary provider:auto)
- hermes_cli/gateway.py: wmic + PowerShell Get-CimInstance PID scan
- hermes_cli/main.py: wmic stale-dashboard PID scan
- gateway/status.py: taskkill /T /F force-kill
windows_hide_flags() returns 0 on POSIX, so every changed call is a no-op on
Linux/macOS (verified: real git/rg probes still work; Windows-simulated calls
all pass creationflags=CREATE_NO_WINDOW).
Scoped to the windowless-backend paths that cause the reported flashing. The
Electron updater-handoff leg (main.cjs windowsHide:false) and the
interactive-CLI banner probes (cli.py) are intentionally NOT touched here —
the former needs a Windows-tested change of its own, the latter runs in a
visible console anyway.
Tracking: #54220
Refs: #53178 #53631 #53781 #53957 #49602 #52982 #53424 #53053 #53016
2026-06-28 05:01:59 -07:00
|
|
|
_popen_kwargs = {"creationflags": windows_hide_flags()} if IS_WINDOWS else {}
|
2026-09-07 03:26:32 -07:00
|
|
|
from agent.delegation_context import delegated_child_subprocess_env
|
2026-04-24 12:59:28 -06:00
|
|
|
try:
|
2026-09-20 14:43:01 +08:00
|
|
|
bash = "bash"
|
|
|
|
|
if IS_WINDOWS:
|
|
|
|
|
# CreateProcess searches System32 before PATH and may pick WSL's
|
|
|
|
|
# launcher. Reuse the terminal's native Git Bash resolution.
|
|
|
|
|
from tools.environments.local import _find_bash
|
|
|
|
|
bash = _find_bash()
|
2026-04-24 12:59:28 -06:00
|
|
|
completed = subprocess.run(
|
2026-09-20 14:43:01 +08:00
|
|
|
[bash, "-c", command],
|
2026-04-24 12:59:28 -06:00
|
|
|
cwd=str(cwd) if cwd else None,
|
|
|
|
|
capture_output=True,
|
2026-06-29 23:42:46 -03:00
|
|
|
text=True, encoding='utf-8', errors='replace',
|
2026-04-24 12:59:28 -06:00
|
|
|
timeout=max(1, int(timeout)),
|
|
|
|
|
check=False,
|
fix: prevent TUI gateway stdin EOF crash across all TUI-context subprocess calls
When Hermes runs in TUI mode, the gateway child process communicates with
the Node.js parent over a JSON-RPC protocol on stdin. Subprocess calls that
inherit this stdin fd can trigger a race condition where the child's stdin
read returns EOF, causing the gateway to exit cleanly (exit code 0) mid-tool-
execution.
This is the same root cause as issue #14036 (byterover plugin) and PR #39257
(SSH environment backend). This commit applies the fix — stdin=subprocess.DEVNULL
— to all 85 subprocess.run() and subprocess.Popen() calls that execute inside
the TUI gateway child process.
Scope: TUI-context code only (agent/, tools/, plugins/, tui_gateway/server.py).
CLI code (cli.py, hermes_cli/), tests, scripts, and gateway process management
are excluded — they don't run inside the TUI child and inherit the terminal's
stdin, not the JSON-RPC pipe.
85 call sites across 28 files. All files pass syntax check.
2026-06-08 10:06:45 -07:00
|
|
|
stdin=subprocess.DEVNULL,
|
2026-09-07 03:26:32 -07:00
|
|
|
env=delegated_child_subprocess_env(),
|
fix(windows): hide console-window flash on backend git/gh/wmic/bash subprocess spawns
The Windows desktop GUI runs its backend headless via pythonw.exe. Several
auxiliary subprocess sites that run inside that windowless backend spawned
console-subsystem children (git, gh, wmic, powershell, bash, rg, taskkill)
WITHOUT CREATE_NO_WINDOW, so Windows allocated a fresh conhost per call and
flashed a black window on screen — sometimes continuously (the dashboard
Projects-tree git probe alone fired ~118 spawns in 60s on startup).
The terminal tool, cron, browser, code_execution, and gateway-spawn paths
already carry windows_hide_flags(); these auxiliary probe/scan/launcher legs
were missed. Wire the existing helper into them:
- tui_gateway/git_probe.py: run_git (+ encoding=utf-8/errors=replace, fixes the
cp950 UnicodeDecodeError on CJK paths from the same site)
- agent/coding_context.py: _git (per-turn git status/log/diff)
- agent/context_references.py: _run_git + _rg_files (@file/@ref resolution)
- hermes_cli/copilot_auth.py: gh auth token probe (auxiliary provider:auto)
- hermes_cli/gateway.py: wmic + PowerShell Get-CimInstance PID scan
- hermes_cli/main.py: wmic stale-dashboard PID scan
- gateway/status.py: taskkill /T /F force-kill
windows_hide_flags() returns 0 on POSIX, so every changed call is a no-op on
Linux/macOS (verified: real git/rg probes still work; Windows-simulated calls
all pass creationflags=CREATE_NO_WINDOW).
Scoped to the windowless-backend paths that cause the reported flashing. The
Electron updater-handoff leg (main.cjs windowsHide:false) and the
interactive-CLI banner probes (cli.py) are intentionally NOT touched here —
the former needs a Windows-tested change of its own, the latter runs in a
visible console anyway.
Tracking: #54220
Refs: #53178 #53631 #53781 #53957 #49602 #52982 #53424 #53053 #53016
2026-06-28 05:01:59 -07:00
|
|
|
**_popen_kwargs,
|
2026-04-24 12:59:28 -06:00
|
|
|
)
|
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
|
return f"[inline-shell timeout after {timeout}s: {command}]"
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
return "[inline-shell error: bash not found]"
|
|
|
|
|
except Exception as exc:
|
2026-09-02 19:13:55 -07:00
|
|
|
# tests/conftest.py's live-system guard may block the os.kill that
|
|
|
|
|
# subprocess.run uses to clean up a timed-out shell; report the timeout.
|
|
|
|
|
if isinstance(exc, RuntimeError) and "live-system guard: blocked os.kill" in str(exc):
|
|
|
|
|
return f"[inline-shell timeout after {timeout}s: {command}]"
|
2026-04-24 12:59:28 -06:00
|
|
|
return f"[inline-shell error: {exc}]"
|
2026-09-02 19:13:55 -07:00
|
|
|
output = (completed.stdout or "").rstrip("\n") or (completed.stderr or "").rstrip("\n")
|
2026-09-20 14:44:28 -07:00
|
|
|
if completed.returncode != 0 and not output:
|
|
|
|
|
# rc!=0 with no output at all is indistinguishable from a legit empty result; it is the
|
|
|
|
|
# "interpreter never ran the command" signature (WSL stub without a distro) — say so.
|
|
|
|
|
return f"[inline-shell exit {completed.returncode} with no output: {command}]"
|
2026-09-26 22:53:18 +05:30
|
|
|
return elide(output, _INLINE_SHELL_MAX_OUTPUT)
|
2026-04-24 12:59:28 -06:00
|
|
|
|
|
|
|
|
|
2026-09-02 19:13:55 -07:00
|
|
|
def expand_inline_shell(content: str, skill_dir: Path | None, timeout: int) -> str:
|
|
|
|
|
"""Replace every !`cmd` snippet with its stdout, run with the skill dir as CWD."""
|
2026-04-24 12:59:28 -06:00
|
|
|
if "!`" not in content:
|
|
|
|
|
return content
|
|
|
|
|
def _replace(match: re.Match) -> str:
|
|
|
|
|
cmd = match.group(1).strip()
|
2026-09-02 19:13:55 -07:00
|
|
|
return run_inline_shell(cmd, skill_dir, timeout) if cmd else ""
|
2026-04-24 12:59:28 -06:00
|
|
|
return _INLINE_SHELL_RE.sub(_replace, content)
|
|
|
|
|
|
|
|
|
|
|
2026-10-06 11:09:14 -04:00
|
|
|
def _is_community_hub_skill(skill_dir: Path | None) -> bool:
|
|
|
|
|
"""Whether *skill_dir* is a hub-installed skill the scan gate classifies as community trust.
|
|
|
|
|
|
|
|
|
|
The hub's INSTALL_POLICY blocks a community install on a caution/dangerous verdict — but
|
|
|
|
|
``--force`` (or a pre-scanner install) puts that skill on disk anyway, and the inline-shell
|
|
|
|
|
DSL scans as high severity, so auto-executing it on view would re-arm exactly what the
|
|
|
|
|
gate refused (#63307). Provenance is the hub lock entry (trusted/builtin entries expand;
|
|
|
|
|
anything without one — bundled-synced, user-created, project/external — keeps the flag's
|
2026-10-09 14:34:51 -07:00
|
|
|
contract). It covers every SKILL.md nested inside a community install and is read from
|
|
|
|
|
the lock that owns the skills tree the dir lives in, not only the active profile's
|
|
|
|
|
(``external_dirs`` can expose another profile's installs). A lock that exists but cannot
|
|
|
|
|
be read fails closed for skills in its tree; no lock means no hub installs.
|
2026-10-06 11:09:14 -04:00
|
|
|
"""
|
|
|
|
|
if skill_dir is None:
|
|
|
|
|
return False
|
|
|
|
|
try:
|
|
|
|
|
from tools.skills_hub import HubLockFile
|
2026-10-09 14:34:51 -07:00
|
|
|
from tools.skills_tool import _skills_dir
|
|
|
|
|
|
|
|
|
|
target = skill_dir.resolve()
|
|
|
|
|
locks = {HubLockFile().path.resolve(): _skills_dir().resolve()}
|
|
|
|
|
for root in target.parents:
|
|
|
|
|
if root.name == "skills" and (root / ".hub" / "lock.json").is_file():
|
|
|
|
|
locks.setdefault((root / ".hub" / "lock.json").resolve(), root)
|
|
|
|
|
for lock_path, root in locks.items():
|
|
|
|
|
if not (target.is_relative_to(root) and lock_path.is_file()):
|
2026-10-06 11:09:14 -04:00
|
|
|
continue
|
|
|
|
|
try:
|
2026-10-09 14:34:51 -07:00
|
|
|
installed = json.loads(lock_path.read_text(encoding="utf-8-sig"))["installed"]
|
|
|
|
|
entries = [e for e in installed.values() if isinstance(e, dict)]
|
|
|
|
|
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
|
|
|
|
logger.debug("Unreadable hub lock %s; inline shell stays off for its tree", lock_path, exc_info=True)
|
|
|
|
|
return True
|
|
|
|
|
for entry in entries:
|
|
|
|
|
rel = str(entry.get("install_path") or "")
|
|
|
|
|
if entry.get("trust_level") == "community" and rel and target.is_relative_to((root / rel).resolve()):
|
2026-10-06 11:09:14 -04:00
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
except Exception:
|
2026-10-09 14:34:51 -07:00
|
|
|
logger.debug("Could not resolve hub provenance for inline-shell trust scoping", exc_info=True)
|
|
|
|
|
return True
|
2026-10-06 11:09:14 -04:00
|
|
|
|
|
|
|
|
|
2026-04-24 12:59:28 -06:00
|
|
|
def preprocess_skill_content(
|
|
|
|
|
content: str,
|
|
|
|
|
skill_dir: Path | None,
|
|
|
|
|
session_id: str | None = None,
|
|
|
|
|
skills_cfg: dict | None = None,
|
|
|
|
|
) -> str:
|
|
|
|
|
"""Apply configured SKILL.md template and inline-shell preprocessing."""
|
|
|
|
|
if not content:
|
|
|
|
|
return content
|
|
|
|
|
cfg = skills_cfg if isinstance(skills_cfg, dict) else load_skills_config()
|
|
|
|
|
if cfg.get("template_vars", True):
|
|
|
|
|
content = substitute_template_vars(content, skill_dir, session_id)
|
2026-10-06 11:09:14 -04:00
|
|
|
if cfg.get("inline_shell", False) and not _is_community_hub_skill(skill_dir):
|
2026-09-02 19:13:55 -07:00
|
|
|
content = expand_inline_shell(content, skill_dir, int(cfg.get("inline_shell_timeout", 10) or 10))
|
2026-04-24 12:59:28 -06:00
|
|
|
return content
|