Elffuss BraidHub

kikocis/continue public

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