The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): report a locally answered command to pre_command only once it ran
unsupportedpastelsc8136a8f0ab3
diff --git a/tests/gateway/test_pre_command_in_gateway.py b/tests/gateway/test_pre_command_in_gateway.pyindex 8c8d0c881b9..8a6dd1095b4 100644--- a/tests/gateway/test_pre_command_in_gateway.py+++ b/tests/gateway/test_pre_command_in_gateway.py@@ -376,7 +376,9 @@ def test_pre_command_fires_in_the_sessions_own_profile(tmp_path):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."""+ profile, with main's values. A name only Ink knows (``/fortune``) is refused and fires nothing.+ This sends ``command.observe`` by hand (the gateway side); when Ink sends it, only once a command+ ran, is covered by ``ui-tui/src/__tests__/canonicalCommandObserve.test.ts``."""from hermes_cli.gateway_client import GatewayClientErrorwith _gateway(tmp_path) as (proc, desc, home, work, _env, log, _peer):wire = _Wire(home, desc)diff --git a/ui-tui/src/__tests__/canonicalCommandObserve.test.ts b/ui-tui/src/__tests__/canonicalCommandObserve.test.tsindex b314cbb277e..37d6c021cec 100644--- a/ui-tui/src/__tests__/canonicalCommandObserve.test.ts+++ b/ui-tui/src/__tests__/canonicalCommandObserve.test.ts@@ -5,8 +5,8 @@ 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.+// command.dispatch). A registry command Ink runs itself is reported through `command.observe` once+// it ran, as the classic CLI reports its own; a refused one is not, and a forwarded one never twice.const flush = () => new Promise(resolve => setTimeout(resolve, 5))beforeEach(() => {@@ -14,7 +14,17 @@ beforeEach(() => {patchUiState({ sid: 'owner', info: { model: 'm', skills: {}, tools: {} } as any })})-function harness({ canonical = true, observe }: { canonical?: boolean; observe?: () => Promise<unknown> } = {}) {+function harness({+ busy = false,+ canonical = true,+ mutate,+ observe+}: {+ busy?: boolean+ canonical?: boolean+ mutate?: () => Promise<unknown>+ observe?: () => Promise<unknown>+} = {}) {const request = vi.fn(async (method: string) => {if (method === 'command.observe') {return observe ? observe() : { queued: true }@@ -24,6 +34,14 @@ function harness({ canonical = true, observe }: { canonical?: boolean; observe?:return { output: 'ok', type: 'exec' }}+ if (method === 'session.resume') {+ return { execution_generation: 1, revision: 1 }+ }++ if (method === 'session.mutate') {+ return mutate ? mutate() : { effort: 'high', execution_generation: 1 }+ }+return {}})@@ -34,7 +52,7 @@ function harness({ canonical = true, observe }: { canonical?: boolean; observe?:composer: { enqueue: vi.fn() },gateway: { gw, rpc: request },local: { getHistoryItems: () => [], getLastUserMsg: () => '', maybeWarn: vi.fn() },- session: { resumeById: vi.fn() },+ session: { guardBusySessionSwitch: vi.fn(() => busy), newSession: vi.fn(), 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)@@ -59,6 +77,63 @@ it('reports a registry command Ink answers itself, as typed, once', async () =>])})+it('reports /help, a bare /reasoning and /tools list, each once', async () => {+ const { observed, slash } = harness()++ slash('/help')+ slash('/reasoning')+ slash('/tools list')+ await flush()++ expect(observed()).toEqual([+ { arg: '', name: 'help', session_id: 'owner' },+ { arg: '', name: 'reasoning', session_id: 'owner' },+ { arg: 'list', name: 'tools', session_id: 'owner' }+ ])+})++it('reports nothing for /tools enable or disable, which the shared gateway refuses', async () => {+ const tools = harness()++ tools.slash('/tools disable web')+ tools.slash('/tools enable web')+ await flush()+ expect(tools.sys).toHaveBeenCalled() // the "not available" line+ expect(tools.observed()).toEqual([])+})++it('reports nothing for a /new the busy guard rejects', async () => {+ const busy = harness({ busy: true })++ busy.slash('/new')+ await flush()+ expect(busy.observed()).toEqual([])++ patchUiState({ destructiveSlashConfirm: false })+ const idle = harness()++ idle.slash('/new')+ await flush()+ expect(idle.observed()).toEqual([{ arg: '', name: 'new', session_id: 'owner' }])+})++it('reports a gateway-backed /reasoning level only once the gateway accepts it', async () => {+ const refused = harness({+ mutate: () => Promise.reject(new JsonRpcGatewayError('busy', { code: 4009, data: { reason: 'busy' } }))+ })++ refused.slash('/reasoning high')+ await flush()+ expect(refused.request).toHaveBeenCalledWith('session.mutate', expect.objectContaining({ operation: 'reasoning' }))+ expect(refused.observed()).toEqual([])++ const accepted = harness()++ accepted.slash('/reasoning high')+ await flush()+ expect(accepted.observed()).toEqual([{ arg: 'high', name: 'reasoning', session_id: 'owner' }])+})+it('never reports a command Ink sends to the gateway, which fires pre_command itself', async () => {const { observed, request, slash } = harness()diff --git a/ui-tui/src/app/createSlashHandler.ts b/ui-tui/src/app/createSlashHandler.tsindex e287e1d0f44..d1a6f295790 100644--- a/ui-tui/src/app/createSlashHandler.ts+++ b/ui-tui/src/app/createSlashHandler.ts@@ -9,7 +9,7 @@ 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 { SlashCommand, SlashRunCtx } from './slash/types.js'+import type { SlashRunCtx } from './slash/types.js'import { captureDestination, isCurrentDestination } from './submissionDestination.js'import { getUiState } from './uiStore.js'import {@@ -33,43 +33,22 @@ 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+/** `SlashRunCtx.ran`: the shared gateway fires `pre_command` for the commands it runs (`slash.exec`,+ * `command.dispatch`). A recognized command Ink runs itself is reported the way the classic CLI+ * reports its own (`command.observe`, plain data, not awaited) once the handler says it ran: a read+ * when it answers, a gateway mutation once accepted. A refusal never calls it, and neither does a+ * forward, so no command fires twice. At most once per typed command; the gateway refuses a name+ * it does not recognize. */+function observer(gw: GatewayClient, name: string, arg: string, sid: null | string): () => void {+ let sent = false++ return () => {+ if (sent || !gw?.isCanonical || !sid || observeUnsupported.has(gw)) {+ return}- }- if (!forwarded) {- gw.request('command.observe', { arg, name, session_id: runCtx.sid }).catch((e: unknown) => {+ sent = true+ gw.request('command.observe', { arg, name, session_id: sid }).catch((e: unknown) => {if ((e as { code?: number })?.code === RPC_UNKNOWN_METHOD || /unknown_method/.test(rpcErrorMessage(e))) {observeUnsupported.add(gw)}@@ -122,7 +101,7 @@ export function createSlashHandler(ctx: SlashHandlerContext): SlashHandler {if (found) {countTyped()// 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)+ found.run(parsed.arg, typed ? { ...runCtx, ran: observer(gw, parsed.name, parsed.arg, sid) } : runCtx, cmd)return true}diff --git a/ui-tui/src/app/slash/canonicalSessionCommands.ts b/ui-tui/src/app/slash/canonicalSessionCommands.tsindex ebd6427654b..efad1faee2e 100644--- a/ui-tui/src/app/slash/canonicalSessionCommands.ts+++ b/ui-tui/src/app/slash/canonicalSessionCommands.ts@@ -128,10 +128,15 @@ export function canonicalReasoning(payload: { scope?: string; value: string }, c}void mutateCanonical(ctx.gateway.gw, ctx.sid!, 'reasoning', { effort }, ctx.stale)- .then(- mutation =>- mutation?.result && !ctx.stale() && ctx.transcript.sys(t('slashCmd.session.reasoning.current', effort))- )+ .then(mutation => {+ if (mutation?.result) {+ ctx.ran?.() // the owner accepted it; a refusal rejects and reports nothing++ if (!ctx.stale()) {+ ctx.transcript.sys(t('slashCmd.session.reasoning.current', effort))+ }+ }+ }).catch(ctx.guardedErr)return truediff --git a/ui-tui/src/app/slash/commands/core.ts b/ui-tui/src/app/slash/commands/core.tsindex 6a733ab64f7..29350cf4e22 100644--- a/ui-tui/src/app/slash/commands/core.ts+++ b/ui-tui/src/app/slash/commands/core.ts@@ -123,6 +123,7 @@ export const coreCommands: SlashCommand[] = [)ctx.transcript.panel(ctx.ui.theme.brand.helpHeader, sections)+ ctx.ran?.()}},@@ -196,6 +197,7 @@ export const coreCommands: SlashCommand[] = [const requestedTitle = isNew ? arg.trim() : ''const commit = () => {+ ctx.ran?.()patchUiState({ status: t('slashCmd.core.clear.forgingSession') })ctx.session.newSession(isNew ? t('slashCmd.core.clear.newSessionStarted') : undefined,@@ -546,6 +548,8 @@ export const coreCommands: SlashCommand[] = [// transcript so `/history` actually reflects what the user just did.const items = ctx.local.getHistoryItems().filter(m => m.role === 'user' || m.role === 'assistant')+ ctx.ran?.()+if (!items.length) {return ctx.transcript.sys(t('slashCmd.core.history.noConversation'))}diff --git a/ui-tui/src/app/slash/commands/ops.ts b/ui-tui/src/app/slash/commands/ops.tsindex 61805180bfe..fba074b6aaf 100644--- a/ui-tui/src/app/slash/commands/ops.ts+++ b/ui-tui/src/app/slash/commands/ops.ts@@ -784,9 +784,13 @@ export const opsCommands: SlashCommand[] = [if (ctx.sid && ctx.gateway.gw?.isCanonical) {// The shared gateway freezes a session's toolsets at launch (the classic CLI refuses the// same change): say so instead of answering enable/disable with the unchanged list.- return subcommand === 'disable' || subcommand === 'enable'- ? ctx.transcript.sys(t('canonical.controls.notAvailable', `tools ${subcommand}`))- : canonicalTools(ctx)+ if (subcommand === 'disable' || subcommand === 'enable') {+ return ctx.transcript.sys(t('canonical.controls.notAvailable', `tools ${subcommand}`))+ }++ ctx.ran?.()++ return canonicalTools(ctx)}if (subcommand !== 'disable' && subcommand !== 'enable') {diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.tsindex 8cd93be1d49..d79649c4ec4 100644--- a/ui-tui/src/app/slash/commands/session.ts+++ b/ui-tui/src/app/slash/commands/session.ts@@ -634,6 +634,8 @@ export const sessionCommands: SlashCommand[] = [name: 'reasoning',run: (arg, ctx) => {if (!arg) {+ ctx.ran?.()+return ctx.gateway.rpc<ConfigGetValueResponse>('config.get', { key: 'reasoning', session_id: ctx.sid }).then(@@ -789,6 +791,8 @@ export const sessionCommands: SlashCommand[] = [name: 'usage',run: (_arg, ctx) => {if (ctx.sid && ctx.gateway.gw?.isCanonical) {+ ctx.ran?.()+return canonicalUsage(ctx)}diff --git a/ui-tui/src/app/slash/types.ts b/ui-tui/src/app/slash/types.tsindex bbd187a23b3..9d540067da1 100644--- a/ui-tui/src/app/slash/types.ts+++ b/ui-tui/src/app/slash/types.ts@@ -6,6 +6,9 @@ export interface SlashRunCtx extends SlashHandlerContext {flight: numberguarded: <T>(fn: (r: T) => void) => (r: null | T) => voidguardedErr: (e: unknown) => void+ /** A recognized command Ink runs itself calls this once it ran (`command.observe`, so the gateway+ * fires `pre_command`); never on a refusal or a forward. Absent off a typed command. */+ ran?: () => voidsid: null | stringslashFlightRef: MutableRefObject<number>stale: () => booleandiff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 405677ed4fe..93696389de9 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 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`); each delivery waits on a thread of its own, never a worker shared with other sessions or the event loop's executor. 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 runs itself is reported to the gateway (`command.observe`) once it has run (a TUI command that changes the session through the gateway, once the gateway accepts the change), and the gateway fires it there after replying, so neither loads plugin code; one either client refuses fires nothing. 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`); each delivery waits on a thread of its own, never a worker shared with other sessions or the event loop's executor. 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. |