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