| 1 | import iconv from "iconv-lite"; |
| 2 | import childProcess from "node:child_process"; |
| 3 | import os from "node:os"; |
| 4 | import util from "node:util"; |
| 5 | // Automatically decode the buffer according to the platform to avoid garbled Chinese |
| 6 | function getDecodedOutput(data: Buffer): string { |
| 7 | if (process.platform === "win32") { |
| 8 | try { |
| 9 | let out = iconv.decode(data, "utf-8"); |
| 10 | if (/�/.test(out)) { |
| 11 | out = iconv.decode(data, "gbk"); |
| 12 | } |
| 13 | return out; |
| 14 | } catch { |
| 15 | return iconv.decode(data, "gbk"); |
| 16 | } |
| 17 | } else { |
| 18 | return data.toString(); |
| 19 | } |
| 20 | } // Simple helper function to use login shell on Unix/macOS and PowerShell on Windows |
| 21 | function getShellCommand(command: string): { shell: string; args: string[] } { |
| 22 | if (process.platform === "win32") { |
| 23 | // Windows: Use PowerShell |
| 24 | return { |
| 25 | shell: "powershell.exe", |
| 26 | args: ["-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", command], |
| 27 | }; |
| 28 | } else { |
| 29 | // Unix/macOS: Use login shell to source .bashrc/.zshrc etc. |
| 30 | const userShell = process.env.SHELL || "/bin/bash"; |
| 31 | return { shell: userShell, args: ["-l", "-c", command] }; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | import { fileURLToPath } from "node:url"; |
| 36 | import { ToolImpl } from "."; |
| 37 | import { |
| 38 | isProcessBackgrounded, |
| 39 | markProcessAsRunning, |
| 40 | removeBackgroundedProcess, |
| 41 | removeRunningProcess, |
| 42 | updateProcessOutput, |
| 43 | } from "../../util/processTerminalStates"; |
| 44 | import { getBooleanArg, getStringArg } from "../parseArgs"; |
| 45 | |
| 46 | const asyncExec = util.promisify(childProcess.exec); |
| 47 | |
| 48 | // Add color-supporting environment variables |
| 49 | const getColorEnv = () => ({ |
| 50 | ...process.env, |
| 51 | FORCE_COLOR: "1", |
| 52 | COLORTERM: "truecolor", |
| 53 | TERM: "xterm-256color", |
| 54 | CLICOLOR: "1", |
| 55 | CLICOLOR_FORCE: "1", |
| 56 | }); |
| 57 | |
| 58 | const ENABLED_FOR_REMOTES = [ |
| 59 | "", |
| 60 | "local", |
| 61 | "wsl", |
| 62 | "dev-container", |
| 63 | "devcontainer", |
| 64 | "ssh-remote", |
| 65 | "attached-container", |
| 66 | "codespaces", |
| 67 | "tunnel", |
| 68 | ]; |
| 69 | |
| 70 | export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { |
| 71 | const command = getStringArg(args, "command"); |
| 72 | // Default to waiting for completion if not specified |
| 73 | const waitForCompletion = |
| 74 | getBooleanArg(args, "waitForCompletion", false) ?? true; |
| 75 | |
| 76 | const ideInfo = await extras.ide.getIdeInfo(); |
| 77 | const toolCallId = extras.toolCallId || ""; |
| 78 | |
| 79 | if (ENABLED_FOR_REMOTES.includes(ideInfo.remoteName)) { |
| 80 | // For streaming output |
| 81 | if (extras.onPartialOutput) { |
| 82 | try { |
| 83 | const workspaceDirs = await extras.ide.getWorkspaceDirs(); |
| 84 | |
| 85 | // Handle case where no workspace is available |
| 86 | let cwd: string; |
| 87 | if (workspaceDirs.length > 0) { |
| 88 | cwd = fileURLToPath(workspaceDirs[0]); |
| 89 | } else { |
| 90 | // Default to user's home directory with fallbacks |
| 91 | try { |
| 92 | cwd = process.env.HOME || process.env.USERPROFILE || process.cwd(); |
| 93 | } catch (error) { |
| 94 | // Final fallback if even process.cwd() fails - use system temp directory |
| 95 | cwd = os.tmpdir(); |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | return new Promise((resolve, reject) => { |
| 100 | let terminalOutput = ""; |
| 101 | |
| 102 | if (!waitForCompletion) { |
| 103 | const status = "Command is running in the background..."; |
| 104 | if (extras.onPartialOutput) { |
| 105 | extras.onPartialOutput({ |
| 106 | toolCallId, |
| 107 | contextItems: [ |
| 108 | { |
| 109 | name: "Terminal", |
| 110 | description: "Terminal command output", |
| 111 | content: "", |
| 112 | status: status, |
| 113 | }, |
| 114 | ], |
| 115 | }); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // Use spawn with color environment |
| 120 | const { shell, args } = getShellCommand(command); |
| 121 | const childProc = childProcess.spawn(shell, args, { |
| 122 | cwd, |
| 123 | env: getColorEnv(), // Add enhanced environment for colors |
| 124 | }); |
| 125 | |
| 126 | // Track this process for foreground cancellation |
| 127 | if (toolCallId && waitForCompletion) { |
| 128 | markProcessAsRunning( |
| 129 | toolCallId, |
| 130 | childProc, |
| 131 | extras.onPartialOutput, |
| 132 | terminalOutput, |
| 133 | ); |
| 134 | } |
| 135 | |
| 136 | childProc.stdout?.on("data", (data) => { |
| 137 | // Skip if this process has been backgrounded |
| 138 | if (isProcessBackgrounded(toolCallId)) return; |
| 139 | |
| 140 | const newOutput = getDecodedOutput(data); |
| 141 | terminalOutput += newOutput; |
| 142 | |
| 143 | // Update the tracked output for potential cancellation notifications |
| 144 | if (toolCallId && waitForCompletion) { |
| 145 | updateProcessOutput(toolCallId, terminalOutput); |
| 146 | } |
| 147 | |
| 148 | // Send partial output to UI |
| 149 | if (extras.onPartialOutput) { |
| 150 | const status = waitForCompletion |
| 151 | ? "" |
| 152 | : "Command is running in the background..."; |
| 153 | extras.onPartialOutput({ |
| 154 | toolCallId, |
| 155 | contextItems: [ |
| 156 | { |
| 157 | name: "Terminal", |
| 158 | description: "Terminal command output", |
| 159 | content: terminalOutput, |
| 160 | status: status, |
| 161 | }, |
| 162 | ], |
| 163 | }); |
| 164 | } |
| 165 | }); |
| 166 | |
| 167 | childProc.stderr?.on("data", (data) => { |
| 168 | // Skip if this process has been backgrounded |
| 169 | if (isProcessBackgrounded(toolCallId)) return; |
| 170 | |
| 171 | const newOutput = getDecodedOutput(data); |
| 172 | terminalOutput += newOutput; |
| 173 | |
| 174 | // Update the tracked output for potential cancellation notifications |
| 175 | if (toolCallId && waitForCompletion) { |
| 176 | updateProcessOutput(toolCallId, terminalOutput); |
| 177 | } |
| 178 | |
| 179 | // Send partial output to UI, status is not required |
| 180 | if (extras.onPartialOutput) { |
| 181 | extras.onPartialOutput({ |
| 182 | toolCallId, |
| 183 | contextItems: [ |
| 184 | { |
| 185 | name: "Terminal", |
| 186 | description: "Terminal command output", |
| 187 | content: terminalOutput, |
| 188 | }, |
| 189 | ], |
| 190 | }); |
| 191 | } |
| 192 | }); |
| 193 | |
| 194 | // If we don't need to wait for completion, resolve immediately |
| 195 | if (!waitForCompletion) { |
| 196 | const status = "Command is running in the background..."; |
| 197 | resolve([ |
| 198 | { |
| 199 | name: "Terminal", |
| 200 | description: "Terminal command output", |
| 201 | content: terminalOutput, |
| 202 | status: status, |
| 203 | }, |
| 204 | ]); |
| 205 | } |
| 206 | |
| 207 | childProc.on("close", (code) => { |
| 208 | // Clean up process tracking |
| 209 | if (toolCallId) { |
| 210 | if (isProcessBackgrounded(toolCallId)) { |
| 211 | removeBackgroundedProcess(toolCallId); |
| 212 | return; |
| 213 | } |
| 214 | // Remove from foreground tracking if it was tracked |
| 215 | removeRunningProcess(toolCallId); |
| 216 | } |
| 217 | |
| 218 | if (waitForCompletion) { |
| 219 | // Normal completion, resolve now |
| 220 | if (!code || code === 0) { |
| 221 | const status = "Command completed"; |
| 222 | resolve([ |
| 223 | { |
| 224 | name: "Terminal", |
| 225 | description: "Terminal command output", |
| 226 | content: terminalOutput, |
| 227 | status: status, |
| 228 | }, |
| 229 | ]); |
| 230 | } else { |
| 231 | const status = `Command failed with exit code ${code}`; |
| 232 | resolve([ |
| 233 | { |
| 234 | name: "Terminal", |
| 235 | description: "Terminal command output", |
| 236 | content: terminalOutput, |
| 237 | status: status, |
| 238 | }, |
| 239 | ]); |
| 240 | } |
| 241 | } else { |
| 242 | // Already resolved, just update the UI with final output |
| 243 | if (extras.onPartialOutput) { |
| 244 | const status = |
| 245 | code === 0 || !code |
| 246 | ? "\nBackground command completed" |
| 247 | : `\nBackground command failed with exit code ${code}`; |
| 248 | extras.onPartialOutput({ |
| 249 | toolCallId, |
| 250 | contextItems: [ |
| 251 | { |
| 252 | name: "Terminal", |
| 253 | description: "Terminal command output", |
| 254 | content: terminalOutput, |
| 255 | status: status, |
| 256 | }, |
| 257 | ], |
| 258 | }); |
| 259 | } |
| 260 | } |
| 261 | }); |
| 262 | |
| 263 | childProc.on("error", (error) => { |
| 264 | // Clean up process tracking |
| 265 | if (toolCallId) { |
| 266 | if (isProcessBackgrounded(toolCallId)) { |
| 267 | removeBackgroundedProcess(toolCallId); |
| 268 | return; |
| 269 | } |
| 270 | // Remove from foreground tracking if it was tracked |
| 271 | removeRunningProcess(toolCallId); |
| 272 | } |
| 273 | |
| 274 | reject(error); |
| 275 | }); |
| 276 | }); |
| 277 | } catch (error: any) { |
| 278 | throw error; |
| 279 | } |
| 280 | } else { |
| 281 | // Fallback to non-streaming for older clients |
| 282 | const workspaceDirs = await extras.ide.getWorkspaceDirs(); |
| 283 | |
| 284 | // Handle case where no workspace is available |
| 285 | let cwd: string; |
| 286 | if (workspaceDirs.length > 0) { |
| 287 | cwd = fileURLToPath(workspaceDirs[0]); |
| 288 | } else { |
| 289 | // Default to user's home directory with fallbacks |
| 290 | try { |
| 291 | cwd = process.env.HOME || process.env.USERPROFILE || process.cwd(); |
| 292 | } catch (error) { |
| 293 | // Final fallback if even process.cwd() fails - use system temp directory |
| 294 | cwd = os.tmpdir(); |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | if (waitForCompletion) { |
| 299 | // Standard execution, waiting for completion |
| 300 | try { |
| 301 | // Use spawn approach for consistency with streaming version |
| 302 | const { shell: nonStreamingShell, args: nonStreamingArgs } = |
| 303 | getShellCommand(command); |
| 304 | const output = await new Promise<{ stdout: string; stderr: string }>( |
| 305 | (resolve, reject) => { |
| 306 | const childProc = childProcess.spawn( |
| 307 | nonStreamingShell, |
| 308 | nonStreamingArgs, |
| 309 | { |
| 310 | cwd, |
| 311 | env: getColorEnv(), |
| 312 | }, |
| 313 | ); |
| 314 | |
| 315 | // Track this process for foreground cancellation |
| 316 | if (toolCallId) { |
| 317 | markProcessAsRunning(toolCallId, childProc, undefined, ""); |
| 318 | } |
| 319 | |
| 320 | let stdout = ""; |
| 321 | let stderr = ""; |
| 322 | |
| 323 | childProc.stdout?.on("data", (data) => { |
| 324 | stdout += getDecodedOutput(data); |
| 325 | }); |
| 326 | |
| 327 | childProc.stderr?.on("data", (data) => { |
| 328 | stderr += getDecodedOutput(data); |
| 329 | }); |
| 330 | |
| 331 | childProc.on("close", (code) => { |
| 332 | // Clean up process tracking |
| 333 | if (toolCallId) { |
| 334 | removeRunningProcess(toolCallId); |
| 335 | } |
| 336 | |
| 337 | if (code === 0) { |
| 338 | resolve({ stdout, stderr }); |
| 339 | } else { |
| 340 | const error = new Error( |
| 341 | `Command failed with exit code ${code}`, |
| 342 | ); |
| 343 | (error as any).stderr = stderr; |
| 344 | reject(error); |
| 345 | } |
| 346 | }); |
| 347 | |
| 348 | childProc.on("error", (error) => { |
| 349 | // Clean up process tracking |
| 350 | if (toolCallId) { |
| 351 | removeRunningProcess(toolCallId); |
| 352 | } |
| 353 | reject(error); |
| 354 | }); |
| 355 | }, |
| 356 | ); |
| 357 | |
| 358 | const status = "Command completed"; |
| 359 | return [ |
| 360 | { |
| 361 | name: "Terminal", |
| 362 | description: "Terminal command output", |
| 363 | content: output.stdout ?? "", |
| 364 | status: status, |
| 365 | }, |
| 366 | ]; |
| 367 | } catch (error: any) { |
| 368 | const status = `Command failed with: ${error.message || error.toString()}`; |
| 369 | return [ |
| 370 | { |
| 371 | name: "Terminal", |
| 372 | description: "Terminal command output", |
| 373 | content: error.stderr ?? error.toString(), |
| 374 | status: status, |
| 375 | }, |
| 376 | ]; |
| 377 | } |
| 378 | } else { |
| 379 | // For non-streaming but also not waiting for completion, use spawn |
| 380 | // but don't attach any listeners other than error |
| 381 | try { |
| 382 | // Use spawn with color environment |
| 383 | const { shell: detachedShell, args: detachedArgs } = |
| 384 | getShellCommand(command); |
| 385 | const childProc = childProcess.spawn(detachedShell, detachedArgs, { |
| 386 | cwd, |
| 387 | env: getColorEnv(), // Add color environment |
| 388 | // Detach the process so it's not tied to the parent |
| 389 | detached: true, |
| 390 | // Redirect to /dev/null equivalent (works cross-platform) |
| 391 | stdio: "ignore", |
| 392 | }); |
| 393 | |
| 394 | // Even for detached processes, add event handlers to clean up the background process map |
| 395 | childProc.on("close", () => { |
| 396 | if (isProcessBackgrounded(toolCallId)) { |
| 397 | removeBackgroundedProcess(toolCallId); |
| 398 | } |
| 399 | }); |
| 400 | |
| 401 | childProc.on("error", () => { |
| 402 | if (isProcessBackgrounded(toolCallId)) { |
| 403 | removeBackgroundedProcess(toolCallId); |
| 404 | } |
| 405 | }); |
| 406 | |
| 407 | // Unref the child to allow the Node.js process to exit |
| 408 | childProc.unref(); |
| 409 | const status = "Command is running in the background..."; |
| 410 | return [ |
| 411 | { |
| 412 | name: "Terminal", |
| 413 | description: "Terminal command output", |
| 414 | content: status, |
| 415 | status: status, |
| 416 | }, |
| 417 | ]; |
| 418 | } catch (error: any) { |
| 419 | const status = `Command failed with: ${error.message || error.toString()}`; |
| 420 | return [ |
| 421 | { |
| 422 | name: "Terminal", |
| 423 | description: "Terminal command output", |
| 424 | content: status, |
| 425 | status: status, |
| 426 | }, |
| 427 | ]; |
| 428 | } |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // For remote environments, just run the command |
| 434 | // Note: waitForCompletion is not supported in remote environments yet |
| 435 | await extras.ide.runCommand(command); |
| 436 | return [ |
| 437 | { |
| 438 | name: "Terminal", |
| 439 | description: "Terminal command output", |
| 440 | content: |
| 441 | "Terminal output not available. This is only available in local development environments and not in SSH environments for example.", |
| 442 | status: "Command failed", |
| 443 | }, |
| 444 | ]; |
| 445 | }; |