-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcommand-registry.ts
More file actions
796 lines (741 loc) · 24.3 KB
/
Copy pathcommand-registry.ts
File metadata and controls
796 lines (741 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
import { safeOpen } from '../utils/open-url'
import { handleAdsEnable, handleAdsDisable } from './ads'
import { handleCopyConversationCommand } from './copy-conversation'
import { handleHelpCommand } from './help'
import { handleImageCommand } from './image'
import { handleInitializationFlowLocally } from './init'
import {
collectProcessDiagnostics,
formatProcessDiagnostics,
} from './process-diagnostics'
import { buildInterviewPrompt, buildPlanPrompt, buildReviewPromptFromArgs, buildSkillPrompt } from './prompt-builders'
import { handleReasoningCommand } from './reasoning'
import { runBashCommand } from './router'
import { handleUsageCommand } from './usage'
import {
returnToFreebuffLanding,
getSessionBoundUserId,
} from '../hooks/use-freebuff-session'
import { releaseFreebuffSlot } from '../utils/freebuff-session-api'
import { clearSessionBinding } from '../utils/session-binding'
import { useFreebuffSessionStore } from '../state/freebuff-session-store'
import { useThemeStore } from '../hooks/use-theme'
import { LOGIN_WEBSITE_URL, WEBSITE_URL } from '../login/constants'
import { startNewChat } from '../project-files'
import { useChatStore } from '../state/chat-store'
import { stopActiveRun } from '../utils/active-run'
import { useFeedbackStore } from '../state/feedback-store'
import { useLoginStore } from '../state/login-store'
import { AGENT_MODES, END_SESSION_MESSAGE, IS_FREEBUFF } from '../utils/constants'
import { exitCliCleanly } from '../utils/exit-cleanly'
import { getSystemMessage, getUserMessage } from '../utils/message-history'
import { capturePendingAttachments } from '../utils/pending-attachments'
import { getSkillByName } from '../utils/skill-registry'
import type { MultilineInputHandle } from '../components/multiline-input'
import type { InputValue, PendingAttachment } from '../types/store'
import type { ChatMessage } from '../types/chat'
import type { SendMessageFn } from '../types/contracts/send-message'
import type { User } from '../utils/auth'
import type { AgentMode } from '../utils/constants'
import type { UseMutationResult } from '@tanstack/react-query'
export type RouterParams = {
agentMode: AgentMode
inputRef: React.MutableRefObject<MultilineInputHandle | null>
inputValue: string
isChainInProgressRef: React.MutableRefObject<boolean>
isStreaming: boolean
logoutMutation: UseMutationResult<boolean, Error, void, unknown>
streamMessageIdRef: React.MutableRefObject<string | null>
addToQueue: (message: string, attachments?: PendingAttachment[]) => void
/** Whether the message queue currently holds anything. Steering checks it
* so a mid-turn submit can't overtake earlier queued submissions. */
hasQueuedMessages?: () => boolean
clearMessages: () => void
saveToHistory: (message: string) => void
scrollToLatest: () => void
sendMessage: SendMessageFn
setCanProcessQueue: (value: React.SetStateAction<boolean>) => void
setInputFocused: (focused: boolean) => void
setInputValue: (
value: InputValue | ((prev: InputValue) => InputValue),
) => void
setIsAuthenticated: (value: React.SetStateAction<boolean | null>) => void
setMessages: (
value: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[]),
) => void
setUser: (value: React.SetStateAction<User | null>) => void
}
export type CommandResult = {
openFeedbackMode?: boolean
openPublishMode?: boolean
openChatHistory?: boolean
openReviewScreen?: boolean
openQueuePanel?: boolean
preSelectAgents?: string[]
} | void
export type CommandHandler = (
params: RouterParams,
args: string,
) => Promise<CommandResult> | CommandResult
export type CommandDefinition = {
name: string
aliases: string[]
handler: CommandHandler
/** Whether this command accepts arguments. Set automatically by the factory functions. */
acceptsArgs: boolean
}
/**
* Handler type for commands that don't accept arguments.
*/
type CommandHandlerNoArgs = (
params: RouterParams,
) => Promise<CommandResult> | CommandResult
/**
* Handler type for commands that accept arguments.
*/
type CommandHandlerWithArgs = (
params: RouterParams,
args: string,
) => Promise<CommandResult> | CommandResult
/**
* Configuration for defining a command that does NOT accept arguments.
*/
type CommandConfig = {
name: string
aliases?: string[]
handler: CommandHandlerNoArgs
}
/**
* Configuration for defining a command that accepts arguments.
*/
type CommandWithArgsConfig = {
name: string
aliases?: string[]
handler: CommandHandlerWithArgs
}
/**
* Factory for commands that do NOT accept arguments.
* Any args passed are gracefully ignored.
*
* @example
* defineCommand({
* name: 'new',
* aliases: ['n', 'clear'],
* handler: (params) => {
* params.setMessages(() => [])
* },
* })
*/
export function defineCommand(config: CommandConfig): CommandDefinition {
return {
name: config.name,
aliases: config.aliases ?? [],
acceptsArgs: false,
handler: (params) => {
// Args are gracefully ignored for commands that don't accept them
return config.handler(params)
},
}
}
/**
* Factory for commands that accept arguments.
* The handler receives both params and args.
*
* @example
* defineCommandWithArgs({
* name: 'bash',
* aliases: ['!'],
* handler: (params, args) => {
* if (args.trim()) {
* runBashCommand(args.trim())
* }
* },
* })
*/
export function defineCommandWithArgs(
config: CommandWithArgsConfig,
): CommandDefinition {
return {
name: config.name,
aliases: config.aliases ?? [],
acceptsArgs: true,
handler: config.handler,
}
}
const clearInput = (params: RouterParams) => {
params.setInputValue({ text: '', cursorPosition: 0, lastEditDueToNav: false })
}
const FREEBUFF_REMOVED_COMMANDS = new Set([
'ads:enable',
'ads:disable',
'usage',
'subscribe',
'image',
'publish',
'gpt-5-agent',
])
const FREEBUFF_ONLY_COMMANDS = new Set([
'plan',
'end-session',
'dashboard',
// Freebuff-only because the ladder it reads is the FREEBUFF catalog's, and
// the metadata it sets is honored only for free-mode traffic
// (isFreebuffOriginatedRequest). On Codebuff the command would take a value
// and silently drop it.
'reasoning',
])
const ALL_COMMANDS: CommandDefinition[] = [
defineCommand({
name: 'ads:enable',
handler: (params) => {
const { postUserMessage } = handleAdsEnable()
params.setMessages((prev) => postUserMessage(prev))
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
defineCommand({
name: 'ads:disable',
handler: (params) => {
const { postUserMessage } = handleAdsDisable()
params.setMessages((prev) => postUserMessage(prev))
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
defineCommand({
name: 'help',
aliases: ['h', '?'],
handler: async (params) => {
const { postUserMessage } = await handleHelpCommand()
params.setMessages((prev) => postUserMessage(prev))
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
defineCommand({
name: 'diagnostics',
aliases: ['diag', 'processes'],
handler: (params) => {
const diagnostics = formatProcessDiagnostics(collectProcessDiagnostics())
params.setMessages((prev) => [...prev, getSystemMessage(diagnostics)])
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
defineCommand({
name: 'copy',
aliases: ['copy-chat', 'export'],
handler: async (params) => {
await handleCopyConversationCommand(params)
},
}),
defineCommandWithArgs({
name: 'feedback',
aliases: ['bug', 'report'],
handler: (params, args) => {
const trimmedArgs = args.trim()
// If user provided feedback text directly, pre-populate the form
if (trimmedArgs) {
useFeedbackStore.getState().setFeedbackText(trimmedArgs)
useFeedbackStore.getState().setFeedbackCursor(trimmedArgs.length)
}
params.saveToHistory(params.inputValue.trim())
clearInput(params)
return { openFeedbackMode: true }
},
}),
defineCommandWithArgs({
name: 'bash',
aliases: ['!'],
handler: (params, args) => {
const trimmedArgs = args.trim()
// If user provided a command directly, execute it immediately
if (trimmedArgs) {
const commandWithBang = '!' + trimmedArgs
params.saveToHistory(commandWithBang)
clearInput(params)
runBashCommand(trimmedArgs)
return
}
// Otherwise enter bash mode
useChatStore.getState().setInputMode('bash')
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
defineCommand({
name: 'login',
aliases: ['signin'],
handler: (params) => {
params.setMessages((prev) => [
...prev,
getSystemMessage(
"You're already in the app. Use /logout to switch accounts.",
),
])
clearInput(params)
},
}),
defineCommandWithArgs({
name: 'logout',
aliases: ['signout'],
handler: (params, args) => {
// Check if a session is bound to this account. If so, require --force
// or ask the user to end the session first to prevent multi-account abuse.
const boundUserId = getSessionBoundUserId()
const force = args.trim() === '--force'
if (boundUserId && !force) {
params.setMessages((prev) => [
...prev,
getSystemMessage(
'You have an active session tied to this account. End it first with /end-session, or force logout with /logout --force.',
),
])
clearInput(params)
return
}
stopActiveRun('logout')
// When force-logging out with an active session, release the server-side
// slot and clear the binding before clearing credentials.
if (boundUserId && force) {
releaseFreebuffSlot().catch(() => {})
useFreebuffSessionStore.getState().setSessionBoundUserId(null)
clearSessionBinding()
}
const { resetLoginState } = useLoginStore.getState()
params.logoutMutation.mutate(undefined, {
onSettled: () => {
resetLoginState()
params.setMessages((prev) => [
...prev,
getSystemMessage('Logged out.'),
])
clearInput(params)
setTimeout(() => {
// The confirmation remains visible briefly; fence that window too
// before unmounting the authenticated runtime.
stopActiveRun('logout')
params.setUser(null)
params.setIsAuthenticated(false)
}, 300)
},
})
},
}),
defineCommand({
name: 'exit',
aliases: ['quit', 'q'],
handler: () => {
void exitCliCleanly()
},
}),
defineCommandWithArgs({
name: 'new',
aliases: ['n', 'clear', 'c', 'reset'],
handler: (params, args) => {
const trimmedArgs = args.trim()
// Abort any in-flight run BEFORE clearing state and rotating the chat
// id: an orphaned run would keep streaming after the switch and its
// late checkpoints/final save would persist the old conversation's
// state under the new chat (or vice versa).
stopActiveRun('new-chat')
// Clear the conversation and rotate to a fresh chat directory, so the
// next message doesn't overwrite the previous conversation's history
params.setMessages(() => [])
params.clearMessages()
startNewChat()
params.saveToHistory(params.inputValue.trim())
clearInput(params)
// If user provided a message, send it as the first message in the new chat
if (trimmedArgs) {
// Re-enable queue processing so the message can be sent
params.setCanProcessQueue(true)
params.sendMessage({
content: trimmedArgs,
agentMode: params.agentMode,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
} else {
// Only disable queue if we're not sending a message
params.setCanProcessQueue(false)
}
},
}),
defineCommand({
name: 'init',
handler: async (params) => {
const { postUserMessage } = handleInitializationFlowLocally()
const trimmed = params.inputValue.trim()
params.saveToHistory(trimmed)
clearInput(params)
// Check streaming/queue state
if (
params.isStreaming ||
params.streamMessageIdRef.current ||
params.isChainInProgressRef.current
) {
const pendingAttachments = capturePendingAttachments()
params.addToQueue(trimmed, pendingAttachments)
params.setInputFocused(true)
params.inputRef.current?.focus()
return
}
params.sendMessage({
content: trimmed,
agentMode: params.agentMode,
postUserMessage,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
},
}),
defineCommand({
name: 'usage',
aliases: ['credits'],
handler: async (params) => {
const { postUserMessage } = await handleUsageCommand()
params.setMessages((prev) => postUserMessage(prev))
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
defineCommand({
name: 'subscribe',
aliases: ['strong', 'sub', 'buy-credits'],
handler: (params) => {
safeOpen(WEBSITE_URL + '/subscribe')
clearInput(params)
},
}),
defineCommand({
name: 'dashboard',
// Freebuff-only (see FREEBUFF_ONLY_COMMANDS): the hub is a Freebuff web
// surface, and Codebuff has its own credits-shaped `/usage` banner.
//
// `usage` is one of the aliases because Freebuff removes that command —
// its banner is credits- and subscription-shaped — leaving the product
// with no answer at all to "how much have I used?". The word now lands
// somewhere, and only in the build where nothing else claims it.
aliases: ['usage', 'stats', 'streak'],
handler: (params) => {
const url = `${LOGIN_WEBSITE_URL}/account`
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
getSystemMessage(
`Opening your dashboard: ${url}\n\nStreak, activity, tokens, sessions and settings for your account — across the CLI, Desktop and web.`,
),
])
// Best-effort: `safeOpen` skips headless Linux and a locked-down WSL
// rather than risking the process, so the URL above is printed first and
// stays useful when nothing opens.
void safeOpen(url)
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
defineCommandWithArgs({
name: 'image',
aliases: ['img', 'attach'],
handler: async (params, args) => {
const trimmedArgs = args.trim()
// If user provided a path directly, process it immediately
if (trimmedArgs) {
await handleImageCommand(trimmedArgs)
params.saveToHistory(params.inputValue.trim())
clearInput(params)
return
}
// Otherwise enter image mode
useChatStore.getState().setInputMode('image')
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
// Mode commands generated from AGENT_MODES (excluded in Freebuff)
...(IS_FREEBUFF ? [] : AGENT_MODES).map((mode) =>
defineCommandWithArgs({
name: `mode:${mode.toLowerCase()}`,
aliases: [`model:${mode.toLowerCase()}`],
handler: (params, args) => {
const trimmedArgs = args.trim()
useChatStore.getState().setAgentMode(mode)
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
getSystemMessage(`Switched to ${mode} mode.`),
])
params.saveToHistory(params.inputValue.trim())
clearInput(params)
// If user provided a message, send it in the new mode
if (trimmedArgs) {
params.setCanProcessQueue(true)
params.sendMessage({
content: trimmedArgs,
agentMode: mode,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
}
},
}),
),
defineCommandWithArgs({
name: 'publish',
handler: (params, args) => {
const trimmedArgs = args.trim()
params.saveToHistory(params.inputValue.trim())
clearInput(params)
// If user provided agent ids directly, skip to confirmation step
if (trimmedArgs) {
const agentIds = trimmedArgs.split(/\s+/).filter(Boolean)
return { openPublishMode: true, preSelectAgents: agentIds }
}
// Otherwise open selection UI
return { openPublishMode: true }
},
}),
defineCommand({
name: 'gpt-5-agent',
handler: (params) => {
// Insert @ GPT-5 Agent into the input field (UI shortcut, not a real command)
params.setInputValue({
text: '@GPT-5 Agent ',
cursorPosition: '@GPT-5 Agent '.length,
lastEditDueToNav: false,
})
params.inputRef.current?.focus()
// Don't save to history - this is just a UI shortcut
},
}),
defineCommand({
name: 'history',
aliases: ['chats'],
handler: (params) => {
params.saveToHistory(params.inputValue.trim())
clearInput(params)
return { openChatHistory: true }
},
}),
defineCommandWithArgs({
name: 'interview',
handler: (params, args) => {
const trimmedArgs = args.trim()
params.saveToHistory(params.inputValue.trim())
clearInput(params)
// If user provided text directly, send it immediately
if (trimmedArgs) {
params.sendMessage({
content: buildInterviewPrompt(trimmedArgs),
agentMode: params.agentMode,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
return
}
// Otherwise enter interview mode
useChatStore.getState().setInputMode('interview')
},
}),
defineCommandWithArgs({
name: 'plan',
handler: (params, args) => {
// /plan runs on the selected model. No gate.
const trimmedArgs = args.trim()
params.saveToHistory(params.inputValue.trim())
clearInput(params)
// If user provided plan text directly, send it immediately
if (trimmedArgs) {
params.sendMessage({
content: buildPlanPrompt(trimmedArgs),
agentMode: params.agentMode,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
return
}
// Otherwise enter plan mode
useChatStore.getState().setInputMode('plan')
},
}),
defineCommandWithArgs({
name: 'review',
handler: (params, args) => {
// /review runs on the selected model. No gate.
const trimmedArgs = args.trim()
params.saveToHistory(params.inputValue.trim())
clearInput(params)
// If user provided review text directly, send it immediately without showing the screen
if (trimmedArgs) {
params.sendMessage({
content: buildReviewPromptFromArgs(trimmedArgs),
agentMode: params.agentMode,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
return
}
// Otherwise open the selection UI
return { openReviewScreen: true }
},
}),
defineCommand({
// No `/q` alias: that one already quits the CLI, and a queue editor is not
// worth the chance of a mis-fired exit.
name: 'queue',
aliases: ['queued'],
handler: (params) => {
params.saveToHistory(params.inputValue.trim())
clearInput(params)
return { openQueuePanel: true }
},
}),
defineCommand({
name: 'theme:toggle',
handler: (params) => {
const { theme, setThemeName } = useThemeStore.getState()
const newTheme = theme.name === 'dark' ? 'light' : 'dark'
setThemeName(newTheme)
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
getSystemMessage(`Switched to ${newTheme} theme.`),
])
clearInput(params)
},
}),
// /reasoning (freebuff-only) — read or set the thinking level for the
// selected model. Takes effect on the NEXT message: the effort rides
// codebuff_metadata on each request, so nothing about the live session has to
// be restarted for a change to land.
defineCommandWithArgs({
name: 'reasoning',
aliases: ['effort', 'think'],
handler: (params, args) => {
const { message } = handleReasoningCommand(args)
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
getSystemMessage(message),
])
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
}),
// /end-session (freebuff-only) — end the active session early and drop back
// to the model picker. The hook flips status to 'none', which unmounts
// <Chat> and mounts <FreebuffLandingScreen>, where the user picks a model
// and hits Enter to start a new session.
defineCommand({
name: 'end-session',
aliases: ['model'],
handler: (params) => {
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
getSystemMessage(END_SESSION_MESSAGE),
])
params.saveToHistory(params.inputValue.trim())
clearInput(params)
returnToFreebuffLanding({ resetChat: true }).catch(() => {
// The hook surfaces poll errors via the session store; nothing to do
// here beyond letting the chat history reflect the attempt.
})
},
}),
]
export const COMMAND_REGISTRY: CommandDefinition[] = IS_FREEBUFF
? ALL_COMMANDS.filter((cmd) => !FREEBUFF_REMOVED_COMMANDS.has(cmd.name))
: ALL_COMMANDS.filter((cmd) => !FREEBUFF_ONLY_COMMANDS.has(cmd.name))
export function findCommand(cmd: string): CommandDefinition | undefined {
const lowerCmd = cmd.toLowerCase()
// First check the static command registry
const staticCommand = COMMAND_REGISTRY.find(
(def) => def.name === lowerCmd || def.aliases.includes(lowerCmd),
)
if (staticCommand) {
return staticCommand
}
// Check if this is a skill command (prefixed with "skill:")
if (lowerCmd.startsWith('skill:')) {
const skillName = lowerCmd.slice('skill:'.length)
const skill = getSkillByName(skillName)
if (skill) {
return createSkillCommand(skill.name)
}
}
return undefined
}
/**
* Creates a dynamic command definition for a skill.
* When invoked, the skill's content is sent to the agent.
*/
function createSkillCommand(skillName: string): CommandDefinition {
return defineCommandWithArgs({
name: skillName,
handler: (params, args) => {
const skill = getSkillByName(skillName)
if (!skill) {
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
getSystemMessage(`Skill not found: ${skillName}`),
])
params.saveToHistory(params.inputValue.trim())
params.setInputValue({ text: '', cursorPosition: 0, lastEditDueToNav: false })
return
}
const trimmed = params.inputValue.trim()
params.saveToHistory(trimmed)
params.setInputValue({ text: '', cursorPosition: 0, lastEditDueToNav: false })
// Bare invocation: like /interview, drop into an input mode so the
// user can add instructions before the skill is sent. Enter with an
// empty composer still runs the skill as-is (the router's skill-mode
// branch), so a no-args run costs one extra keystroke, not a feature.
if (!args.trim()) {
useChatStore.getState().enterSkillMode(skill.name)
params.setInputFocused(true)
params.inputRef.current?.focus()
return
}
dispatchSkillPrompt(params, skill, args)
},
})
}
/**
* Send (or queue, mid-turn) a user-invoked skill prompt. Shared by the
* /skill:<name> args form and the skill input mode's submit (router), so the
* two entry paths for the same feature cannot drift.
*/
export function dispatchSkillPrompt(
params: RouterParams,
skill: { name: string; content: string },
input: string,
): void {
const userPrompt = buildSkillPrompt(skill, input)
if (
params.isStreaming ||
params.streamMessageIdRef.current ||
params.isChainInProgressRef.current
) {
params.addToQueue(userPrompt, capturePendingAttachments())
params.setInputFocused(true)
params.inputRef.current?.focus()
return
}
params.sendMessage({
content: userPrompt,
agentMode: params.agentMode,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
}