Elffuss BraidHub

kikocis/continue public

66328f2e8dcf · 8.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 { reloadService, SERVICE_NAMES, services } from "./services/index.js";
11import { 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(
22 _args: string[],
23 _assistant: AssistantConfig,
24) {
25 const helpMessage = [
26 chalk.bold("Keyboard Shortcuts:"),
27 "",
28 chalk.white("Navigation:"),
29 ` ${chalk.cyan("↑/↓")} Navigate command/file suggestions or history`,
30 ` ${chalk.cyan("Tab")} Complete command or file selection`,
31 ` ${chalk.cyan("Enter")} Submit message`,
32 ` ${chalk.cyan("Shift+Enter")} New line`,
33 ` ${chalk.cyan("\\")} Line continuation (at end of line)`,
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 "",
46 chalk.white("Available Commands:"),
47 ` Type ${chalk.cyan("/")} to see available slash commands`,
48 ].join("\n");
49 posthogService.capture("useSlashCommand", { name: "help" });
50 return { output: helpMessage };
51}
52
53async function handleLogin() {
54 posthogService.capture("useSlashCommand", { name: "login" });
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 posthogService.capture("useSlashCommand", { name: "logout" });
81 try {
82 await services.auth.logout();
83 return {
84 exit: true,
85 output: "Logged out successfully",
86 };
87 } catch {
88 return {
89 exit: true,
90 output: "Logged out successfully",
91 };
92 }
93}
94
95function handleWhoami() {
96 posthogService.capture("useSlashCommand", { name: "whoami" });
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 handleInfo() {
119 posthogService.capture("useSlashCommand", { name: "info" });
120
121 const infoLines = [];
122
123 // Version and working directory info
124 const version = getVersion();
125 const cwd = process.cwd();
126
127 infoLines.push(chalk.white("CLI Information:"));
128 infoLines.push(` Version: ${chalk.green(version)}`);
129 infoLines.push(` Working Directory: ${chalk.blue(cwd)}`);
130
131 // Auth info
132 if (isAuthenticated()) {
133 const config = loadAuthConfig();
134 if (config && isAuthenticatedConfig(config)) {
135 const email = config.userEmail || config.userId;
136 const org = "(no org)"; // Organization info not available in AuthenticatedConfig
137 infoLines.push("");
138 infoLines.push(chalk.white("Authentication:"));
139 infoLines.push(` Email: ${chalk.green(email)}`);
140 infoLines.push(` Organization: ${chalk.cyan(org)}`);
141 } else {
142 infoLines.push("");
143 infoLines.push(chalk.white("Authentication:"));
144 infoLines.push(
145 ` ${chalk.yellow("Authenticated via environment variable")}`,
146 );
147 }
148 } else {
149 infoLines.push("");
150 infoLines.push(chalk.white("Authentication:"));
151 infoLines.push(` ${chalk.red("Not logged in")}`);
152 }
153
154 // Config info
155 try {
156 const configState = services.config.getState();
157 infoLines.push("");
158 infoLines.push(chalk.white("Configuration:"));
159 if (configState.config) {
160 infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`);
161 } else {
162 infoLines.push(` ${chalk.red(`Config not found`)}`);
163 }
164 if (configState.configPath) {
165 infoLines.push(` Path: ${chalk.blue(configState.configPath)}`);
166 }
167
168 // Add current model info
169 try {
170 const modelInfo = services.model?.getModelInfo();
171 if (modelInfo) {
172 infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`);
173 } else {
174 infoLines.push(` Model: ${chalk.red("Not available")}`);
175 }
176 } catch {
177 infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`);
178 }
179 } catch {
180 infoLines.push("");
181 infoLines.push(chalk.white("Configuration:"));
182 infoLines.push(` ${chalk.red("Configuration service not available")}`);
183 }
184
185 // Session history path
186 infoLines.push("");
187 infoLines.push(chalk.white("Session History:"));
188 const sessionFilePath = getSessionFilePath();
189
190 infoLines.push(` File: ${chalk.blue(sessionFilePath)}`);
191
192 return {
193 exit: false,
194 output: infoLines.join("\n"),
195 };
196}
197
198const commandHandlers: Record<string, CommandHandler> = {
199 help: handleHelp,
200 clear: () => {
201 posthogService.capture("useSlashCommand", { name: "clear" });
202 return { clear: true, output: "Chat history cleared" };
203 },
204 exit: () => {
205 posthogService.capture("useSlashCommand", { name: "exit" });
206 return { exit: true, output: "Goodbye!" };
207 },
208 config: () => {
209 posthogService.capture("useSlashCommand", { name: "config" });
210 return { openConfigSelector: true };
211 },
212 login: handleLogin,
213 logout: handleLogout,
214 whoami: handleWhoami,
215 info: handleInfo,
216 model: () => ({ openModelSelector: true }),
217 compact: () => {
218 posthogService.capture("useSlashCommand", { name: "compact" });
219 return { compact: true };
220 },
221 mcp: () => {
222 posthogService.capture("useSlashCommand", { name: "mcp" });
223 return { openMcpSelector: true };
224 },
225 resume: () => {
226 posthogService.capture("useSlashCommand", { name: "resume" });
227 return { openSessionSelector: true };
228 },
229};
230
231export async function handleSlashCommands(
232 input: string,
233 assistant: AssistantConfig,
234): Promise<{
235 output?: string;
236 exit?: boolean;
237 newInput?: string;
238 clear?: boolean;
239 openConfigSelector?: boolean;
240 openModelSelector?: boolean;
241 openMCPSelector?: boolean;
242 openSessionSelector?: boolean;
243 compact?: boolean;
244} | null> {
245 // Only trigger slash commands if slash is the very first character
246 if (!input.startsWith("/") || !input.trim().startsWith("/")) {
247 return null;
248 }
249
250 const [command, ...args] = input.slice(1).split(" ");
251
252 const handler = commandHandlers[command];
253 if (handler) {
254 return await handler(args, assistant);
255 }
256
257 // Check for custom assistant prompts
258 const assistantPrompt = assistant.prompts?.find(
259 (prompt) => prompt?.name === command,
260 );
261 if (assistantPrompt) {
262 const newInput = assistantPrompt.prompt + args.join(" ");
263 return { newInput };
264 }
265
266 // Check if this command would match any available commands (same logic as UI)
267 const allCommands = getAllSlashCommands(assistant);
268 const hasMatches = allCommands.some((cmd) =>
269 cmd.name.toLowerCase().includes(command.toLowerCase()),
270 );
271
272 // If no commands match, treat this as regular text instead of an unknown command
273 if (!hasMatches) {
274 return null;
275 }
276
277 return { output: `Unknown command: ${command}` };
278}