Elffuss BraidHub

kikocis/continue public

main · 7.1 KiBRawPermalink
1import { type AssistantConfig } from "@continuedev/sdk";
2import chalk from "chalk";
3
4import {
5 isAuthenticated,
6 isAuthenticatedConfig,
7 loadAuthConfig,
8} from "./auth/workos.js";
9import { getAllSlashCommands } from "./commands/commands.js";
10import { handleInit } from "./commands/init.js";
11import { handleInfoSlashCommand } from "./infoScreen.js";
12import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
13import { getCurrentSession, updateSessionTitle } from "./session.js";
14import { posthogService } from "./telemetry/posthogService.js";
15import { telemetryService } from "./telemetry/telemetryService.js";
16import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
17
18type CommandHandler = (
19 args: string[],
20 assistant: AssistantConfig,
21 remoteUrl?: string,
22 options?: { isRemoteMode?: boolean },
23) => Promise<SlashCommandResult> | SlashCommandResult;
24
25async function handleHelp(_args: string[], _assistant: AssistantConfig) {
26 const helpMessage = [
27 chalk.bold("Keyboard Shortcuts:"),
28 "",
29 chalk.white("Navigation:"),
30 ` ${chalk.cyan("↑/↓")} Navigate command/file suggestions or history`,
31 ` ${chalk.cyan("Tab")} Complete command or file selection`,
32 ` ${chalk.cyan("Enter")} Submit message`,
33 ` ${chalk.cyan("Shift+Enter")} New line`,
34 ` ${chalk.cyan("\\")} Line continuation (at end of line)`,
35 ` ${chalk.cyan("!")} Shell mode - run shell commands`,
36 "",
37 chalk.white("Controls:"),
38 ` ${chalk.cyan("Ctrl+C")} Clear input`,
39 ` ${chalk.cyan("Ctrl+D")} Exit application`,
40 ` ${chalk.cyan("Ctrl+L")} Clear screen`,
41 ` ${chalk.cyan("Shift+Tab")} Cycle permission modes (normal/plan/auto)`,
42 ` ${chalk.cyan("Esc")} Cancel streaming or close suggestions`,
43 "",
44 chalk.white("Special Characters:"),
45 ` ${chalk.cyan("@")} Search and attach files for context`,
46 ` ${chalk.cyan("/")} Access slash commands`,
47 ` ${chalk.cyan("!")} Execute bash commands directly`,
48 "",
49 chalk.white("Available Commands:"),
50 ` Type ${chalk.cyan("/")} to see available slash commands`,
51 ` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
52 ].join("\n");
53 return { output: helpMessage };
54}
55
56async function handleLogin() {
57 try {
58 const newAuthState = await services.auth.login();
59 await reloadService(SERVICE_NAMES.AUTH);
60
61 const userInfo =
62 newAuthState.authConfig && isAuthenticatedConfig(newAuthState.authConfig)
63 ? newAuthState.authConfig.userEmail || newAuthState.authConfig.userId
64 : "user";
65
66 console.info(chalk.green(`\nLogged in as ${userInfo}`));
67
68 return {
69 exit: false,
70 output: "Login successful! All services updated automatically.",
71 };
72 } catch (error: any) {
73 console.error(chalk.red(`\nLogin failed: ${error.message}`));
74 return {
75 exit: false,
76 output: `Login failed: ${error.message}`,
77 };
78 }
79}
80
81async function handleLogout() {
82 try {
83 await services.auth.logout();
84 return {
85 exit: true,
86 output: "Logged out successfully",
87 };
88 } catch {
89 return {
90 exit: true,
91 output: "Logged out successfully",
92 };
93 }
94}
95
96function handleWhoami() {
97 if (isAuthenticated()) {
98 const config = loadAuthConfig();
99 if (config && isAuthenticatedConfig(config)) {
100 return {
101 exit: false,
102 output: `Logged in as ${config.userEmail || config.userId}`,
103 };
104 } else {
105 return {
106 exit: false,
107 output: "Authenticated via environment variable",
108 };
109 }
110 } else {
111 return {
112 exit: false,
113 output: "Not logged in. Use /login to authenticate.",
114 };
115 }
116}
117
118async function handleFork() {
119 try {
120 const currentSession = getCurrentSession();
121 const forkCommand = `cn --fork ${currentSession.sessionId}`;
122 // Try to copy to clipboard dynamically to avoid hard dependency in tests
123 try {
124 const clipboardy = await import("clipboardy");
125 await clipboardy.default.write(forkCommand);
126 return {
127 exit: false,
128 output: chalk.gray(`${forkCommand} (copied to clipboard)`),
129 };
130 } catch {
131 return {
132 exit: false,
133 output: chalk.gray(`${forkCommand}`),
134 };
135 }
136 } catch (error: any) {
137 return {
138 exit: false,
139 output: chalk.red(`Failed to create fork command: ${error.message}`),
140 };
141 }
142}
143
144function handleTitle(args: string[]) {
145 posthogService.capture("useSlashCommand", { name: "title" });
146
147 const title = args.join(" ").trim();
148 if (!title) {
149 return {
150 exit: false,
151 output: chalk.yellow(
152 "Please provide a title. Usage: /title <your title>",
153 ),
154 };
155 }
156
157 try {
158 updateSessionTitle(title);
159 return {
160 exit: false,
161 output: chalk.green(`Session title updated to: "${title}"`),
162 };
163 } catch (error: any) {
164 return {
165 exit: false,
166 output: chalk.red(`Failed to update title: ${error.message}`),
167 };
168 }
169}
170
171const commandHandlers: Record<string, CommandHandler> = {
172 help: handleHelp,
173 clear: () => {
174 return { clear: true, output: "Chat history cleared" };
175 },
176 exit: () => {
177 return { exit: true, output: "Goodbye!" };
178 },
179 config: () => {
180 return { openConfigSelector: true };
181 },
182 login: handleLogin,
183 logout: handleLogout,
184 whoami: handleWhoami,
185 info: handleInfoSlashCommand,
186 model: () => ({ openModelSelector: true }),
187 compact: () => {
188 return { compact: true };
189 },
190 mcp: () => {
191 return { openMcpSelector: true };
192 },
193 resume: () => {
194 return { openSessionSelector: true };
195 },
196 fork: handleFork,
197 title: handleTitle,
198 init: (args, assistant) => {
199 posthogService.capture("useSlashCommand", { name: "init" });
200 return handleInit(args, assistant);
201 },
202 update: () => {
203 return { openUpdateSelector: true };
204 },
205};
206
207export async function handleSlashCommands(
208 input: string,
209 assistant: AssistantConfig,
210 options?: { remoteUrl?: string; isRemoteMode?: boolean },
211): Promise<SlashCommandResult | null> {
212 // Only trigger slash commands if slash is the very first character
213 if (!input.startsWith("/") || !input.trim().startsWith("/")) {
214 return null;
215 }
216
217 const [command, ...args] = input.slice(1).split(" ");
218
219 telemetryService.recordSlashCommand(command);
220 posthogService.capture("useSlashCommand", { name: command });
221
222 const handler = commandHandlers[command];
223 if (handler) {
224 return await handler(args, assistant, options?.remoteUrl, options);
225 }
226
227 // Check for custom assistant prompts
228 const assistantPrompt = assistant.prompts?.find(
229 (prompt) => prompt?.name === command,
230 );
231 if (assistantPrompt) {
232 const newInput = assistantPrompt.prompt + args.join(" ");
233 return { newInput };
234 }
235
236 // Check if this command would match any available commands (same logic as UI)
237 const allCommands = getAllSlashCommands(assistant, {
238 isRemoteMode: options?.isRemoteMode,
239 });
240 const hasMatches = allCommands.some((cmd) =>
241 cmd.name.toLowerCase().includes(command.toLowerCase()),
242 );
243
244 // If no commands match, treat this as regular text instead of an unknown command
245 if (!hasMatches) {
246 return null;
247 }
248
249 return { output: `Unknown command: ${command}` };
250}