Skip to content

The agent that grows with you

refactor(slash): delete the dead web slash re-implementation; one slash parser + command.dispatch narrowing in @hermes/shared

teknium1057c2c85fce6
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
index 4b04f6925cf..7692cf60cd9 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
@@ -7,10 +7,10 @@ import '@/store/suggestion-providers/mcp'
import '@/store/suggestion-providers/skill'
import { useAui, useAuiState, useComposerRuntime } from '@assistant-ui/react'
+import { SLASH_COMMAND_RE } from '@hermes/shared'
import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
-import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
import {
type ComposerAttachment,
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index 30d016bdb91..f1f18ea115f 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@ -1,7 +1,7 @@
+import { SLASH_COMMAND_RE } from '@hermes/shared'
import { type RefObject, useLayoutEffect, useRef } from 'react'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
-import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
import { triggerHaptic } from '@/lib/haptics'
import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
import { clearSessionDraft, type ComposerAttachment } from '@/store/composer'
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 5759cf484e5..c2dc8c7a2d9 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -9,12 +9,12 @@
*/
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
+import { SLASH_COMMAND_RE } from '@hermes/shared'
import { useCallback, useMemo, useRef } from 'react'
import type { ClientSessionState } from '@/app/types'
import { useI18n } from '@/i18n'
import { textPart } from '@/lib/chat-messages'
-import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
import { triggerHaptic } from '@/lib/haptics'
import { clearClarifyRequest } from '@/store/clarify'
import type { ComposerAttachment } from '@/store/composer'
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index 6831eecb128..63d346a5914 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@ -1,5 +1,6 @@
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
import { JsonRpcGatewayError } from '@hermes/shared'
+import { SLASH_COMMAND_RE } from '@hermes/shared'
import { stripAnsi } from '@hermes/shared/ansi'
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
@@ -7,7 +8,7 @@ import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
import { transcribeAudio } from '@/hermes'
import { useI18n } from '@/i18n'
import { type ChatMessage, textPart } from '@/lib/chat-messages'
-import { pathLabel, SLASH_COMMAND_RE } from '@/lib/chat-runtime'
+import { pathLabel } from '@/lib/chat-runtime'
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
import { triggerHaptic } from '@/lib/haptics'
import { setMutableRef } from '@/lib/mutable-ref'
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index a54a7bdfb6c..44dc819ffdc 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@ -1,10 +1,11 @@
import { skillInvocationText } from '@hermes/shared'
+import { parseCommandDispatch, parseSlashCommand } from '@hermes/shared'
import { type MutableRefObject, useCallback, useRef } from 'react'
import { getProfiles } from '@/hermes'
import type { Translations } from '@/i18n'
import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'
-import { parseCommandDispatch, parseSlashCommand, sessionTitle } from '@/lib/chat-runtime'
+import { sessionTitle } from '@/lib/chat-runtime'
import {
type CommandsCatalogLike,
type DesktopActionId,
diff --git a/apps/desktop/src/app/types.ts b/apps/desktop/src/app/types.ts
index 57e85a0a9ca..1236178bfc5 100644
--- a/apps/desktop/src/app/types.ts
+++ b/apps/desktop/src/app/types.ts
@@ -122,46 +122,6 @@ export interface HandoffFailResponse {
state?: string
}
-export interface ExecCommandDispatchResponse {
- type: 'exec' | 'plugin'
- output?: string
-}
-
-export interface AliasCommandDispatchResponse {
- type: 'alias'
- target: string
-}
-
-export interface SkillCommandDispatchResponse {
- type: 'skill'
- name: string
- message?: string
- /** The invocation the UI renders (`/work fix the leak`). `message` is the
- * expanded skill body — model-facing scaffolding no surface may show. */
- display?: string
-}
-
-export interface SendCommandDispatchResponse {
- type: 'send'
- message: string
- notice?: string
- /** Set for a skill-bundle send: see SkillCommandDispatchResponse.display. */
- display?: string
-}
-
-export interface PrefillCommandDispatchResponse {
- type: 'prefill'
- message: string
- notice?: string
-}
-
-export type CommandDispatchResponse =
- | ExecCommandDispatchResponse
- | AliasCommandDispatchResponse
- | SkillCommandDispatchResponse
- | SendCommandDispatchResponse
- | PrefillCommandDispatchResponse
-
export type SidebarNavId = 'artifacts' | 'command-center' | 'cron' | 'messaging' | 'new-session' | 'settings' | 'skills'
export interface SidebarNavItem {
diff --git a/apps/desktop/src/lib/chat-runtime.test.ts b/apps/desktop/src/lib/chat-runtime.test.ts
index 39f4a507735..2a8c9bc7962 100644
--- a/apps/desktop/src/lib/chat-runtime.test.ts
+++ b/apps/desktop/src/lib/chat-runtime.test.ts
@@ -11,8 +11,6 @@ import {
createToolMergeCache,
messageCreatedAt,
optimisticAttachmentRef,
- parseCommandDispatch,
- parseSlashCommand,
toRuntimeMessage
} from './chat-runtime'
@@ -129,72 +127,6 @@ describe('coerceThinkingText', () => {
})
})
-describe('parseCommandDispatch', () => {
- it('keeps the notice on a send directive (e.g. /goal set)', () => {
- // The backend's /goal set returns {type:send, notice:"⊙ Goal set …", message}.
- // Dropping the notice made /goal look like it did nothing in the desktop app.
- const parsed = parseCommandDispatch({ type: 'send', notice: '⊙ Goal set', message: 'do the thing' })
-
- expect(parsed).toEqual({ type: 'send', message: 'do the thing', notice: '⊙ Goal set' })
- })
-
- it('keeps message-only send directives working (no notice)', () => {
- expect(parseCommandDispatch({ type: 'send', message: 'hi' })).toEqual({
- type: 'send',
- message: 'hi',
- notice: undefined
- })
- })
-
- it('parses a prefill directive with its notice (e.g. /undo)', () => {
- const parsed = parseCommandDispatch({ type: 'prefill', notice: 'backed up 1 turn', message: 'edit me' })
-
- expect(parsed).toEqual({ type: 'prefill', message: 'edit me', notice: 'backed up 1 turn' })
- })
-
- it('rejects a prefill directive missing its message', () => {
- expect(parseCommandDispatch({ type: 'prefill', notice: 'x' })).toBeNull()
- })
-})
-
-describe('parseSlashCommand', () => {
- it('parses a single-line command', () => {
- expect(parseSlashCommand('/some-skill do something')).toEqual({
- arg: 'do something',
- name: 'some-skill'
- })
- })
-
- it('keeps a multiline arg intact instead of failing the whole parse (#41323)', () => {
- expect(parseSlashCommand('/goal Write a Python script\nthat prints Hello World')).toEqual({
- arg: 'Write a Python script\nthat prints Hello World',
- name: 'goal'
- })
- })
-
- it('parses a skill command with a long pasted multi-paragraph context (#55510)', () => {
- const context = 'summarize this:\n\nparagraph one\nparagraph two\n\nparagraph three'
-
- expect(parseSlashCommand(`/some-skill ${context}`)).toEqual({
- arg: context,
- name: 'some-skill'
- })
- })
-
- it('takes the name across a newline boundary like the CLI and gateway (split on any whitespace)', () => {
- expect(parseSlashCommand('/goal\npasted block')).toEqual({ arg: 'pasted block', name: 'goal' })
- })
-
- it('keeps truly empty slash input empty', () => {
- expect(parseSlashCommand('/')).toEqual({ arg: '', name: '' })
- expect(parseSlashCommand('/ ')).toEqual({ arg: '', name: '' })
- })
-
- it('does not treat text after horizontal whitespace as a command name (CLI parity)', () => {
- expect(parseSlashCommand('/ some words')).toEqual({ arg: '', name: '' })
- })
-})
-
describe('attachmentId', () => {
it('normalizes a trailing slash on a url so a re-attach dedupes (#59305 P2)', () => {
expect(attachmentId('url', 'https://example.com/a')).toBe(attachmentId('url', 'https://example.com/a/'))
diff --git a/apps/desktop/src/lib/chat-runtime.ts b/apps/desktop/src/lib/chat-runtime.ts
index 7c048a5ec60..6fed15ba61b 100644
--- a/apps/desktop/src/lib/chat-runtime.ts
+++ b/apps/desktop/src/lib/chat-runtime.ts
@@ -2,14 +2,13 @@ import type { ThreadMessage } from '@assistant-ui/react'
import type { ModelOptionsResponse } from '@hermes/shared'
import type { QuickModelOption } from '@/app/chat/composer/types'
-import type { ClientSessionState, CommandDispatchResponse } from '@/app/types'
+import type { ClientSessionState } from '@/app/types'
import { formatRefValue } from '@/components/assistant-ui/directive-text'
import { type ChatMessage, type ChatMessagePart, chatMessageText, textPart } from '@/lib/chat-messages'
import { normalize } from '@/lib/text'
import type { ComposerAttachment } from '@/store/composer'
import type { SessionInfo } from '@/types/hermes'
-export const SLASH_COMMAND_RE = /^\/[^\s/]*(?:\s|$)/
export { BUILTIN_PERSONALITIES } from '@/lib/personalities'
const THINKING_STATUS_PREFIX_RE =
@@ -296,52 +295,6 @@ export function normalizePersonalityValue(value: string): string {
return !trimmed || trimmed === 'default' || trimmed === 'none' ? '' : trimmed
}
-export function parseSlashCommand(command: string) {
- // `[\s\S]*` (not `.*`): the arg may span newlines — `/goal <multi-line text>`
- // or a skill command with a long pasted context. The old `.*$` regex failed
- // the whole match on any newline, so every multiline slash command parsed as
- // an empty name and got swallowed (#41323, #55510). The backend and CLI both
- // split on any whitespace (`split(maxsplit=1)`), so this is the parity fix.
- const match = command.replace(/^\/+/, '').match(/^(\S+)([\s\S]*)$/)
-
- return match ? { name: match[1], arg: match[2].trim() } : { name: '', arg: '' }
-}
-
-export function parseCommandDispatch(raw: unknown): CommandDispatchResponse | null {
- if (!raw || typeof raw !== 'object') {
- return null
- }
-
- const row = raw as Record<string, unknown>
- const str = (value: unknown) => (typeof value === 'string' ? value : undefined)
-
- switch (row.type) {
- case 'exec':
-
- case 'plugin':
- return { type: row.type, output: str(row.output) }
-
- case 'alias':
- return typeof row.target === 'string' ? { type: 'alias', target: row.target } : null
-
- case 'skill':
- return typeof row.name === 'string'
- ? { type: 'skill', name: row.name, message: str(row.message), display: str(row.display) }
- : null
-
- case 'send':
- return typeof row.message === 'string'
- ? { type: 'send', message: row.message, notice: str(row.notice), display: str(row.display) }
- : null
-
- case 'prefill':
- return typeof row.message === 'string' ? { type: 'prefill', message: row.message, notice: str(row.notice) } : null
-
- default:
- return null
- }
-}
-
export function quickModelOptions(
data: ModelOptionsResponse | undefined,
currentProvider: string,
diff --git a/apps/desktop/src/lib/draft-title.ts b/apps/desktop/src/lib/draft-title.ts
index bd9f2f221d2..1278c1d34f5 100644
--- a/apps/desktop/src/lib/draft-title.ts
+++ b/apps/desktop/src/lib/draft-title.ts
@@ -1,4 +1,4 @@
-import { SLASH_COMMAND_RE } from './chat-runtime'
+import { SLASH_COMMAND_RE } from '@hermes/shared'
/** Matches `agent/title_generator.py`'s MAX_DERIVED_TITLE_CHARS, so a draft
* doesn't visibly reflow the moment the backend's derived title replaces it. */
diff --git a/apps/desktop/src/store/composer-queue.ts b/apps/desktop/src/store/composer-queue.ts
index f51828f87d0..09e64832b84 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -1,7 +1,6 @@
+import { SLASH_COMMAND_RE } from '@hermes/shared'
import { atom } from 'nanostores'
-import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
-
import type { ComposerAttachment } from './composer'
export interface QueuedPromptEntry {
diff --git a/apps/shared/package.json b/apps/shared/package.json
index 3aa4faa0ec7..1863917a580 100644
--- a/apps/shared/package.json
+++ b/apps/shared/package.json
@@ -18,7 +18,8 @@
"./model-search-text": "./src/model-search-text.ts",
"./reasoning-effort": "./src/reasoning-effort.ts",
"./reconnect-backoff": "./src/reconnect-backoff.ts",
- "./skin": "./src/skin.ts"
+ "./skin": "./src/skin.ts",
+ "./slash": "./src/slash.ts"
},
"types": "./src/index.ts",
"scripts": {
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index 8f3a6cc7b88..8c77b9de3a0 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -154,6 +154,19 @@ export {
type SkinColors,
type SkinColorToken
} from './skin'
+export {
+ type AliasCommandDispatchResponse,
+ type CommandDispatchResponse,
+ type ExecCommandDispatchResponse,
+ looksLikeSlashCommand,
+ parseCommandDispatch,
+ type ParsedSlashCommand,
+ parseSlashCommand,
+ type PrefillCommandDispatchResponse,
+ type SendCommandDispatchResponse,
+ type SkillCommandDispatchResponse,
+ SLASH_COMMAND_RE
+} from './slash'
export {
backgroundMaterialFor,
clampIntensity,
diff --git a/apps/shared/src/slash.test.ts b/apps/shared/src/slash.test.ts
new file mode 100644
index 00000000000..a990ab1a3b9
--- /dev/null
+++ b/apps/shared/src/slash.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest'
+
+import { looksLikeSlashCommand, parseCommandDispatch, parseSlashCommand } from './slash'
+
+describe('parseSlashCommand', () => {
+ it('splits the name off a single separator and lower-cases it', () => {
+ expect(parseSlashCommand('/cron add daily')).toEqual({ arg: 'add daily', name: 'cron' })
+ expect(parseSlashCommand('/Exit ')).toEqual({ arg: '', name: 'exit' })
+ })
+
+ it('keeps a multi-line argument byte-for-byte (#41323, #55510)', () => {
+ const arg = 'first line\nsecond line\n\n indented tail'
+
+ expect(parseSlashCommand(`/pr-triage ${arg}`)).toEqual({ arg, name: 'pr-triage' })
+ expect(parseSlashCommand('/goal ship it').arg).toBe('ship it')
+ })
+
+ it('takes the name across a newline boundary like the CLI and gateway (split on any whitespace)', () => {
+ expect(parseSlashCommand('/goal\npasted block')).toEqual({ arg: 'pasted block', name: 'goal' })
+ })
+
+ it('treats a bare or space-separated slash as no command (CLI parity)', () => {
+ expect(parseSlashCommand('/')).toEqual({ arg: '', name: '' })
+ expect(parseSlashCommand('/ ')).toEqual({ arg: '', name: '' })
+ expect(parseSlashCommand('/ some words')).toEqual({ arg: '', name: '' })
+ })
+
+ it('recognises a command only at position 0 with a single bare segment', () => {
+ expect(looksLikeSlashCommand('/help')).toBe(true)
+ expect(looksLikeSlashCommand('/goal do it')).toBe(true)
+ expect(looksLikeSlashCommand('/usr/local/bin')).toBe(false)
+ expect(looksLikeSlashCommand('run /clean')).toBe(false)
+ })
+})
+
+describe('parseCommandDispatch', () => {
+ it('parses every variant of the command.dispatch union and keeps notice/display', () => {
+ expect(parseCommandDispatch({ type: 'exec', output: 'hi' })).toEqual({ type: 'exec', output: 'hi' })
+ expect(parseCommandDispatch({ type: 'plugin' })).toEqual({ type: 'plugin', output: undefined })
+ expect(parseCommandDispatch({ type: 'alias', target: 'help' })).toEqual({ type: 'alias', target: 'help' })
+ expect(parseCommandDispatch({ type: 'skill', name: 'x', message: 'do', display: '/x' })).toEqual({
+ type: 'skill',
+ name: 'x',
+ message: 'do',
+ display: '/x'
+ })
+ // /goal set answers {type:send, notice, message}; dropping the notice once
+ // made /goal look like it did nothing on the desktop.
+ expect(parseCommandDispatch({ type: 'send', notice: '⊙ Goal set', message: 'do the thing' })).toEqual({
+ type: 'send',
+ message: 'do the thing',
+ notice: '⊙ Goal set',
+ display: undefined
+ })
+ expect(parseCommandDispatch({ type: 'prefill', message: 'edit me', notice: '↶ rewound' })).toEqual({
+ type: 'prefill',
+ message: 'edit me',
+ notice: '↶ rewound'
+ })
+ })
+
+ it('rejects malformed payloads', () => {
+ expect(parseCommandDispatch(null)).toBeNull()
+ expect(parseCommandDispatch([{ type: 'exec' }])).toBeNull()
+ expect(parseCommandDispatch({ type: 'alias' })).toBeNull()
+ expect(parseCommandDispatch({ type: 'skill', name: 1 })).toBeNull()
+ expect(parseCommandDispatch({ type: 'send' })).toBeNull()
+ expect(parseCommandDispatch({ type: 'send', message: 42 })).toBeNull()
+ expect(parseCommandDispatch({ type: 'prefill', notice: 'x' })).toBeNull()
+ expect(parseCommandDispatch({ type: 'nope' })).toBeNull()
+ })
+})
diff --git a/apps/shared/src/slash.ts b/apps/shared/src/slash.ts
new file mode 100644
index 00000000000..5f365d3e407
--- /dev/null
+++ b/apps/shared/src/slash.ts
@@ -0,0 +1,117 @@
+/**
+ * The slash-command wire contract every TypeScript surface shares: how a typed
+ * line splits into `name` + `arg`, and the `command.dispatch` response union
+ * (`tui_gateway/methods_tools.py::command.dispatch`). One parser, so a fix such
+ * as the multi-line argument bug (#41323, #55510) reaches desktop and TUI at
+ * once instead of landing in whichever copy the reporter happened to use.
+ */
+
+/** A slash COMMAND invocation: `/` at position 0, a bare name, then whitespace
+ * or end. `/usr/local` (second slash) and `run /clean` (not at 0) are prose. */
+export const SLASH_COMMAND_RE = /^\/[^\s/]*(?:\s|$)/
+
+export const looksLikeSlashCommand = (text: string): boolean => SLASH_COMMAND_RE.test(text)
+
+// `[\s\S]*` (not `.*`): the arg may span newlines — `/goal <multi-line text>`
+// or a skill command with a long pasted context. A `.*$` regex fails the
+// whole match on any newline, so every multiline slash command parsed as an
+// empty name and got swallowed. The backend and CLI both split on any
+// whitespace (`split(maxsplit=1)`), so `\S+` for the name is the parity rule.
+// Only the separator between name and argument is whitespace the parser owns;
+// the argument's interior (runs of spaces, indentation, blank lines) survives
+// verbatim — flattening it once turned every pasted diff into one line.
+const SLASH_PARTS_RE = /^(\S+)([\s\S]*)$/
+
+export interface ParsedSlashCommand {
+ /** Argument text with the outer whitespace removed; interior kept verbatim. */
+ arg: string
+ /** Lower-cased command name without the slash; '' for `/`, `/ `, `/ words`. */
+ name: string
+}
+
+/** Split `/name arg…` the way the backend does. The name is lower-cased because
+ * every consumer (`hermes_cli.commands.resolve_command`, `slash.exec`) is
+ * case-insensitive; keeping the typed case only made surfaces disagree. */
+export function parseSlashCommand(command: string): ParsedSlashCommand {
+ const match = SLASH_PARTS_RE.exec(command.replace(/^\/+/, ''))
+
+ return match ? { arg: match[2]!.trim(), name: match[1]!.toLowerCase() } : { arg: '', name: '' }
+}
+
+export interface ExecCommandDispatchResponse {
+ output?: string
+ type: 'exec' | 'plugin'
+}
+
+export interface AliasCommandDispatchResponse {
+ target: string
+ type: 'alias'
+}
+
+export interface SkillCommandDispatchResponse {
+ /** The invocation the UI renders (`/work fix the leak`). `message` is the
+ * expanded skill body — model-facing scaffolding no surface may show. */
+ display?: string
+ message?: string
+ name: string
+ type: 'skill'
+}
+
+export interface SendCommandDispatchResponse {
+ /** Set for a skill-bundle send: see SkillCommandDispatchResponse.display. */
+ display?: string
+ message: string
+ notice?: string
+ type: 'send'
+}
+
+export interface PrefillCommandDispatchResponse {
+ message: string
+ notice?: string
+ type: 'prefill'
+}
+
+export type CommandDispatchResponse =
+ | AliasCommandDispatchResponse
+ | ExecCommandDispatchResponse
+ | PrefillCommandDispatchResponse
+ | SendCommandDispatchResponse
+ | SkillCommandDispatchResponse
+
+const str = (value: unknown) => (typeof value === 'string' ? value : undefined)
+
+/** Narrow a raw `command.dispatch` result to the union, or null when the
+ * payload is malformed (missing required field, unknown `type`). */
+export function parseCommandDispatch(raw: unknown): CommandDispatchResponse | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return null
+ }
+
+ const row = raw as Record<string, unknown>
+
+ switch (row.type) {
+ case 'alias':
+ return typeof row.target === 'string' ? { target: row.target, type: 'alias' } : null
+
+ case 'exec':
+
+ case 'plugin':
+ return { output: str(row.output), type: row.type }
+
+ case 'prefill':
+ return typeof row.message === 'string' ? { message: row.message, notice: str(row.notice), type: 'prefill' } : null
+
+ case 'send':
+ return typeof row.message === 'string'
+ ? { display: str(row.display), message: row.message, notice: str(row.notice), type: 'send' }
+ : null
+
+ case 'skill':
+ return typeof row.name === 'string'
+ ? { display: str(row.display), message: str(row.message), name: row.name, type: 'skill' }
+ : null
+
+ default:
+ return null
+ }
+}
diff --git a/ui-tui/src/__tests__/asCommandDispatch.test.ts b/ui-tui/src/__tests__/asCommandDispatch.test.ts
deleted file mode 100644
index 5dac25fab7b..00000000000
--- a/ui-tui/src/__tests__/asCommandDispatch.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { asCommandDispatch } from '../lib/rpc.js'
-
-describe('asCommandDispatch', () => {
- it('parses exec, alias, skill, and send', () => {
- expect(asCommandDispatch({ type: 'exec', output: 'hi' })).toEqual({ type: 'exec', output: 'hi' })
- expect(asCommandDispatch({ type: 'alias', target: 'help' })).toEqual({ type: 'alias', target: 'help' })
- expect(asCommandDispatch({ type: 'skill', name: 'x', message: 'do' })).toEqual({
- type: 'skill',
- name: 'x',
- message: 'do'
- })
- expect(asCommandDispatch({ type: 'send', message: 'hello world' })).toEqual({
- type: 'send',
- message: 'hello world'
- })
- expect(asCommandDispatch({ type: 'prefill', message: 'edit me' })).toEqual({
- type: 'prefill',
- message: 'edit me'
- })
- expect(asCommandDispatch({ type: 'prefill', message: 'edit me', notice: '↶ rewound' })).toEqual({
- type: 'prefill',
- message: 'edit me',
- notice: '↶ rewound'
- })
- })
-
- it('rejects malformed payloads', () => {
- expect(asCommandDispatch(null)).toBeNull()
- expect(asCommandDispatch({ type: 'alias' })).toBeNull()
- expect(asCommandDispatch({ type: 'skill', name: 1 })).toBeNull()
- expect(asCommandDispatch({ type: 'send' })).toBeNull()
- expect(asCommandDispatch({ type: 'send', message: 42 })).toBeNull()
- expect(asCommandDispatch({ type: 'prefill' })).toBeNull()
- expect(asCommandDispatch({ type: 'prefill', message: 42 })).toBeNull()
- })
-})
diff --git a/ui-tui/src/__tests__/slashParity.test.ts b/ui-tui/src/__tests__/slashParity.test.ts
index c76be8efca1..4a335348846 100644
--- a/ui-tui/src/__tests__/slashParity.test.ts
+++ b/ui-tui/src/__tests__/slashParity.test.ts
@@ -2,10 +2,10 @@ import { execFileSync } from 'node:child_process'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { parseSlashCommand } from '@hermes/shared/slash'
import { describe, expect, it } from 'vitest'
import { findSlashCommand, SLASH_COMMANDS } from '../app/slash/registry.js'
-import { parseSlashCommand } from '../domain/slash.js'
type CommandRoute = 'fallback' | 'local' | 'native'
@@ -130,7 +130,6 @@ describe('parseSlashCommand argument fidelity', () => {
expect(parseSlashCommand(`/pr-triage ${arg}`)).toEqual({
arg,
- cmd: `/pr-triage ${arg}`,
name: 'pr-triage'
})
})
@@ -142,10 +141,9 @@ describe('parseSlashCommand argument fidelity', () => {
it('still splits the command name off a single separator', () => {
expect(parseSlashCommand('/cron add daily')).toEqual({
arg: 'add daily',
- cmd: '/cron add daily',
name: 'cron'
})
- expect(parseSlashCommand('/exit')).toEqual({ arg: '', cmd: '/exit', name: 'exit' })
- expect(parseSlashCommand('/exit ')).toEqual({ arg: '', cmd: '/exit ', name: 'exit' })
+ expect(parseSlashCommand('/exit')).toEqual({ arg: '', name: 'exit' })
+ expect(parseSlashCommand('/exit ')).toEqual({ arg: '', name: 'exit' })
})
})
diff --git a/ui-tui/src/app/createSlashHandler.ts b/ui-tui/src/app/createSlashHandler.ts
index 3a354c3ef20..75f19c7af51 100644
--- a/ui-tui/src/app/createSlashHandler.ts
+++ b/ui-tui/src/app/createSlashHandler.ts
@@ -1,6 +1,7 @@
-import { parseSlashCommand } from '../domain/slash.js'
+import { parseCommandDispatch, parseSlashCommand } from '@hermes/shared/slash'
+
import type { SlashExecResponse } from '../gatewayTypes.js'
-import { asCommandDispatch, rpcErrorMessage } from '../lib/rpc.js'
+import { rpcErrorMessage } from '../lib/rpc.js'
import { launchWidget } from '../sdk/host.js'
import { getWidgetApp } from '../sdk/registry.js'
@@ -97,7 +98,7 @@ export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string) => b
}
const handleDispatch = (raw: unknown): void => {
- const d = asCommandDispatch(raw)
+ const d = parseCommandDispatch(raw)
if (!d) {
return sys('error: invalid response: command.dispatch')
@@ -157,7 +158,7 @@ export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string) => b
return
}
- if (asCommandDispatch(r)) {
+ if (parseCommandDispatch(r)) {
return handleDispatch(r)
}
diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.ts
index 57ce9f60f9e..048f2f32406 100644
--- a/ui-tui/src/app/useSubmission.ts
+++ b/ui-tui/src/app/useSubmission.ts
@@ -1,8 +1,9 @@
+import { looksLikeSlashCommand, parseSlashCommand } from '@hermes/shared/slash'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
import { TYPING_IDLE_MS } from '../config/timing.js'
import { expandTokens } from '../domain/attachments.js'
-import { completionToApplyOnSubmit, looksLikeSlashCommand, parseSlashCommand } from '../domain/slash.js'
+import { completionToApplyOnSubmit } from '../domain/slash.js'
import type { GatewayClient } from '../gatewayClient.js'
import type { SessionSteerResponse, ShellExecResponse } from '../gatewayTypes.js'
import { queueItem, type QueueItem } from '../hooks/useQueue.js'
diff --git a/ui-tui/src/domain/slash.ts b/ui-tui/src/domain/slash.ts
index 3b24d1e7a34..cf9bad368e9 100644
--- a/ui-tui/src/domain/slash.ts
+++ b/ui-tui/src/domain/slash.ts
@@ -8,8 +8,6 @@ export const sessionScopedModelArg = (value: string) => {
return kept.length ? `${kept.join(' ')} --session` : ''
}
-export const looksLikeSlashCommand = (text: string) => /^\/[^\s/]*(?:\s|$)/.test(text)
-
// A `/` means two different things depending on where it sits:
//
// - At position 0 it's a COMMAND invocation the TUI executes
@@ -47,19 +45,6 @@ export const inlineSlashTrigger = (text: string): { query: string; start: number
return { query, start: text.length - query.length - 1 }
}
-// Only the separator between the command name and its argument is whitespace
-// the parser owns. Everything after it is the user's text and survives
-// verbatim: splitting the whole line on `\s+` and rejoining with a space
-// flattened every pasted diff, log, or PR thread into one run-on line before
-// the command ever saw it.
-const SLASH_PARTS_RE = /^(\S*)\s*([\s\S]*)$/
-
-export const parseSlashCommand = (cmd: string) => {
- const [, name = '', arg = ''] = SLASH_PARTS_RE.exec(cmd.slice(1)) ?? []
-
- return { arg, cmd, name: name.toLowerCase() }
-}
-
/**
* Apply a completion row to the current input, mirroring the editor's
* replace semantics: replace from `compReplace` with the row text, dropping
diff --git a/ui-tui/src/gatewayTypes.ts b/ui-tui/src/gatewayTypes.ts
index b19e915bd5f..a353a6e4f1f 100644
--- a/ui-tui/src/gatewayTypes.ts
+++ b/ui-tui/src/gatewayTypes.ts
@@ -69,13 +69,6 @@ export type {
UsageModelData
} from '@hermes/shared/billing'
-export type CommandDispatchResponse =
- | { output?: string; type: 'exec' | 'plugin' }
- | { target: string; type: 'alias' }
- | { display?: string; message?: string; name: string; type: 'skill' }
- | { display?: string; message: string; notice?: string; type: 'send' }
- | { message: string; notice?: string; type: 'prefill' }
-
// ── Config ───────────────────────────────────────────────────────────
export interface ConfigDisplayConfig {
diff --git a/ui-tui/src/hooks/useCompletion.ts b/ui-tui/src/hooks/useCompletion.ts
index bcbcb8ab638..a0ed0a52266 100644
--- a/ui-tui/src/hooks/useCompletion.ts
+++ b/ui-tui/src/hooks/useCompletion.ts
@@ -1,8 +1,9 @@
+import { looksLikeSlashCommand } from '@hermes/shared/slash'
import { useEffect, useRef, useState } from 'react'
import type { CompletionItem } from '../app/interfaces.js'
import { rankSlashItems } from '../app/slash/fuzzyScore.js'
-import { inlineSlashTrigger, looksLikeSlashCommand } from '../domain/slash.js'
+import { inlineSlashTrigger } from '../domain/slash.js'
import type { GatewayClient } from '../gatewayClient.js'
import type { CompletionResponse } from '../gatewayTypes.js'
import { asRpcResult } from '../lib/rpc.js'
diff --git a/ui-tui/src/lib/rpc.ts b/ui-tui/src/lib/rpc.ts
index f54fb166f77..f95b4d4a05f 100644
--- a/ui-tui/src/lib/rpc.ts
+++ b/ui-tui/src/lib/rpc.ts
@@ -1,52 +1,7 @@
-import type { CommandDispatchResponse } from '../gatewayTypes.js'
-
export type RpcResult = Record<string, any>
export const asRpcResult = <T extends RpcResult = RpcResult>(value: unknown): T | null =>
!value || typeof value !== 'object' || Array.isArray(value) ? null : (value as T)
-export const asCommandDispatch = (value: unknown): CommandDispatchResponse | null => {
- const o = asRpcResult(value)
-
- if (!o || typeof o.type !== 'string') {
- return null
- }
-
- const t = o.type
-
- if (t === 'exec' || t === 'plugin') {
- return { type: t, output: typeof o.output === 'string' ? o.output : undefined }
- }
-
- if (t === 'alias' && typeof o.target === 'string') {
- return { type: 'alias', target: o.target }
- }
-
- const str = (value: unknown) => (typeof value === 'string' ? value : undefined)
-
- if (t === 'skill' && typeof o.name === 'string') {
- return { type: 'skill', name: o.name, message: str(o.message), display: str(o.display) }
- }
-
- if (t === 'send' && typeof o.message === 'string') {
- return {
- type: 'send',
- message: o.message,
- notice: str(o.notice),
- display: str(o.display)
- }
- }
-
- if (t === 'prefill' && typeof o.message === 'string') {
- return {
- type: 'prefill',
- message: o.message,
- notice: typeof o.notice === 'string' ? o.notice : undefined
- }
- }
-
- return null
-}
-
export const rpcErrorMessage = (err: unknown) =>
err instanceof Error && err.message ? err.message : typeof err === 'string' && err.trim() ? err : 'request failed'
diff --git a/web/src/components/SlashPopover.tsx b/web/src/components/SlashPopover.tsx
deleted file mode 100644
index e7198671bc9..00000000000
--- a/web/src/components/SlashPopover.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-import type { GatewayClient } from "@/lib/gatewayClient";
-import { ListItem } from "@nous-research/ui/ui/components/list-item";
-import { ChevronRight } from "lucide-react";
-import {
- forwardRef,
- useCallback,
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
-} from "react";
-
-/**
- * Slash-command autocomplete popover, rendered above the composer in ChatPage.
- * Mirrors the completion UX of the Ink TUI — type `/`, see matching commands,
- * arrow keys or click to select, Tab to apply, Enter to submit.
- *
- * The parent owns all keyboard handling via `ref.handleKey`, which returns
- * true when the popover consumed the event, so the composer's Enter/arrow
- * logic stays in one place.
- */
-
-export interface CompletionItem {
- display: string;
- text: string;
- meta?: string;
-}
-
-export interface SlashPopoverHandle {
- /** Returns true if the key was consumed by the popover. */
- handleKey(e: React.KeyboardEvent<HTMLTextAreaElement>): boolean;
-}
-
-interface Props {
- input: string;
- gw: GatewayClient | null;
- onApply(nextInput: string): void;
-}
-
-interface CompletionResponse {
- items?: CompletionItem[];
- replace_from?: number;
-}
-
-const DEBOUNCE_MS = 60;
-
-export const SlashPopover = forwardRef<SlashPopoverHandle, Props>(
- function SlashPopover({ input, gw, onApply }, ref) {
- const [items, setItems] = useState<CompletionItem[]>([]);
- const [selected, setSelected] = useState(0);
- const [replaceFrom, setReplaceFrom] = useState(1);
- const lastInputRef = useRef<string>("");
-
- // Debounced completion fetch. We never clear `items` in the effect body
- // (doing so would flag react-hooks/set-state-in-effect); instead the
- // render guard below hides stale items once the input stops matching.
- useEffect(() => {
- const trimmed = input ?? "";
-
- if (!gw || !trimmed.startsWith("/") || trimmed === lastInputRef.current) {
- if (!trimmed.startsWith("/")) lastInputRef.current = "";
- return;
- }
- lastInputRef.current = trimmed;
-
- const timer = window.setTimeout(async () => {
- if (lastInputRef.current !== trimmed) return;
- try {
- const r = await gw.request<CompletionResponse>("complete.slash", {
- text: trimmed,
- });
- if (lastInputRef.current !== trimmed) return;
- setItems(r?.items ?? []);
- setReplaceFrom(r?.replace_from ?? 1);
- setSelected(0);
- } catch {
- if (lastInputRef.current === trimmed) setItems([]);
- }
- }, DEBOUNCE_MS);
-
- return () => window.clearTimeout(timer);
- }, [input, gw]);
-
- const apply = useCallback(
- (item: CompletionItem) => {
- onApply(input.slice(0, replaceFrom) + item.text);
- },
- [input, replaceFrom, onApply],
- );
-
- // Only consume keys when the popover is actually visible. Stale items from
- // a previous slash prefix are ignored once the user deletes the "/".
- const visible = items.length > 0 && input.startsWith("/");
-
- useImperativeHandle(
- ref,
- () => ({
- handleKey: (e) => {
- if (!visible) return false;
-
- switch (e.key) {
- case "ArrowDown":
- e.preventDefault();
- setSelected((s) => (s + 1) % items.length);
- return true;
-
- case "ArrowUp":
- e.preventDefault();
- setSelected((s) => (s - 1 + items.length) % items.length);
- return true;
-
- case "Tab": {
- e.preventDefault();
- const item = items[selected];
- if (item) apply(item);
- return true;
- }
-
- case "Escape":
- e.preventDefault();
- setItems([]);
- return true;
-
- default:
- return false;
- }
- },
- }),
- [visible, items, selected, apply],
- );
-
- if (!visible) return null;
-
- return (
- <div
- className="absolute bottom-full left-0 right-0 mb-2 max-h-64 overflow-y-auto rounded-md border border-border bg-popover shadow-xl text-sm"
- role="listbox"
- >
- {items.map((it, i) => {
- const active = i === selected;
-
- return (
- <ListItem
- key={`${it.text}-${i}`}
- active={active}
- role="option"
- aria-selected={active}
- onMouseEnter={() => setSelected(i)}
- onClick={() => apply(it)}
- className="px-3 py-1.5"
- >
- <ChevronRight
- className={`h-3 w-3 shrink-0 ${active ? "text-primary" : "text-transparent"}`}
- />
-
- <span className="font-mono text-xs shrink-0 truncate">
- {it.display}
- </span>
-
- {it.meta && (
- <span className="text-xs text-text-tertiary truncate ml-auto">
- {it.meta}
- </span>
- )}
- </ListItem>
- );
- })}
- </div>
- );
- },
-);
diff --git a/web/src/lib/slashExec.ts b/web/src/lib/slashExec.ts
deleted file mode 100644
index c232f2aa4b1..00000000000
--- a/web/src/lib/slashExec.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * Slash command execution pipeline for the web chat.
- *
- * Mirrors the Ink TUI's createSlashHandler.ts:
- *
- * 1. Parse the command into `name` + `arg`.
- * 2. Try `slash.exec` — covers every registry-backed command the terminal
- * UI knows about (/help, /resume, /compact, /model, …). Output is
- * rendered into the transcript.
- * 3. If `slash.exec` errors (command rejected, unknown, or needs client
- * behaviour), fall back to `command.dispatch` which returns a typed
- * directive: `exec` | `plugin` | `alias` | `skill` | `send`.
- * 4. Each directive is dispatched to the appropriate callback.
- *
- * Keeping the pipeline here (instead of inline in ChatPage) lets future
- * clients (SwiftUI, Android) implement the same logic by reading the same
- * contract.
- */
-
-import type { GatewayClient } from "@/lib/gatewayClient";
-
-export interface SlashExecResponse {
- output?: string;
- warning?: string;
-}
-
-export type CommandDispatchResponse =
- | { type: "exec" | "plugin"; output?: string }
- | { type: "alias"; target: string }
- | { type: "skill"; name: string; message?: string }
- | { type: "send"; message: string };
-
-export interface SlashExecCallbacks {
- /** Render a transcript system message. */
- sys(text: string): void;
- /** Submit a user message to the agent (prompt.submit). */
- send(message: string): Promise<void> | void;
-}
-
-export interface SlashExecOptions {
- /** Raw command including the leading slash (e.g. "/model opus-4.6"). */
- command: string;
- /** Session id. If empty the call is still issued — some commands are session-less. */
- sessionId: string;
- gw: GatewayClient;
- callbacks: SlashExecCallbacks;
-}
-
-export type SlashExecResult = "done" | "sent" | "error";
-
-/**
- * Run a slash command. Returns the terminal state so callers can decide
- * whether to clear the composer, queue retries, etc.
- */
-export async function executeSlash({
- command,
- sessionId,
- gw,
- callbacks: { sys, send },
-}: SlashExecOptions): Promise<SlashExecResult> {
- const { name, arg } = parseSlash(command);
-
- if (!name) {
- sys("empty slash command");
- return "error";
- }
-
- // Primary dispatcher.
- try {
- const r = await gw.request<SlashExecResponse>("slash.exec", {
- command: command.replace(/^\/+/, ""),
- session_id: sessionId,
- });
- const body = r?.output || `/${name}: no output`;
- sys(r?.warning ? `warning: ${r.warning}\n${body}` : body);
- return "done";
- } catch {
- /* fall through to command.dispatch */
- }
-
- try {
- const d = parseCommandDispatch(
- await gw.request<unknown>("command.dispatch", {
- name,
- arg,
- session_id: sessionId,
- }),
- );
-
- if (!d) {
- sys("error: invalid response: command.dispatch");
- return "error";
- }
-
- switch (d.type) {
- case "exec":
- case "plugin":
- sys(d.output ?? "(no output)");
- return "done";
-
- case "alias":
- return executeSlash({
- command: `/${d.target}${arg ? ` ${arg}` : ""}`,
- sessionId,
- gw,
- callbacks: { sys, send },
- });
-
- case "skill":
- case "send": {
- const msg = d.message?.trim() ?? "";
- if (!msg) {
- sys(
- `/${name}: ${d.type === "skill" ? "skill payload missing message" : "empty message"}`,
- );
- return "error";
- }
- if (d.type === "skill") sys(`⚡ loading skill: ${d.name}`);
- await send(msg);
- return "sent";
- }
- }
- } catch (err) {
- sys(`error: ${err instanceof Error ? err.message : String(err)}`);
- return "error";
- }
-}
-
-export function parseSlash(command: string): { name: string; arg: string } {
- const m = command.replace(/^\/+/, "").match(/^(\S+)\s*(.*)$/);
- return m ? { name: m[1], arg: m[2].trim() } : { name: "", arg: "" };
-}
-
-function parseCommandDispatch(raw: unknown): CommandDispatchResponse | null {
- if (!raw || typeof raw !== "object") return null;
-
- const r = raw as Record<string, unknown>;
- const str = (v: unknown) => (typeof v === "string" ? v : undefined);
-
- switch (r.type) {
- case "exec":
- case "plugin":
- return { type: r.type, output: str(r.output) };
-
- case "alias":
- return typeof r.target === "string"
- ? { type: "alias", target: r.target }
- : null;
-
- case "skill":
- return typeof r.name === "string"
- ? { type: "skill", name: r.name, message: str(r.message) }
- : null;
-
- case "send":
- return typeof r.message === "string"
- ? { type: "send", message: r.message }
- : null;
-
- default:
- return null;
- }
-}