The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): report the commands Ink answers itself through command.observe
unsupportedpastelsc5d32dd85e6f
diff --git a/tests/gateway/test_pre_command_in_gateway.py b/tests/gateway/test_pre_command_in_gateway.pyindex a368026bd87..628a6a197ad 100644--- a/tests/gateway/test_pre_command_in_gateway.py+++ b/tests/gateway/test_pre_command_in_gateway.py@@ -372,6 +372,28 @@ def test_pre_command_fires_in_the_sessions_own_profile(tmp_path):('status', root_sid, str(home.resolve()))], root_fired[email protected]("linux")+def test_a_command_ink_answers_itself_fires_once_in_the_gateway_when_observed(tmp_path):+ """Ink answers ``/usage`` and ``/history`` without ``slash.exec`` and reports them through+ ``command.observe``: each fires ``pre_command`` once, in the gateway, under the TUI session's+ profile, with main's values. A name only Ink knows (``/fortune``) is refused and fires nothing."""+ from hermes_cli.gateway_client import GatewayClientError+ with _gateway(tmp_path) as (proc, desc, home, work, _env, log, _peer):+ wire = _Wire(home, desc)+ try:+ tui = wire.call('session.create', request_id='ink', source='tui', toolsets=[], cwd=str(work))['session_id']+ assert wire.call('command.observe', session_id=tui, name='usage', arg='') == {'queued': True}+ with pytest.raises(GatewayClientError):+ wire.call('command.observe', session_id=tui, name='fortune', arg='')+ assert wire.call('command.observe', session_id=tui, name='history', arg='') == {'queued': True}+ fired = _hooks_through(log, 'history')+ finally:+ wire.close()+ assert [(r['pid'], r['surface'], r['platform'], r['command'], r['alias_used'], r['session_key'], r['home'])+ for r in fired] == [(proc.pid, 'cli', 'cli', command, command, tui, str(home.resolve()))+ for command in ('usage', 'history')], fired++@pytest.mark.platforms("linux")def test_commands_refused_during_a_turn_fire_nothing(tmp_path):"""``/reasoning`` is a settings control the busy dispatcher rejects during a turn (defaultdiff --git a/ui-tui/src/__tests__/canonicalCommandObserve.test.ts b/ui-tui/src/__tests__/canonicalCommandObserve.test.tsnew file mode 100644index 00000000000..b314cbb277e--- /dev/null+++ b/ui-tui/src/__tests__/canonicalCommandObserve.test.ts@@ -0,0 +1,108 @@+import { JsonRpcGatewayError } from '@hermes/shared/json-rpc-channel'+import { beforeEach, expect, it, vi } from 'vitest'++import { createSlashHandler } from '../app/createSlashHandler.js'+import { patchUiState, resetUiState } from '../app/uiStore.js'++// PLG-7: the shared gateway fires `pre_command` for the commands it runs (slash.exec,+// command.dispatch). A registry command Ink answers itself is reported through `command.observe`,+// as the classic CLI reports its own; one Ink forwards is never reported twice.+const flush = () => new Promise(resolve => setTimeout(resolve, 5))++beforeEach(() => {+ resetUiState()+ patchUiState({ sid: 'owner', info: { model: 'm', skills: {}, tools: {} } as any })+})++function harness({ canonical = true, observe }: { canonical?: boolean; observe?: () => Promise<unknown> } = {}) {+ const request = vi.fn(async (method: string) => {+ if (method === 'command.observe') {+ return observe ? observe() : { queued: true }+ }++ if (method === 'slash.exec') {+ return { output: 'ok', type: 'exec' }+ }++ return {}+ })++ const sys = vi.fn()+ const gw = { isCanonical: canonical, request }++ const slash = createSlashHandler({+ composer: { enqueue: vi.fn() },+ gateway: { gw, rpc: request },+ local: { getHistoryItems: () => [], getLastUserMsg: () => '', maybeWarn: vi.fn() },+ session: { resumeById: vi.fn() },+ slashFlightRef: { current: 0 },+ transcript: { page: vi.fn(), panel: vi.fn(), send: vi.fn(), setHistoryItems: vi.fn(), sys, trimLastExchange: (x: unknown[]) => x }+ } as any)++ const observed = () => request.mock.calls.filter(([method]) => method === 'command.observe').map(([, params]) => params)++ return { gw, observed, request, slash, sys }+}++it('reports a registry command Ink answers itself, as typed, once', async () => {+ const { gw, observed, request, slash } = harness()++ slash('/history')+ slash('/usage')+ await flush()++ expect(gw.request).toBe(request) // the same client, its own request restored++ expect(observed()).toEqual([+ { arg: '', name: 'history', session_id: 'owner' },+ { arg: '', name: 'usage', session_id: 'owner' }+ ])+})++it('never reports a command Ink sends to the gateway, which fires pre_command itself', async () => {+ const { observed, request, slash } = harness()++ slash('/status')+ slash('/plugins list')+ slash('/no-such-local-command')+ await flush()++ expect(request).toHaveBeenCalledWith('slash.exec', expect.objectContaining({ command: 'status' }))+ expect(request).toHaveBeenCalledWith('slash.exec', expect.objectContaining({ command: 'plugins list' }))+ expect(observed()).toEqual([])+})++it('reports nothing off the shared gateway, for programmatic calls, or with no session', async () => {+ const legacy = harness({ canonical: false })++ legacy.slash('/history')+ await flush()+ expect(legacy.observed()).toEqual([])++ const programmatic = harness()++ programmatic.slash('/history', undefined, false)+ await flush()+ expect(programmatic.observed()).toEqual([])++ patchUiState({ sid: null })+ const fresh = harness()++ fresh.slash('/history')+ await flush()+ expect(fresh.observed()).toEqual([])+})++it('an older gateway without command.observe shows nothing and is not asked again', async () => {+ const older = harness({+ observe: () => Promise.reject(new JsonRpcGatewayError('unknown_method: command.observe', { code: -32601 }))+ })++ older.slash('/history')+ await flush()+ older.slash('/usage')+ await flush()++ expect(older.observed()).toHaveLength(1)+ expect(older.sys).not.toHaveBeenCalledWith(expect.stringMatching(/observe|unknown_method/))+})diff --git a/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx b/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsxindex 002477713c7..d777cb18cd4 100644--- a/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx+++ b/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx@@ -41,7 +41,7 @@ function mount(canonical = false, extra: (method: string, params: any) => unknowif (method === 'image.detach') {images.set(params.session_id, (images.get(params.session_id) ?? []).filter(path => path !== params.path))- } else if (!method.startsWith('complete.') && method !== 'shared_metrics.slash_command') {+ } else if (!method.startsWith('complete.') && !['command.observe', 'shared_metrics.slash_command'].includes(method)) {throw new Error(`Unexpected RPC: ${method}`)}diff --git a/ui-tui/src/app/createSlashHandler.ts b/ui-tui/src/app/createSlashHandler.tsindex b52a46e2906..e287e1d0f44 100644--- a/ui-tui/src/app/createSlashHandler.ts+++ b/ui-tui/src/app/createSlashHandler.ts@@ -9,10 +9,15 @@ import { getWidgetApp } from '../sdk/registry.js'import type { SlashHandler, SlashHandlerContext, SlashSubmission } from './interfaces.js'import { scoreSlashMenuItem } from './slash/fuzzyScore.js'import { findSlashCommand } from './slash/registry.js'-import type { SlashRunCtx } from './slash/types.js'+import type { SlashCommand, SlashRunCtx } from './slash/types.js'import { captureDestination, isCurrentDestination } from './submissionDestination.js'import { getUiState } from './uiStore.js'-import { describeSlashExecError, isUnsupportedCommand, shouldFallbackToDispatch } from './userMessages.js'+import {+ describeSlashExecError,+ isUnsupportedCommand,+ RPC_UNKNOWN_METHOD,+ shouldFallbackToDispatch+} from './userMessages.js'/** Shared metrics count each user-typed command once, from the client: the gateway no longer* counts slash.exec, so locally handled commands (/resume, /skin, overlays) land too.@@ -25,6 +30,53 @@ export function reportSlashCommand(gw: GatewayClient, name: string, sid: null |}}+// Gateways that answered `command.observe` with unknown_method (older than this TUI): not asked again.+const observeUnsupported = new WeakSet<object>()++const FORWARDS = new Set(['command.dispatch', 'slash.exec'])++/** The shared gateway fires `pre_command` for the commands it runs (`slash.exec`,+ * `command.dispatch`). A recognized command Ink answers itself is reported the way the classic CLI+ * reports its own (`command.observe`, plain data, not awaited); the gateway refuses a name it does+ * not recognize. A command Ink sends to the gateway (every one sends it synchronously from `run`)+ * is never reported twice: while `run` runs, the client's `request` notes a forward. The client+ * itself stays the same object (session state is keyed by it), and is restored before returning. */+function runObserved(found: SlashCommand, arg: string, runCtx: SlashRunCtx, cmd: string, name: string): void {+ const { gw } = runCtx.gateway++ if (!gw?.isCanonical || !runCtx.sid || observeUnsupported.has(gw)) {+ return found.run(arg, runCtx, cmd)+ }++ let forwarded = false+ const own = Object.prototype.hasOwnProperty.call(gw, 'request')+ const original = gw.request++ gw.request = ((method: string, ...rest: unknown[]) => {+ forwarded ||= FORWARDS.has(method)++ return (original as (...a: unknown[]) => unknown).call(gw, method, ...rest)+ }) as typeof gw.request++ try {+ found.run(arg, runCtx, cmd)+ } finally {+ if (own) {+ gw.request = original+ } else {+ delete (gw as { request?: unknown }).request+ }+ }++ if (!forwarded) {+ gw.request('command.observe', { arg, name, session_id: runCtx.sid }).catch((e: unknown) => {+ if ((e as { code?: number })?.code === RPC_UNKNOWN_METHOD || /unknown_method/.test(rpcErrorMessage(e))) {+ observeUnsupported.add(gw)+ }+ })+ }+}+/** `typed` is false for programmatic calls (a picker re-issuing `/model <x>`) and for the* backend's alias re-dispatch; prefix/alias expansion keeps it, so a typed `/hea` counts once* as the /heartbeat it resolved to. */@@ -69,7 +121,8 @@ export function createSlashHandler(ctx: SlashHandlerContext): SlashHandler {if (found) {countTyped()- found.run(parsed.arg, runCtx, cmd)+ // A programmatic call (a picker's re-issue, an alias re-dispatch) is not the user's command.+ typed ? runObserved(found, parsed.arg, runCtx, cmd, parsed.name) : found.run(parsed.arg, runCtx, cmd)return true}diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 066092b9b7f..c63e3fcb26e 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -478,7 +478,7 @@ Payload fields below are the exact event-specific fields supplied by each call s| `pre_gateway_dispatch` | Directive/control | Once per incoming non-internal message, at ingress: platform-adapter messages before auth/pairing/dispatch; webhook and relay deliveries after their authorization, before the admission commits; never for local CLI/TUI/Desktop or API turns, a retry of a committed delivery, or a queued admission when it executes. First valid `skip`, `rewrite`, or `allow` controls flow. | `event`, `gateway`, `session_store` | Extremely privileged in-process objects expose inbound user/routing data and host handles. || `post_gateway_admission` | Directive/control (fail-open) | Admitted non-internal message after auth, pause/drain, pending-reply, running-session and slash-command lanes, inside the claimed session slot and the routed profile's scope; first `handled` result skips the agent turn, anything else (including a raise or timeout) runs it. | `session_key`, `platform`, `source` (dict snapshot), `message_id`, `text` | Inbound text is untrusted user data; no runner or session-store handles are passed. || `gateway_platform_event` | Observer | After the gateway's profile-scoped authorization succeeds, when a supported platform-native event is normalized at the gateway boundary (Telegram: reactions, message edits; Discord: message edits/deletes, thread created/renamed); return ignored. | `platform`, `event_type`, `payload` (event-type-specific dict — see the per-event contracts below) | Normalized plain-dict envelope only; raw SDK objects, adapter handles, and bot clients are never exposed. |-| `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). A command the classic CLI, TUI or Desktop sends to the gateway fires it once, in the gateway, with `surface` and `platform` both `"cli"` as before (Ink and Desktop fired it through the CLI slash worker) and `session_key` the session id; a command the classic CLI runs itself is reported to the gateway (`command.observe`), which fires it there after replying, so the CLI never loads plugin code. A gateway older than the CLI gets a one-time notice and no hook for those commands. During a local session's turn every command that still runs fires it except `/stop`, `/approve` and `/deny`; a command that is refused (rejected while busy, or named as unavailable on the gateway) fires nothing. Each callback is timeout-bounded (`plugins.hook_callback_timeout`) and runs on the gateway's own observer workers; one session's commands reach it in order, and a callback still running for that session (hung) is skipped for its later commands instead of running out of order, without holding up other sessions. Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. |+| `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). A command the classic CLI, TUI or Desktop sends to the gateway fires it once, in the gateway, with `surface` and `platform` both `"cli"` as before (Ink and Desktop fired it through the CLI slash worker) and `session_key` the session id; a recognized command the classic CLI or the TUI answers itself is reported to the gateway (`command.observe`), which fires it there after replying, so neither loads plugin code. A gateway older than the client fires no hook for those commands (the classic CLI prints a one-time notice). Desktop's own pickers, actions and dedicated RPCs (commands it answers without `slash.exec`) fire nothing yet. During a local session's turn every command that still runs fires it except `/stop`, `/approve` and `/deny`; a command that is refused (rejected while busy, or named as unavailable on the gateway) fires nothing. Each callback is timeout-bounded (`plugins.hook_callback_timeout`) and runs on the gateway's own observer workers; one session's commands reach it in order, and a callback still running for that session (hung) is skipped for its later commands instead of running out of order, without holding up other sessions. Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. || `pre_approval_request` | Observer | Before prompted or smart approval; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id` | Command may contain secrets; smart observer preparation force-redacts, but surfaces do not all have identical redaction. || `post_approval_response` | Observer | After a decision, timeout, or gateway notification failure; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id`, `choice`; smart path may add `decided_by` | Same command sensitivity plus decision metadata. || `on_human_input_request` | Observer | The agent is about to block on a person — sudo password prompt, `clarify` question, or dangerous-command approval — on CLI, Ink TUI/Desktop, ACP and gateway platforms; return ignored. | `kind` (`"sudo"` \| `"clarify"` \| `"approval"`), `request_id`, `session_id`, `session_key`, `platform`, `prompt` | `prompt` is always force-redacted; the typed password or answer is never passed. |