Skip to content

The agent that grows with you

fix(gateway,tui): skills installed from another terminal appear as Ink /commands

Teknium9f744be4b6b8
diff --git a/agent/skill_commands.py b/agent/skill_commands.py
index fbdcc3c2477..fe1230a3376 100644
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@ -29,6 +29,10 @@ _skill_commands_by_key: dict[tuple, dict[str, dict[str, Any]]] = {}
# Keep the last map callers could actually see, even when plugin lifecycle
# invalidation drops the projection cache before /reload-skills can diff it.
_last_interactive_skill_commands_by_key: dict[tuple, dict[str, dict[str, Any]]] = {}
+# The on-disk signature each published map was scanned at (same key). The one gateway serves every
+# local session for its whole lifetime, so a skill installed or removed from another terminal must
+# move this signature and rescan on the next lookup instead of waiting for /reload-skills (CFG-8).
+_skill_commands_sig_by_key: dict[tuple, tuple] = {}
_publish_lock = threading.Lock()
# ``\w`` keeps Unicode letters (CJK, Cyrillic) so a ``name: 小说拆条`` skill registers ``/小说拆条``
# instead of slugging to "" and being dropped (#12351); Telegram's ``[a-z0-9_]`` menu limit is
@@ -524,6 +528,8 @@ def scan_skill_commands() -> dict[str, dict[str, Any]]:
# its own (empty) ``seen_names`` but collided against the first scan's already- published slugs, logging
# one bogus "already claimed" warning per skill — each naming the same skill as its own incumbent
# (#74574).
+ # Taken BEFORE the scan: an install racing the scan moves it, so the next lookup rescans.
+ signature = _skill_dirs_signature()
commands: dict[str, dict[str, Any]] = {}
try:
from tools.skills_tool import _get_disabled_skill_names, _skill_catalog
@@ -548,9 +554,23 @@ def scan_skill_commands() -> dict[str, dict[str, Any]]:
# reader between the lookup and this store (#14536, #74574); the scan above
# (file I/O, deferred imports) stays outside it.
_skill_commands_by_key[key] = commands
+ _skill_commands_sig_by_key[key] = signature
return commands
+def _skill_dirs_signature() -> Optional[tuple]:
+ """Stat-cheap change signature of every skill root (the catalog's own: each root's mtime and its
+ immediate child dirs', the disabled set and the platform). None when it cannot be computed, which
+ keeps the published map rather than rescanning on every lookup."""
+ try:
+ from tools.skills_tool import _get_disabled_skill_names, _skill_search_dirs, _skills_scan_signature
+ roots, _active = _skill_search_dirs()
+ return _skills_scan_signature([d for _tier, d in roots], _get_disabled_skill_names())
+ except Exception:
+ logger.debug("Skill dir signature failed", exc_info=True)
+ return None
+
+
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
@@ -566,8 +586,13 @@ def get_skill_commands() -> dict[str, dict[str, Any]]:
key = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
with _publish_lock:
cached = _skill_commands_by_key.get(key)
+ scanned_at = _skill_commands_sig_by_key.get(key)
if cached is not None:
- return cached
+ # A skill installed or removed from another terminal moves the dir signature: rescan, so the
+ # long-lived gateway's palette and dispatch see it without /reload-skills (CFG-8).
+ current = _skill_dirs_signature()
+ if current is None or scanned_at is None or current == scanned_at:
+ return cached
# Scan outside the lock — file I/O and deferred imports; concurrent scans
# are safe since each builds its own map.
return scan_skill_commands()
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index f2ae60c691c..3d4b930f831 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -6972,6 +6972,8 @@ export interface BackendGatewayEventMap {
'sessions.changed': ChangeSignalPayload
/** The free-tier bootstrap finished (broadcast); the desktop's setup gate reads the record. */
'setup.ready': SetupReadyPayload
+ /** A skill root moved (installed/removed elsewhere); refetch commands.catalog from the gateway. */
+ 'skills.changed': ChangeSignalPayload
/** The active skin moved (name switch or live colour edit); repaint from this palette. */
'skin.changed': SkinPayload
/** Transient status line (kind: status, lifecycle, compacting, goal, loop, heartbeat, process, …). */
@@ -7074,6 +7076,7 @@ export const GATEWAY_EVENT_TYPES = [
'session.usage',
'sessions.changed',
'setup.ready',
+ 'skills.changed',
'skin.changed',
'status.update',
'subagent.complete',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 77f125b52fa..5fe1c7b2f0a 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -48417,6 +48417,18 @@
}
]
},
+ {
+ "name": "skills.changed",
+ "summary": "A skill root moved (installed/removed elsewhere); refetch commands.catalog from the gateway.",
+ "params": [
+ {
+ "name": "payload",
+ "schema": {
+ "$ref": "#/components/schemas/ChangeSignalPayload"
+ }
+ }
+ ]
+ },
{
"name": "skin.changed",
"summary": "The active skin moved (name switch or live colour edit); repaint from this palette.",
diff --git a/tests/agent/test_skill_commands_freshness.py b/tests/agent/test_skill_commands_freshness.py
new file mode 100644
index 00000000000..6eb1ad06d84
--- /dev/null
+++ b/tests/agent/test_skill_commands_freshness.py
@@ -0,0 +1,47 @@
+"""CFG-8: a skill installed from another terminal reaches the long-lived gateway's slash map.
+
+The one gateway owns every local session for its whole lifetime, so a process-lifetime memo of the
+skill command map left ``hermes skills install`` (or a dropped SKILL.md) invisible to Ink's
+``/command`` lookup and completion until ``/reload-skills`` or a gateway restart.
+"""
+from unittest.mock import patch
+
+
+def _make_skill(skills_dir, name):
+ skill_dir = skills_dir / name
+ skill_dir.mkdir(parents=True, exist_ok=True)
+ (skill_dir / "SKILL.md").write_text(
+ f"---\nname: {name}\ndescription: Description for {name}.\n---\n\nDo the thing.\n", encoding="utf-8")
+ return skill_dir
+
+
+def test_skill_added_on_disk_after_the_first_scan_is_served_without_reload(tmp_path):
+ import shutil
+
+ import agent.skill_commands as sc_mod
+ import tools.skills_tool as st
+ from agent.skill_commands import get_skill_commands
+
+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path), patch.object(sc_mod, "_skill_commands_by_key", {}):
+ st.clear_skills_cache()
+ _make_skill(tmp_path, "first")
+ assert set(get_skill_commands()) == {"/first"}
+
+ _make_skill(tmp_path, "installed-elsewhere") # another terminal: no reload_skills() here
+ assert set(get_skill_commands()) == {"/first", "/installed-elsewhere"}
+
+ shutil.rmtree(tmp_path / "first") # an uninstall elsewhere drops its command too
+ assert set(get_skill_commands()) == {"/installed-elsewhere"}
+
+
+def test_unchanged_skills_dirs_reuse_the_published_map(tmp_path):
+ import agent.skill_commands as sc_mod
+ import tools.skills_tool as st
+ from agent.skill_commands import get_skill_commands
+
+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path), patch.object(sc_mod, "_skill_commands_by_key", {}):
+ st.clear_skills_cache()
+ _make_skill(tmp_path, "steady")
+ first = get_skill_commands()
+ with patch.object(sc_mod, "scan_skill_commands", side_effect=AssertionError("rescanned")):
+ assert get_skill_commands() is first
diff --git a/tests/tui_gateway/test_change_watcher.py b/tests/tui_gateway/test_change_watcher.py
index 8e8feb3f049..6af24eb211b 100644
--- a/tests/tui_gateway/test_change_watcher.py
+++ b/tests/tui_gateway/test_change_watcher.py
@@ -482,3 +482,23 @@ def test_broken_probe_never_kills_the_pass(watcher_home, monkeypatch):
# The broken cron probe is skipped; sessions still broadcasts.
assert ("sessions.changed", {}) in events
+
+
+def test_skill_installed_from_another_terminal_broadcasts_skills_changed(watcher_home, monkeypatch):
+ """CFG-8: the gateway notices a new skill dir and tells attached clients to refetch
+ ``commands.catalog``; clients never rescan disk themselves."""
+ home, events = watcher_home
+ import tools.skills_tool as st
+ skills = home / "skills"
+ skills.mkdir()
+ monkeypatch.setattr(st, "SKILLS_DIR", skills)
+ server._broadcast_watched_changes(now=0.0)
+ assert not [e for e in events if e[0] == "skills.changed"]
+
+ skill = skills / "new-skill"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text("---\nname: new-skill\ndescription: d\n---\nbody\n")
+ os.utime(skills, (time.time() + 5, time.time() + 5))
+ server._broadcast_watched_changes(now=10.0)
+
+ assert ("skills.changed", {}) in events
diff --git a/tui_gateway/change_watcher.py b/tui_gateway/change_watcher.py
index 734344f6764..bf10566d037 100644
--- a/tui_gateway/change_watcher.py
+++ b/tui_gateway/change_watcher.py
@@ -361,6 +361,14 @@ def _bot_relay_outbox_sig():
return _bot_relay_outbox_seen or None
+def _skills_sig():
+ """The skill roots' stat signature (``agent.skill_commands._skill_dirs_signature``): a skill
+ installed or removed from another terminal (``hermes skills install``, a dropped SKILL.md) moves it,
+ and attached clients refetch ``commands.catalog`` from this gateway instead of rescanning disk."""
+ from agent.skill_commands import _skill_dirs_signature
+ return _skill_dirs_signature()
+
+
# event → (check interval, signature fn, payload fn). Signatures are stat-cheap; the interval
# keeps pricier probes (pet resolves the sheet off disk) off the 0.5s tick. cron/jobs.json
# moves on edits AND scheduler ticks; gateway_state.json is where the messaging gateway
@@ -375,6 +383,7 @@ _CHANGE_WATCHES: dict[str, tuple[float, Any, Any]] = {
"platforms.changed": (2.0, lambda: _home_mtime_ns("gateway_state.json"), dict),
"projects.changed": (2.0, _projects_sig, dict),
"pairing.changed": (2.0, _pairing_sig, dict),
+ "skills.changed": (2.0, _skills_sig, dict),
# 1s so a queued DM envelope reaches the Desktop's push-triggered drain fast.
"bot_relay.outbox.pending": (1.0, _bot_relay_outbox_sig, dict)}
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index 563bb13679b..55383ceb140 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -823,6 +823,8 @@ event("sessions.changed", ChangeSignalPayload, doc="state.db moved; refetch the
event("platforms.changed", ChangeSignalPayload, doc="gateway_state.json moved; refetch platform status.")
event("projects.changed", ChangeSignalPayload, doc="projects.db moved; refetch the project list + tree.")
event("pairing.changed", ChangeSignalPayload, doc="Pairing state moved; refetch pairing.")
+event("skills.changed", ChangeSignalPayload,
+ doc="A skill root moved (installed/removed elsewhere); refetch commands.catalog from the gateway.")
event("bot_relay.outbox.pending", ChangeSignalPayload, doc="A bot-relay outbox envelope is queued; drain it.")
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
index 0f48af0132a..baedf7e5738 100644
--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
@@ -1070,6 +1070,21 @@ describe('createGatewayEventHandler', () => {
vi.unstubAllEnvs()
})
+ it('skills.changed refetches the slash catalog from the gateway for the live session (CFG-8)', async () => {
+ const ctx = buildCtx([])
+
+ const rpc = vi.fn(async () => ({ canon: { '/new-skill': '/new-skill' }, pairs: [['/new-skill', 'd']], skill_count: 1 }))
+
+ ;(ctx.gateway as any).rpc = rpc
+ patchUiState({ sid: 'sid-cfg8' })
+
+ createGatewayEventHandler(ctx)({ payload: {}, type: 'skills.changed' } as any)
+ await vi.waitFor(() => expect(ctx.session.setCatalog).toHaveBeenCalled())
+
+ expect(rpc).toHaveBeenCalledWith('commands.catalog', { session_id: 'sid-cfg8' })
+ expect((ctx.session.setCatalog as any).mock.calls.at(-1)[0].canon).toEqual({ '/new-skill': '/new-skill' })
+ })
+
it('a skin that owns the background paints BOTH terminal defaults (OSC 11 bg + OSC 10 fg)', () => {
// Default-fg tokens (markdown body, borders) render with the TERMINAL's
// default foreground. A dark skin on a light terminal repaints the
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index fe019aea870..c4e752c44cb 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -1116,6 +1116,13 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
return
+ // A skill installed or removed from another terminal: refetch the palette from the gateway
+ // (it rescans; this client never reads the skills dir itself).
+ case 'skills.changed':
+ void loadSlashCatalog(rpc, getUiState().sid, setCatalog)
+
+ return
+
case 'free_tier.challenge':
showChallenge(ev.payload)