Skip to content

The agent that grows with you

fix(tui): project-local skills register and dispatch for the session's repo

teknium11764508c1635
diff --git a/agent/runtime_cwd.py b/agent/runtime_cwd.py
index b70f084c978..7599650836c 100644
--- a/agent/runtime_cwd.py
+++ b/agent/runtime_cwd.py
@@ -44,6 +44,11 @@ def clear_session_cwd() -> None:
_SESSION_CWD.set("")
+def reset_session_cwd(token: Token) -> None:
+ """Restore the logical cwd that was active before the matching ``set_session_cwd``."""
+ _SESSION_CWD.reset(token)
+
+
def scope_terminal_cwd() -> str:
"""Scope-aware TERMINAL_CWD value (may be empty) — every cwd consumer reads through this.
diff --git a/agent/skill_commands.py b/agent/skill_commands.py
index ae64a88189d..1ce7098d4df 100644
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@ -17,7 +17,8 @@ logger = logging.getLogger(__name__)
_skill_commands: Dict[str, Dict[str, Any]] = {}
_skill_commands_platform: Optional[str] = None
_skill_commands_home: Optional[str] = None
-# Guards the (map, platform-tag, home-tag) triple so publication and the
+_skill_commands_project: Optional[str] = None
+# Guards the (map, platform-tag, home-tag, project-tag) tuple so publication and the
# freshness lookup always see a consistent snapshot. Scanning stays outside.
_publish_lock = threading.Lock()
# ``\w`` keeps Unicode letters (CJK, Cyrillic) so a ``name: 小说拆条`` skill registers ``/小说拆条``
@@ -152,6 +153,15 @@ def _resolve_skill_commands_home() -> str:
return str(get_hermes_home())
+def _resolve_skill_commands_project() -> Optional[str]:
+ """The project root the scan's project skills resolve from (None outside a repo). One multi-session
+ host serves sessions in different repos; without this tag the first session's project skills stayed
+ published for every other session's ``get_skill_commands`` lookup (#114359)."""
+ from agent.skill_utils import find_project_root
+ root = find_project_root()
+ return str(root) if root is not None else None
+
+
def _load_skill_payload(skill_identifier: str, task_id: str | None = None) -> tuple[dict[str, Any], Path | None, str] | None:
"""Load a skill by name/path and return (loaded_payload, skill_dir, display_name)."""
raw_identifier = (skill_identifier or "").strip()
@@ -368,9 +378,10 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
Builds a local map and publishes once at the end: writing straight into the
global exposed partial results to overlapping scans, which then logged
bogus "already claimed" collisions against their own incumbents."""
- global _skill_commands, _skill_commands_platform, _skill_commands_home
+ global _skill_commands, _skill_commands_platform, _skill_commands_home, _skill_commands_project
platform = _resolve_skill_commands_platform()
home = _resolve_skill_commands_home()
+ project = _resolve_skill_commands_project()
# Build into a local map and publish once, at the end. Writing straight into the global made a scan's
# partial results visible to everything else in the process: a second, overlapping scan deduped against
# its own (empty) ``seen_names`` but collided against the first scan's already- published slugs, logging
@@ -413,22 +424,22 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
_skill_commands = commands
_skill_commands_platform = platform
_skill_commands_home = home
+ _skill_commands_project = project
return commands
def get_skill_commands() -> Dict[str, Dict[str, Any]]:
"""Return the current skill commands mapping (scan first if empty). Rescans
when the platform scope (one gateway serving Telegram and Discord) or the
- active profile's home (Desktop profile switch) changes, so each sees its
- own ``platform_disabled`` / ``external_dirs`` view.
+ active profile's home (Desktop profile switch) or the session's project root (two sessions in two
+ repos) changes, so each sees its own ``platform_disabled`` / ``external_dirs`` / project-skill view.
- See #14536, #88023.
+ See #14536, #88023, #114359.
"""
- current_platform = _resolve_skill_commands_platform()
- current_home = _resolve_skill_commands_home()
+ current = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
with _publish_lock:
commands = _skill_commands
- is_fresh = bool(commands) and (_skill_commands_platform, _skill_commands_home) == (current_platform, current_home)
+ is_fresh = bool(commands) and (_skill_commands_platform, _skill_commands_home, _skill_commands_project) == current
# Scan outside the lock — file I/O and deferred imports; concurrent scans
# are safe since each builds its own map.
return commands if is_fresh else scan_skill_commands()
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index d493de3027c..982be8017ae 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -3124,6 +3124,57 @@ def test_expand_skill_invocation_for_replay_leaves_ordinary_text_alone(monkeypat
assert server._expand_skill_invocation_for_replay("/status", "t") == "/status"
+def test_command_dispatch_and_catalog_resolve_project_skills_from_the_session_cwd(tmp_path, monkeypatch):
+ # TUI/desktop: the RPC thread has no session context and the terminal scope / process env resolve a
+ # placeholder ``terminal.cwd`` to $HOME, so project skills of the session's repo never registered and
+ # ``/<name>`` died with "not a quick/plugin/bundle/skill command". Two sessions in two trusted repos
+ # in ONE process must each catalog and dispatch their own repo's skill (the cached registry is
+ # keyed by project root, not just platform + home).
+ import agent.skill_commands as skill_commands
+ import agent.skill_utils as skill_utils
+ import tools.skills_tool as skills_tool
+
+ def repo(name: str, skill: str) -> Path:
+ r = tmp_path / name
+ (r / ".git").mkdir(parents=True)
+ (r / ".hermes" / "skills" / skill).mkdir(parents=True)
+ (r / ".hermes" / "skills" / skill / "SKILL.md").write_text(
+ f"---\nname: {skill}\ndescription: from {name}\n---\n\n# {skill}\n\nBODY OF {skill.upper()}\n")
+ return r
+
+ repo_a, repo_b = repo("proj-a", "alpha-skill"), repo("proj-b", "beta-skill")
+ home = tmp_path / "hermes-home"
+ (home / "skills").mkdir(parents=True)
+ (home / "config.yaml").write_text(
+ f"skills:\n external_dirs: []\n trusted_project_dirs: ['{repo_a}', '{repo_b}']\n")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(skills_tool, "SKILLS_DIR", home / "skills")
+ monkeypatch.setattr(skill_utils, "_skills_cfg", lambda: {
+ "external_dirs": [], "trusted_project_dirs": [str(repo_a), str(repo_b)]})
+ skill_utils._external_dirs_cache_clear()
+ monkeypatch.setattr(skill_commands, "_skill_commands", {})
+ monkeypatch.setattr(skill_commands, "_skill_commands_platform", None)
+ # Launch shape: process cwd and TERMINAL_CWD both point at a non-project dir (the resolved placeholder).
+ elsewhere = tmp_path / "home-dir"
+ elsewhere.mkdir()
+ monkeypatch.chdir(elsewhere)
+ monkeypatch.setenv("TERMINAL_CWD", str(elsewhere))
+ monkeypatch.setattr(server, "_sessions", {
+ "sid-a": {"session_key": "key-a", "cwd": str(repo_a)},
+ "sid-b": {"session_key": "key-b", "cwd": str(repo_b)}})
+
+ for sid, own, other in (("sid-a", "alpha-skill", "beta-skill"), ("sid-b", "beta-skill", "alpha-skill")):
+ catalog = server._methods["commands.catalog"]("c", {"session_id": sid})["result"]
+ assert f"/{own}" in catalog["skills"] and f"/{other}" not in catalog["skills"]
+ res = server._methods["command.dispatch"]("d", {"name": own, "arg": "go", "session_id": sid})
+ assert res["result"]["type"] == "skill", res
+ assert f"BODY OF {own.upper()}" in res["result"]["message"]
+ miss = server._methods["command.dispatch"]("m", {"name": other, "arg": "", "session_id": sid})
+ assert miss["error"]["code"] == 4018
+ # Nothing leaks past the RPC: the thread's logical cwd is unbound again.
+ assert skill_utils.find_project_root() is None
+
+
def test_history_to_messages_types_a_legacy_auto_continue_row():
# A crash-interrupted turn used to be typed only AFTER it finished, so a
# turn killed a second time (or any row written before turn-start typing
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 88c78668e9b..ce1f35b0df0 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -432,7 +432,9 @@ def _catalog_skills(cat: _Catalog, skills: dict[str, dict]) -> None:
@_rpc("commands.catalog", 5020)
def _(rid, params: dict) -> dict:
"""Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``
- (skills' message wins, then quick commands', then plugins')."""
+ (skills' message wins, then quick commands', then plugins'). Skill discovery is bound to the calling
+ session's profile and workspace (``_completion_cwd``: its record, else the cwd a new session would be
+ seeded with) so project-local skills register for the repo the session is actually in (#114359)."""
cat = _Catalog()
_catalog_registry(cat)
warning = ""
@@ -446,7 +448,8 @@ def _(rid, params: dict) -> dict:
warning = warning or f"plugin command discovery unavailable: {e}"
skills: dict[str, dict] = {}
try:
- _catalog_skills(cat, skills)
+ with _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params)):
+ _catalog_skills(cat, skills)
except Exception as e:
warning = f"skill discovery unavailable: {e}"
return _ok(rid, {
@@ -516,18 +519,27 @@ def _run_plugin_command(handler, arg: str) -> str:
@contextlib.contextmanager
-def _session_home_scope(session):
- """Bind HERMES_HOME to the session's profile for the block (no-op for the launch profile).
+def _session_home_scope(session, cwd: str | None = None):
+ """Bind HERMES_HOME and the logical cwd to the session for the block.
Skill/bundle/quick-command resolution is home-keyed (``skills.external_dirs``, ``skill-bundles/``,
``quick_commands`` all live in the profile's config/home); nothing upstream of these RPC handlers
- binds it, so an unscoped call resolves against the launch profile (#110695)."""
+ binds it, so an unscoped call resolves against the launch profile (#110695). Project-local skills
+ are cwd-keyed (``find_project_root`` reads the session-bound cwd first): these RPCs run on the socket
+ thread with no session context, where the terminal scope resolves a placeholder ``terminal.cwd`` to
+ ``$HOME`` and no project skill ever registers or dispatches (#114359). ``cwd`` overrides the session
+ record (a session-less catalog request binds the workspace a new session would be seeded with)."""
hc = _tools_mod("hermes_constants")
+ rc = _tools_mod("agent.runtime_cwd")
profile_home = session.get("profile_home") if session else None
+ cwd = cwd or (str(session.get("cwd") or "") if session else "")
token = hc.set_hermes_home_override(profile_home) if profile_home else None
+ cwd_token = rc.set_session_cwd(cwd) if cwd else None
try:
yield
finally:
+ if cwd_token is not None:
+ rc.reset_session_cwd(cwd_token)
if token is not None:
hc.reset_hermes_home_override(token)