Elffuss BraidHub

kikocis/continue public

78eef004d400 · 8.5 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 { reloadService, SERVICE_NAMES, services } from "./services/index.js";
11import { getCurrentSession, getSessionFilePath } from "./session.js";
12import { posthogService } from "./telemetry/posthogService.js";
13import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
14import { getVersion } from "./version.js";
15
16type CommandHandler = (
17 args: string[],
18 assistant: AssistantConfig,
19) => Promise<SlashCommandResult> | SlashCommandResult;
20
21async function handleHelp(_args: string[], _assistant: AssistantConfig) {
22 const helpMessage = [
23 chalk.bold("Keyboard Shortcuts:"),
24 "",
25 chalk.white("Navigation:"),
26 ` ${chalk.cyan("↑/↓")} Navigate command/file suggestions or history`,
27 ` ${chalk.cyan("Tab")} Complete command or file selection`,
28 ` ${chalk.cyan("Enter")} Submit message`,
29 ` ${chalk.cyan("Shift+Enter")} New line`,
30 ` ${chalk.cyan("\\")} Line continuation (at end of line)`,
31 "",
32 chalk.white("Controls:"),
33 ` ${chalk.cyan("Ctrl+C")} Clear input`,
34 ` ${chalk.cyan("Ctrl+D")} Exit application`,
35 ` ${chalk.cyan("Ctrl+L")} Clear screen`,
36 ` ${chalk.cyan("Shift+Tab")} Cycle permission modes (normal/plan/auto)`,
37 ` ${chalk.cyan("Esc")} Cancel streaming or close suggestions`,
38 "",
39 chalk.white("Special Characters:"),
40 ` ${chalk.cyan("@")} Search and attach files for context`,
41 ` ${chalk.cyan("/")} Access slash commands`,
42 "",
43 chalk.white("Available Commands:"),
44 ` Type ${chalk.cyan("/")} to see available slash commands`,
45 ].join("\n");
46 posthogService.capture("useSlashCommand", { name: "help" });
47 return { output: helpMessage };
48}
49
50async function handleLogin() {
51 posthogService.capture("useSlashCommand", { name: "login" });
52 try {
53 const newAuthState = await services.auth.login();
54 await reloadService(SERVICE_NAMES.AUTH);
55
56 const userInfo =
57 newAuthState.authConfig && isAuthenticatedConfig(newAuthState.authConfig)
58 ? newAuthState.authConfig.userEmail || newAuthState.authConfig.userId
59 : "user";
60
61 console.info(chalk.green(`\nLogged in as ${userInfo}`));
62
63 return {
64 exit: false,
65 output: "Login successful! All services updated automatically.",
66 };
67 } catch (error: any) {
68 console.error(chalk.red(`\nLogin failed: ${error.message}`));
69 return {
70 exit: false,
71 output: `Login failed: ${error.message}`,
72 };
73 }
74}
75
76async function handleLogout() {
77 posthogService.capture("useSlashCommand", { name: "logout" });
78 try {
79 await services.auth.logout();
80 return {
81 exit: true,
82 output: "Logged out successfully",
83 };
84 } catch {
85 return {
86 exit: true,
87 output: "Logged out successfully",
88 };
89 }
90}
91
92function handleWhoami() {
93 posthogService.capture("useSlashCommand", { name: "whoami" });
94 if (isAuthenticated()) {
95 const config = loadAuthConfig();
96 if (config && isAuthenticatedConfig(config)) {
97 return {
98 exit: false,
99 output: `Logged in as ${config.userEmail || config.userId}`,
100 };
101 } else {
102 return {
103 exit: false,
104 output: "Authenticated via environment variable",
105 };
106 }
107 } else {
108 return {
109 exit: false,
110 output: "Not logged in. Use /login to authenticate.",
111 };
112 }
113}
114
115async function handleInfo() {
116 posthogService.capture("useSlashCommand", { name: "info" });
117
118 const infoLines = [];
119
120 // Version and working directory info
121 const version = getVersion();
122 const cwd = process.cwd();
123
124 infoLines.push(chalk.white("CLI Information:"));
125 infoLines.push(` Version: ${chalk.green(version)}`);
126 infoLines.push(` Working Directory: ${chalk.blue(cwd)}`);
127
128 // Auth info
129 if (isAuthenticated()) {
130 const config = loadAuthConfig();
131 if (config && isAuthenticatedConfig(config)) {
132 const email = config.userEmail || config.userId;
133 const org = "(no org)"; // Organization info not available in AuthenticatedConfig
134 infoLines.push("");
135 infoLines.push(chalk.white("Authentication:"));
136 infoLines.push(` Email: ${chalk.green(email)}`);
137 infoLines.push(` Organization: ${chalk.cyan(org)}`);
138 } else {
139 infoLines.push("");
140 infoLines.push(chalk.white("Authentication:"));
141 infoLines.push(
142 ` ${chalk.yellow("Authenticated via environment variable")}`,
143 );
144 }
145 } else {
146 infoLines.push("");
147 infoLines.push(chalk.white("Authentication:"));
148 infoLines.push(` ${chalk.red("Not logged in")}`);
149 }
150
151 // Config info
152 try {
153 const configState = services.config.getState();
154 infoLines.push("");
155 infoLines.push(chalk.white("Configuration:"));
156 if (configState.config) {
157 infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`);
158 } else {
159 infoLines.push(` ${chalk.red(`Config not found`)}`);
160 }
161 if (configState.configPath) {
162 infoLines.push(` Path: ${chalk.blue(configState.configPath)}`);
163 }
164
165 // Add current model info
166 try {
167 const modelInfo = services.model?.getModelInfo();
168 if (modelInfo) {
169 infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`);
170 } else {
171 infoLines.push(` Model: ${chalk.red("Not available")}`);
172 }
173 } catch {
174 infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`);
175 }
176 } catch {
177 infoLines.push("");
178 infoLines.push(chalk.white("Configuration:"));
179 infoLines.push(` ${chalk.red("Configuration service not available")}`);
180 }
181
182 // Session info
183 infoLines.push("");
184 infoLines.push(chalk.white("Session:"));
185 try {
186 const currentSession = getCurrentSession();
187 infoLines.push(` Title: ${chalk.green(currentSession.title)}`);
188 infoLines.push(` ID: ${chalk.gray(currentSession.sessionId)}`);
189
190 const sessionFilePath = getSessionFilePath();
191 infoLines.push(` File: ${chalk.blue(sessionFilePath)}`);
192 } catch {
193 infoLines.push(` ${chalk.red("Session not available")}`);
194 }
195
196 return {
197 exit: false,
198 output: infoLines.join("\n"),
199 };
200}
201
202const commandHandlers: Record<string, CommandHandler> = {
203 help: handleHelp,
204 clear: () => {
205 posthogService.capture("useSlashCommand", { name: "clear" });
206 return { clear: true, output: "Chat history cleared" };
207 },
208 exit: () => {
209 posthogService.capture("useSlashCommand", { name: "exit" });
210 return { exit: true, output: "Goodbye!" };
211 },
212 config: () => {
213 posthogService.capture("useSlashCommand", { name: "config" });
214 return { openConfigSelector: true };
215 },
216 login: handleLogin,
217 logout: handleLogout,
218 whoami: handleWhoami,
219 info: handleInfo,
220 model: () => ({ openModelSelector: true }),
221 compact: () => {
222 posthogService.capture("useSlashCommand", { name: "compact" });
223 return { compact: true };
224 },
225 mcp: () => {
226 posthogService.capture("useSlashCommand", { name: "mcp" });
227 return { openMcpSelector: true };
228 },
229 resume: () => {
230 posthogService.capture("useSlashCommand", { name: "resume" });
231 return { openSessionSelector: true };
232 },
233};
234
235export async function handleSlashCommands(
236 input: string,
237 assistant: AssistantConfig,
238): Promise<{
239 output?: string;
240 exit?: boolean;
241 newInput?: string;
242 clear?: boolean;
243 openConfigSelector?: boolean;
244 openModelSelector?: boolean;
245 openMCPSelector?: boolean;
246 openSessionSelector?: boolean;
247 compact?: boolean;
248} | null> {
249 // Only trigger slash commands if slash is the very first character
250 if (!input.startsWith("/") || !input.trim().startsWith("/")) {
251 return null;
252 }
253
254 const [command, ...args] = input.slice(1).split(" ");
255
256 const handler = commandHandlers[command];
257 if (handler) {
258 return await handler(args, assistant);
259 }
260
261 // Check for custom assistant prompts
262 const assistantPrompt = assistant.prompts?.find(
263 (prompt) => prompt?.name === command,
264 );
265 if (assistantPrompt) {
266 const newInput = assistantPrompt.prompt + args.join(" ");
267 return { newInput };
268 }
269
270 // Check if this command would match any available commands (same logic as UI)
271 const allCommands = getAllSlashCommands(assistant);
272 const hasMatches = allCommands.some((cmd) =>
273 cmd.name.toLowerCase().includes(command.toLowerCase()),
274 );
275
276 // If no commands match, treat this as regular text instead of an unknown command
277 if (!hasMatches) {
278 return null;
279 }
280
281 return { output: `Unknown command: ${command}` };
282}