| 1 | import { type AssistantConfig } from "@continuedev/sdk"; |
| 2 | import chalk from "chalk"; |
| 3 | |
| 4 | import { |
| 5 | isAuthenticated, |
| 6 | isAuthenticatedConfig, |
| 7 | loadAuthConfig, |
| 8 | } from "./auth/workos.js"; |
| 9 | import { getAllSlashCommands } from "./commands/commands.js"; |
| 10 | import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; |
| 11 | import { getCurrentSession, getSessionFilePath } from "./session.js"; |
| 12 | import { posthogService } from "./telemetry/posthogService.js"; |
| 13 | import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; |
| 14 | import { getVersion } from "./version.js"; |
| 15 | |
| 16 | type CommandHandler = ( |
| 17 | args: string[], |
| 18 | assistant: AssistantConfig, |
| 19 | ) => Promise<SlashCommandResult> | SlashCommandResult; |
| 20 | |
| 21 | async 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 | |
| 50 | async 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 | |
| 76 | async 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 | |
| 92 | function 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 | |
| 115 | async 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 | |
| 202 | async function handleFork() { |
| 203 | posthogService.capture("useSlashCommand", { name: "fork" }); |
| 204 | |
| 205 | try { |
| 206 | const currentSession = getCurrentSession(); |
| 207 | const forkCommand = `cn --fork ${currentSession.sessionId}`; |
| 208 | // Try to copy to clipboard dynamically to avoid hard dependency in tests |
| 209 | try { |
| 210 | const clipboardy = await import("clipboardy"); |
| 211 | await clipboardy.default.write(forkCommand); |
| 212 | return { |
| 213 | exit: false, |
| 214 | output: chalk.gray(`${forkCommand} (copied to clipboard)`), |
| 215 | }; |
| 216 | } catch { |
| 217 | return { |
| 218 | exit: false, |
| 219 | output: chalk.gray(`${forkCommand}`), |
| 220 | }; |
| 221 | } |
| 222 | } catch (error: any) { |
| 223 | return { |
| 224 | exit: false, |
| 225 | output: chalk.red(`Failed to create fork command: ${error.message}`), |
| 226 | }; |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | const commandHandlers: Record<string, CommandHandler> = { |
| 231 | help: handleHelp, |
| 232 | clear: () => { |
| 233 | posthogService.capture("useSlashCommand", { name: "clear" }); |
| 234 | return { clear: true, output: "Chat history cleared" }; |
| 235 | }, |
| 236 | exit: () => { |
| 237 | posthogService.capture("useSlashCommand", { name: "exit" }); |
| 238 | return { exit: true, output: "Goodbye!" }; |
| 239 | }, |
| 240 | config: () => { |
| 241 | posthogService.capture("useSlashCommand", { name: "config" }); |
| 242 | return { openConfigSelector: true }; |
| 243 | }, |
| 244 | login: handleLogin, |
| 245 | logout: handleLogout, |
| 246 | whoami: handleWhoami, |
| 247 | info: handleInfo, |
| 248 | model: () => ({ openModelSelector: true }), |
| 249 | compact: () => { |
| 250 | posthogService.capture("useSlashCommand", { name: "compact" }); |
| 251 | return { compact: true }; |
| 252 | }, |
| 253 | mcp: () => { |
| 254 | posthogService.capture("useSlashCommand", { name: "mcp" }); |
| 255 | return { openMcpSelector: true }; |
| 256 | }, |
| 257 | resume: () => { |
| 258 | posthogService.capture("useSlashCommand", { name: "resume" }); |
| 259 | return { openSessionSelector: true }; |
| 260 | }, |
| 261 | fork: handleFork, |
| 262 | }; |
| 263 | |
| 264 | export async function handleSlashCommands( |
| 265 | input: string, |
| 266 | assistant: AssistantConfig, |
| 267 | ): Promise<{ |
| 268 | output?: string; |
| 269 | exit?: boolean; |
| 270 | newInput?: string; |
| 271 | clear?: boolean; |
| 272 | openConfigSelector?: boolean; |
| 273 | openModelSelector?: boolean; |
| 274 | openMCPSelector?: boolean; |
| 275 | openSessionSelector?: boolean; |
| 276 | compact?: boolean; |
| 277 | } | null> { |
| 278 | // Only trigger slash commands if slash is the very first character |
| 279 | if (!input.startsWith("/") || !input.trim().startsWith("/")) { |
| 280 | return null; |
| 281 | } |
| 282 | |
| 283 | const [command, ...args] = input.slice(1).split(" "); |
| 284 | |
| 285 | const handler = commandHandlers[command]; |
| 286 | if (handler) { |
| 287 | return await handler(args, assistant); |
| 288 | } |
| 289 | |
| 290 | // Check for custom assistant prompts |
| 291 | const assistantPrompt = assistant.prompts?.find( |
| 292 | (prompt) => prompt?.name === command, |
| 293 | ); |
| 294 | if (assistantPrompt) { |
| 295 | const newInput = assistantPrompt.prompt + args.join(" "); |
| 296 | return { newInput }; |
| 297 | } |
| 298 | |
| 299 | // Check if this command would match any available commands (same logic as UI) |
| 300 | const allCommands = getAllSlashCommands(assistant); |
| 301 | const hasMatches = allCommands.some((cmd) => |
| 302 | cmd.name.toLowerCase().includes(command.toLowerCase()), |
| 303 | ); |
| 304 | |
| 305 | // If no commands match, treat this as regular text instead of an unknown command |
| 306 | if (!hasMatches) { |
| 307 | return null; |
| 308 | } |
| 309 | |
| 310 | return { output: `Unknown command: ${command}` }; |
| 311 | } |