Elffuss BraidHub

kikocis/continue public

d13968478db8 · 6.7 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";
14
15type CommandHandler = (
16 args: string[],
17 assistant: AssistantConfig,
18) => Promise<SlashCommandResult> | SlashCommandResult;
19
20async function handleHelp(args: string[], assistant: AssistantConfig) {
21 const allCommands = getAllSlashCommands(assistant);
22 const helpMessage = [
23 "Slash commands:",
24 ...allCommands
25 .sort((a, b) => a.name.localeCompare(b.name))
26 .map(
27 (cmd) =>
28 `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`,
29 ),
30 ].join("\n");
31 posthogService.capture("useSlashCommand", { name: "help" });
32 return { output: helpMessage };
33}
34
35async function handleLogin() {
36 posthogService.capture("useSlashCommand", { name: "login" });
37 try {
38 const newAuthState = await services.auth.login();
39 await reloadService(SERVICE_NAMES.AUTH);
40
41 const userInfo =
42 newAuthState.authConfig && isAuthenticatedConfig(newAuthState.authConfig)
43 ? newAuthState.authConfig.userEmail || newAuthState.authConfig.userId
44 : "user";
45
46 console.info(chalk.green(`\nLogged in as ${userInfo}`));
47
48 return {
49 exit: false,
50 output: "Login successful! All services updated automatically.",
51 };
52 } catch (error: any) {
53 console.error(chalk.red(`\nLogin failed: ${error.message}`));
54 return {
55 exit: false,
56 output: `Login failed: ${error.message}`,
57 };
58 }
59}
60
61async function handleLogout() {
62 posthogService.capture("useSlashCommand", { name: "logout" });
63 try {
64 await services.auth.logout();
65 return {
66 exit: true,
67 output: "Logged out successfully",
68 };
69 } catch {
70 return {
71 exit: true,
72 output: "Logged out successfully",
73 };
74 }
75}
76
77function handleWhoami() {
78 posthogService.capture("useSlashCommand", { name: "whoami" });
79 if (isAuthenticated()) {
80 const config = loadAuthConfig();
81 if (config && isAuthenticatedConfig(config)) {
82 return {
83 exit: false,
84 output: `Logged in as ${config.userEmail || config.userId}`,
85 };
86 } else {
87 return {
88 exit: false,
89 output: "Authenticated via environment variable",
90 };
91 }
92 } else {
93 return {
94 exit: false,
95 output: "Not logged in. Use /login to authenticate.",
96 };
97 }
98}
99
100async function handleInfo() {
101 posthogService.capture("useSlashCommand", { name: "info" });
102
103 const infoLines = [];
104
105 // Auth info
106 if (isAuthenticated()) {
107 const config = loadAuthConfig();
108 if (config && isAuthenticatedConfig(config)) {
109 const email = config.userEmail || config.userId;
110 const org = "(no org)"; // Organization info not available in AuthenticatedConfig
111 infoLines.push(chalk.white("Authentication:"));
112 infoLines.push(` Email: ${chalk.green(email)}`);
113 infoLines.push(` Organization: ${chalk.cyan(org)}`);
114 } else {
115 infoLines.push(chalk.white("Authentication:"));
116 infoLines.push(
117 ` ${chalk.yellow("Authenticated via environment variable")}`,
118 );
119 }
120 } else {
121 infoLines.push(chalk.white("Authentication:"));
122 infoLines.push(` ${chalk.red("Not logged in")}`);
123 }
124
125 // Config info
126 try {
127 const configState = services.config.getState();
128 infoLines.push("");
129 infoLines.push(chalk.white("Configuration:"));
130 if (configState.config) {
131 infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`);
132 } else {
133 infoLines.push(` ${chalk.red(`Config not found`)}`);
134 }
135 if (configState.configPath) {
136 infoLines.push(` Path: ${chalk.blue(configState.configPath)}`);
137 }
138 } catch {
139 infoLines.push("");
140 infoLines.push(chalk.white("Configuration:"));
141 infoLines.push(` ${chalk.red("Configuration service not available")}`);
142 }
143
144 // Session history path
145 infoLines.push("");
146 infoLines.push(chalk.white("Session History:"));
147 const sessionFilePath = getSessionFilePath();
148
149 infoLines.push(` File: ${chalk.blue(sessionFilePath)}`);
150
151 return {
152 exit: false,
153 output: infoLines.join("\n"),
154 };
155}
156
157const commandHandlers: Record<string, CommandHandler> = {
158 help: handleHelp,
159 clear: () => {
160 posthogService.capture("useSlashCommand", { name: "clear" });
161 return { clear: true, output: "Chat history cleared" };
162 },
163 exit: () => {
164 posthogService.capture("useSlashCommand", { name: "exit" });
165 return { exit: true, output: "Goodbye!" };
166 },
167 config: () => {
168 posthogService.capture("useSlashCommand", { name: "config" });
169 return { openConfigSelector: true };
170 },
171 login: handleLogin,
172 logout: handleLogout,
173 whoami: handleWhoami,
174 info: handleInfo,
175 model: () => ({ openModelSelector: true }),
176 compact: () => {
177 posthogService.capture("useSlashCommand", { name: "compact" });
178 return { compact: true };
179 },
180 mcp: () => {
181 posthogService.capture("useSlashCommand", { name: "mcp" });
182 return { openMcpSelector: true };
183 },
184 resume: () => {
185 posthogService.capture("useSlashCommand", { name: "resume" });
186 return { openSessionSelector: true };
187 },
188};
189
190export async function handleSlashCommands(
191 input: string,
192 assistant: AssistantConfig,
193): Promise<{
194 output?: string;
195 exit?: boolean;
196 newInput?: string;
197 clear?: boolean;
198 openConfigSelector?: boolean;
199 openModelSelector?: boolean;
200 openMCPSelector?: boolean;
201 openSessionSelector?: boolean;
202 compact?: boolean;
203} | null> {
204 // Only trigger slash commands if slash is the very first character
205 if (!input.startsWith("/") || !input.trim().startsWith("/")) {
206 return null;
207 }
208
209 const [command, ...args] = input.slice(1).split(" ");
210
211 const handler = commandHandlers[command];
212 if (handler) {
213 return await handler(args, assistant);
214 }
215
216 // Check for custom assistant prompts
217 const assistantPrompt = assistant.prompts?.find(
218 (prompt) => prompt?.name === command,
219 );
220 if (assistantPrompt) {
221 const newInput = assistantPrompt.prompt + args.join(" ");
222 return { newInput };
223 }
224
225 // Check if this command would match any available commands (same logic as UI)
226 const allCommands = getAllSlashCommands(assistant);
227 const hasMatches = allCommands.some((cmd) =>
228 cmd.name.toLowerCase().includes(command.toLowerCase()),
229 );
230
231 // If no commands match, treat this as regular text instead of an unknown command
232 if (!hasMatches) {
233 return null;
234 }
235
236 return { output: `Unknown command: ${command}` };
237}