Files
hermes-agent/agent/runtime_cwd.py
Teknium be5c6a2fd8 refactor(agent/prompt): remove dead code, unify duplicated helpers, compact docstrings across prompt/skill/redaction modules
Dead (zero refs): coding_system_blocks, get_friendly_tool_labels, get_scan_ordered_skills_dirs,
_project_quarantine_cache_clear, clear_stable_prefixes, _redact_http_request_target_query_params,
_has_http_method_substring, PromptCachePlan.marker_count, display _diff_* colour thunks (-> _diff_ansi),
pass-through RedactingFormatter.__init__.
Unified: _slugify -> slugify_skill_name; reload diff -> diff_command_snapshots; _is_summary_item ->
is_compaction_summary_message alias; sanitizer walkers -> _sanitize_messages/_sanitize_structure;
assignment redaction passes -> _redact_assignments/_should_redact_assignment; quiet-mode tool lines -> _CUTE_LINES table.
2026-09-02 13:53:57 -07:00

118 lines
4.1 KiB
Python

"""Single source of truth for the agent working directory.
`TERMINAL_CWD` is the runtime carrier for the configured working directory
(`terminal.cwd` is bridged to it once at gateway/cron startup; the local CLI
leaves it unset and relies on the launch dir). Reading it in one place keeps the
system prompt, tool surfaces, and context-file discovery agreeing on where the
agent lives. Multi-session gateways can pin a logical cwd via `_SESSION_CWD`.
"""
import logging
import os
from contextvars import ContextVar, Token
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
_UNSET: Any = object()
_SESSION_CWD: ContextVar = ContextVar("HERMES_SESSION_CWD", default=_UNSET)
# The package/source root (<root>/agent/runtime_cwd.py). A backend launched from
# or self-spawned into this tree (desktop default) must never let an os.getcwd()
# fallback inject this repo's contributor AGENTS.md as project context.
_PACKAGE_ROOT = Path(__file__).resolve().parent.parent
def _is_install_tree(p: Path) -> bool:
"""True only when ``p`` IS the package root or sits inside it — ancestors
(a home dir containing the checkout) are legitimate workspaces."""
try:
p = p.resolve()
except Exception:
return False
return p == _PACKAGE_ROOT or _PACKAGE_ROOT in p.parents
def set_session_cwd(cwd: str | None) -> Token:
"""Pin the logical cwd for the current context."""
return _SESSION_CWD.set((cwd or "").strip())
def clear_session_cwd() -> None:
_SESSION_CWD.set("")
def _session_cwd_override() -> str:
value = _SESSION_CWD.get()
if value is _UNSET:
return ""
return str(value).strip()
def _terminal_cwd_env() -> str:
"""Scope-aware TERMINAL_CWD read (tools.terminal_scope.terminal_env).
Under gateway multiplexing the per-turn terminal scope carries the active
profile's cwd; the process-global env var may hold another profile's. Only
an ImportError falls back: an active refusal scope must raise, not silently
resolve the launch profile's cwd.
"""
try:
from tools.terminal_scope import terminal_env
except ImportError:
return os.environ.get("TERMINAL_CWD", "")
return terminal_env("TERMINAL_CWD", "")
def scope_terminal_cwd() -> str:
"""Public wrapper — the scope-aware TERMINAL_CWD value (may be empty).
Shared by agent_init / skill_utils / code_execution_tool so every cwd consumer
reads through the per-turn terminal scope under gateway multiplexing.
"""
return _terminal_cwd_env()
def _resolve_configured_cwd(*, override_is_final: bool) -> Path | None:
"""Session override, then TERMINAL_CWD; each validated as a real directory.
``override_is_final``: a set-but-missing session override yields None
instead of falling through to TERMINAL_CWD.
"""
override = _session_cwd_override()
if override:
p = Path(override).expanduser()
if p.is_dir():
return p
logger.warning("configured working directory does not exist: %s", override)
if override_is_final:
return None
raw = _terminal_cwd_env().strip()
if raw:
p = Path(raw).expanduser()
if p.is_dir():
return p
logger.warning("TERMINAL_CWD does not exist: %s", raw)
return None
def resolve_agent_cwd() -> Path:
"""Configured cwd, else the launch dir (os.getcwd() — its OSError on a
deleted cwd deliberately propagates; the caller owns that guard)."""
p = _resolve_configured_cwd(override_is_final=False)
return p if p is not None else Path(os.getcwd())
def resolve_context_cwd() -> Path | None:
"""Configured cwd for context-file discovery, or None for "no configured cwd".
None makes build_context_files_prompt fall back to the launch dir (correct
for a local CLI launched inside a real project). A configured path is
validated here; an existing one is honored verbatim — including the Hermes
source tree itself, a legitimate workspace when developing Hermes
(fallback-directory policy lives in build_context_files_prompt).
"""
return _resolve_configured_cwd(override_is_final=True)