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