The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: remove unused extraction copies
ethernetf2a19b0e0670
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 643059217a7..76e0b9127e9 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -6403,12 +6403,3 @@ def _pm_runtime_venv_dir(project_root: Path | None = None) -> Path | None:venv = selected_venv(root) # a malformed committed selection raises: fail closedreturn venv if venv.is_dir() else None-def _systemd_watchdog_service_fields(- hermes_home: str | Path | None = None,-) -> tuple[str, str]:- """Return systemd service fields for the effective gateway config."""- seconds = _systemd_watchdog_seconds(hermes_home)- if seconds <= 0:- return "simple", ""- return "notify", f"NotifyAccess=main\nWatchdogSec={seconds}s\n"-diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex 65c1089dbdf..aaeff5e1c30 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -362,52 +362,6 @@ def _print_banner(*lines: str) -> None:print(color("└─────────────────────────────────────────────────────────┘", Colors.MAGENTA))-def _prompt_container_resources(config: dict):- """Prompt for container resource settings (Docker, Singularity, Modal, Daytona)."""- terminal = config.setdefault("terminal", {})-- print()- print_info("Container Resource Settings:")-- # Persistence- current_persist = terminal.get("container_persistent", True)- persist_label = "yes" if current_persist else "no"- print_info(" Persistent filesystem keeps files between sessions.")- print_info(" Set to 'no' for ephemeral sandboxes that reset each time.")- persist_str = prompt(- " Persist filesystem across sessions? (yes/no)", persist_label- )- terminal["container_persistent"] = persist_str.lower() in {"yes", "true", "y", "1"}-- # CPU- current_cpu = terminal.get("container_cpu", 1)- cpu_str = prompt(" CPU cores", str(current_cpu))- try:- terminal["container_cpu"] = float(cpu_str)- except ValueError:- pass-- # Memory- current_mem = terminal.get("container_memory", 5120)- mem_str = prompt(" Memory in MB (5120 = 5GB)", str(current_mem))- try:- terminal["container_memory"] = int(mem_str)- except ValueError:- pass-- # Disk- current_disk = terminal.get("container_disk", 51200)- disk_str = prompt(" Disk in MB (51200 = 50GB)", str(current_disk))- try:- terminal["container_disk"] = int(disk_str)- except ValueError:- pass---# Tool categories and provider config are now in tools_config.py (shared-# between `hermes tools` and `hermes setup tools`).--# =============================================================================# Section 1: Model & Provider Configuration# =============================================================================diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.pyindex 4c3700d7307..37f51177658 100644--- a/plugins/platforms/dingtalk/adapter.py+++ b/plugins/platforms/dingtalk/adapter.py@@ -51,7 +51,7 @@ from gateway.platforms.helpers import MessageDeduplicator, compile_mention_pattefrom gateway.platforms.base import BasePlatformAdapter, SendResultfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.platforms._shared import get_scoped_secret as _get_scoped_secret-from plugins.platforms.dingtalk.inbound import DINGTALK_TYPE_MAPPING+from plugins.platforms.dingtalk.inbound import DINGTALK_TYPE_MAPPING, collect_download_codeslogger = logging.getLogger(__name__)@@ -1421,32 +1421,7 @@ class DingTalkAdapter(BasePlatformAdapter):returnrobot_code = getattr(message, "robot_code", None) or self._client_id- codes_to_resolve = []-- # Collect codes and references to update- # 1. Single image content- img_content = getattr(message, "image_content", None)- if img_content and getattr(img_content, "download_code", None):- codes_to_resolve.append((img_content, "download_code"))-- # 2. Rich text list- rich_text = getattr(message, "rich_text_content", None)- if rich_text:- rich_list = getattr(rich_text, "rich_text_list", []) or []- for item in rich_list:- if isinstance(item, dict):- for key in ("downloadCode", "pictureDownloadCode", "download_code"):- if item.get(key):- codes_to_resolve.append((item, key))-- # 3. File/image message (msgtype='file' or 'image', codes in extensions)- msg_type_str = getattr(message, "message_type", "") or ""- if msg_type_str in ("file", "image"):- extensions = getattr(message, "extensions", {}) or {}- ext_content = extensions.get("content", {})- if isinstance(ext_content, dict) and ext_content.get("downloadCode"):- codes_to_resolve.append((ext_content, "downloadCode"))-+ codes_to_resolve = collect_download_codes(message)if not codes_to_resolve:returndiff --git a/pm/ensure.py b/pm/ensure.pyindex 9158be1f4e5..3f6d1259e41 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -324,8 +324,6 @@ def _install(else version)LOG.info("repair: %s re-realized %s -> %s", package.name, old, new)- if previous and previous.get("version") != version:- package.migrate(previous["version"], version)def stage_only(name: str, target: str, progress=None) -> "Path":diff --git a/pm/package.py b/pm/package.pyindex 344bcbbb3ef..d57f7b759f6 100644--- a/pm/package.py+++ b/pm/package.py@@ -161,9 +161,6 @@ class Package:diff["PATH"] = [str(binary.parent)]return diff- def migrate(self, previous_version: str, version: str) -> None:- """User-state migration on version change."""-class DebPackage(Package):"""A .deb artifact staged by ar+tar extraction (never dpkg, neverdiff --git a/tests/gateway/test_dingtalk.py b/tests/gateway/test_dingtalk.pyindex 9b0df151648..7785444abfd 100644--- a/tests/gateway/test_dingtalk.py+++ b/tests/gateway/test_dingtalk.py@@ -765,3 +765,63 @@ class TestDingTalkAdapterAICards:mock_card_sdk.deliver_card_with_options_async.assert_called_once()mock_card_sdk.streaming_update_with_options_async.assert_called_once()assert result.success is True+++class TestResolveMediaCodes:+ """Media codes resolve through the robot API."""++ @pytest.mark.parametrize("message_type", ["file", "image"])+ def test_resolves_codes_from_every_payload_shape(self, message_type):+ from plugins.platforms.dingtalk.adapter import DingTalkAdapter++ adapter = DingTalkAdapter(PlatformConfig(enabled=True))+ adapter._client_id = "robot-x"+ message = SimpleNamespace(+ robot_code=None,+ image_content=SimpleNamespace(download_code="dl-img"),+ rich_text_content=SimpleNamespace(rich_text_list=[+ {"downloadCode": "dl-rich"},+ {"pictureDownloadCode": "dl-pic"},+ {"download_code": "dl-snake"},+ ]),+ message_type=message_type,+ extensions={"content": {"downloadCode": "dl-ext"}},+ )++ seen = []++ async def fetch(request, headers, runtime):+ seen.append((request.download_code, request.robot_code, headers.x_acs_dingtalk_access_token))+ return SimpleNamespace(body=SimpleNamespace(download_url=f"https://example.test/{request.download_code}"))++ adapter._get_access_token = AsyncMock(return_value="tok")+ adapter._robot_sdk = SimpleNamespace(+ robot_message_file_download_with_options_async=AsyncMock(side_effect=fetch),+ )+ asyncio.run(adapter._resolve_media_codes(message))+ assert sorted(seen) == [+ ("dl-ext", "robot-x", "tok"),+ ("dl-img", "robot-x", "tok"),+ ("dl-pic", "robot-x", "tok"),+ ("dl-rich", "robot-x", "tok"),+ ("dl-snake", "robot-x", "tok"),+ ]+ assert message.image_content.download_code == "https://example.test/dl-img"+ assert message.rich_text_content.rich_text_list == [+ {"downloadCode": "https://example.test/dl-rich"},+ {"pictureDownloadCode": "https://example.test/dl-pic"},+ {"download_code": "https://example.test/dl-snake"},+ ]+ assert message.extensions["content"]["downloadCode"] == "https://example.test/dl-ext"++ @pytest.mark.parametrize("has_token,has_codes", [(False, True), (True, False)])+ def test_missing_token_or_codes_never_fetches(self, has_token, has_codes):+ from plugins.platforms.dingtalk.adapter import DingTalkAdapter++ adapter = DingTalkAdapter(PlatformConfig(enabled=True))+ message = SimpleNamespace(image_content=SimpleNamespace(download_code="dl") if has_codes else None)+ adapter._get_access_token = AsyncMock(return_value="tok" if has_token else None)+ fetch = AsyncMock()+ adapter._robot_sdk = SimpleNamespace(robot_message_file_download_with_options_async=fetch)+ asyncio.run(adapter._resolve_media_codes(message))+ fetch.assert_not_called()diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.pyindex 16bf3db6d20..f5a872ab586 100644--- a/tests/pm/test_pm_core.py+++ b/tests/pm/test_pm_core.py@@ -302,19 +302,16 @@ def test_deps_compose_dependents_win(pm_env):assert path.index("toptool-1.0") < path.index("deptool-1.0")-def test_version_bump_reinstalls_and_migrates(pm_env):+def test_version_bump_selects_the_new_tool(pm_env):from pm.ensure import ensurelockfile_path, _, docroot, _ = pm_env- migrations = []- registry._packages["faketool"].migrate = lambda prev, new: migrations.append((prev, new))ensure("faketool", base_env={})name, digest = make_tar(docroot, "faketool-2.0.tar.gz", {"bin/faketool": "#!2"})_pin(lockfile_path, "faketool", "2.0", digest)runner = ensure("faketool", base_env={})assert "faketool-2.0" in runner.env["PATH"]- assert migrations == [("1.0", "2.0")]def test_lazy_installs_disabled(pm_env, monkeypatch):diff --git a/tools/environments/base.py b/tools/environments/base.pyindex 6e88caf6427..21207e876fc 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -234,94 +234,6 @@ class _ThreadedProcessHandle:return self._returncode-# ----------------------------------------------------------------------------# CWD marker for remote backends-# ------------------------------------------------------------------------------def _cwd_marker(session_id: str) -> str:- return f"__HERMES_CWD_{session_id}__"---# Per-session variables that the gateway bridges freshly onto every command's-# process environment (via tools/environments/local._inject_session_context_env,-# reading gateway.session_context._VAR_MAP). They must NEVER be persisted into-# the shared bash session snapshot: a single long-lived backend serves many-# concurrent sessions (the messaging gateway, TUI, desktop/web dashboard all-# collapse the terminal to one "default" environment), so ``export -p`` dumping-# the FIRST session's HERMES_SESSION_ID into the snapshot makes every LATER-# session ``source`` that stale value and see a FOREIGN session's identity —-# overriding the correct per-command Popen env (issue: cross-session-# HERMES_SESSION_ID leak via the shared snapshot). Stripping them from the-# snapshot is safe because they are re-injected on every command; a snapshot-# should only carry the user's own shell state (PATH, functions, exports they-# set), not Hermes' per-turn session identity.-#-# Kept in sync with gateway.session_context._VAR_MAP: every bridged name starts-# with one of these prefixes (or is HERMES_UI_SESSION_ID). Used by unit tests-# as the Python-side contract for the exclusion set; the dump path unsets by-# name/prefix instead of grepping declare lines (see below / issue #71296).-_SNAPSHOT_EXCLUDED_ENV_REGEX = (- "^declare -x (HERMES_SESSION_|HERMES_UI_SESSION_ID|HERMES_CRON_AUTO_DELIVER_|"- "HERMES_CRON_SESSION|HERMES_BROWSER_CONTROL_)"-)-_SHELL_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")---def _export_dump_excluding_session_vars(- tmp_path: str,- excluded_names: Iterable[str] = (),-) -> str:- """Return a shell snippet that dumps ``export -p`` to *tmp_path* minus the- per-session bridged vars (see ``_SNAPSHOT_EXCLUDED_ENV_REGEX``) and any- additional names supplied by the caller.-- Unset the bridged vars in a subshell *before* ``export -p``. A line-based- ``grep -vE`` filter is unsafe: bash 3.2 prints a value containing a newline- as a multi-line ``declare -x NAME="…`` block, so only the opener matches the- regex and continuation lines (e.g. ``curl … | bash #`` smuggled into a- Matrix room/display name via ``HERMES_SESSION_CHAT_NAME``) land in the- snapshot and execute on the next ``source`` (issue #71296). Unsetting first- means ``export -p`` never emits those vars — including any continuation- lines. ``|| true`` keeps the success contract for callers that chain on it.-- The dump MUST be wrapped in a brace group with the redirection applied to- the group. *tmp_path* is typically a shell-variable expansion (a- mktemp-allocated per-writer temp name); a redirection attached to a- pipeline segment would expand it inside that segment's subshell,- potentially inconsistently with the parent that expands the follow-up- ``mv``. The brace-group redirect is expanded in the current shell,- keeping both expansions consistent.- """- # ${!PREFIX*} is bash 3.2+ name-prefix expansion; empty matches are fine- # because ``unset`` with only missing names is ignored under 2>/dev/null.- # Quote caller-provided names so malformed configuration can never become- # shell syntax. Valid environment names remain unquoted by shlex.quote().- safe_names = {- name for name in excluded_names- if isinstance(name, str) and name- }- extra_unset = " ".join(shlex.quote(name) for name in sorted(safe_names))- if extra_unset:- extra_unset = f" {extra_unset}"- return (- "{ ( "- "unset ${!HERMES_SESSION_*} ${!HERMES_CRON_AUTO_DELIVER_*} "- "${!HERMES_BROWSER_CONTROL_*} "- # AI_AGENT / HERMES_AGENT are per-command attribution markers- # (re-exported by every _wrap_command with outer-harness-preserving- # ${VAR:-default} semantics). Persisting them into the snapshot- # would make the FIRST command's value override a later outer- # harness value arriving via the process env, exactly like the- # session-var leak this dump already guards against.- "AI_AGENT HERMES_AGENT "- f"HERMES_UI_SESSION_ID{extra_unset} 2>/dev/null; "- "export -p; "- ") || true; } "- f"> {tmp_path}"- )--# ---------------------------------------------------------------------------# BaseEnvironment# ---------------------------------------------------------------------------diff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex 6ef7e611232..e45b8f92023 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -21,8 +21,9 @@ import uuidfrom pathlib import Pathfrom typing import Optional-from tools.environments.base import BaseEnvironment, EnvironmentConnectionError, _SHELL_ENV_NAME_RE+from tools.environments.base import BaseEnvironment, EnvironmentConnectionErrorfrom tools.environments.base_output import _popen_bash+from tools.environments.base_session_env import _SHELL_ENV_NAME_REfrom tools.environments.docker_egress import (_EGRESS_LABEL_KEY, _critical_egress_env_names, _egress_enforce_on_docker, _egress_proxy_args_for_docker,_egress_reuse_fingerprint, check_docker_env_collisions, check_extra_args_collisions,diff --git a/tools/transcription_tools.py b/tools/transcription_tools.pyindex 8be86077c3f..5704032bae8 100644--- a/tools/transcription_tools.py+++ b/tools/transcription_tools.py@@ -175,45 +175,12 @@ def _detect_local_backend() -> Optional[str]:return "local_command" if _has_local_command() else ("local" if _try_lazy_install_stt() else None)-def _read_command_stt_output(output_path: Path, stdout: str, fmt: str) -> str:- """Return the transcript text from a command-provider invocation.-- Resolution:- 1. If ``output_path`` exists and is non-empty → read it (raw text).- 2. Else if ``stdout`` is non-empty → use stdout (lets users write- curl-style one-liners that emit transcript to stdout instead of- writing a file).- 3. Else → raise RuntimeError (no usable output produced).-- For JSON format, we still return the raw bytes — extracting a- ``text`` field is out of scope; users either configure ``format: txt``- or post-process JSON downstream. (Same trade-off as TTS: the runner- doesn't try to be clever about output shape.)- """- if output_path.exists():- try:- content = output_path.read_text(encoding="utf-8-sig").strip()- except UnicodeDecodeError:- content = output_path.read_bytes().decode("utf-8", errors="replace").strip()- if content:- return content- if stdout and stdout.strip():- return stdout.strip()- raise RuntimeError(- f"Command STT provider wrote no output file at {output_path} "- f"and produced no stdout"- )--def _resolve_explicit_local() -> str:backend = _detect_local_backend()if not backend:logger.warning("STT provider 'local' configured but unavailable ""(install faster-whisper or set HERMES_LOCAL_STT_COMMAND)")return backend or "none"-# MERGE-CHECK: kept our utf-8-sig _read_command_stt_output alongside upstream's refactored-# _resolve_explicit_local; upstream moved the command-STT reader to tools/transcription_command.py-# WITHOUT the utf-8-sig fix — parent may want to port it there and drop this copy.def _resolve_explicit_local_command() -> str: