-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathrunTerminalCommand.ts
More file actions
609 lines (545 loc) · 20.7 KB
/
runTerminalCommand.ts
File metadata and controls
609 lines (545 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import iconv from "iconv-lite";
import childProcess from "node:child_process";
import os from "node:os";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
// Default timeout for terminal commands (2 minutes)
const DEFAULT_TOOL_TIMEOUT_MS = 120_000;
// Automatically decode the buffer according to the platform to avoid garbled Chinese
function getDecodedOutput(data: Buffer): string {
if (process.platform === "win32") {
try {
let out = iconv.decode(data, "utf-8");
if (/�/.test(out)) {
out = iconv.decode(data, "gbk");
}
return out;
} catch {
return iconv.decode(data, "gbk");
}
} else {
return data.toString();
}
}
// Tracks whether PowerShell failed to spawn on Windows (e.g., blocked by corporate policy)
// so subsequent calls can fall back to cmd.exe without retrying PowerShell.
let _powershellUnavailable = false;
// Simple helper function to use login shell on Unix/macOS and PowerShell on Windows
function getShellCommand(command: string): { shell: string; args: string[] } {
if (process.platform === "win32") {
if (!_powershellUnavailable) {
// Windows: prefer PowerShell for richer command support
return {
shell: "powershell.exe",
args: ["-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", command],
};
}
// PowerShell unavailable (e.g., blocked by corporate security policy);
// fall back to cmd.exe via COMSPEC.
return {
shell: process.env.COMSPEC || "cmd.exe",
args: ["/D", "/S", "/C", command],
};
} else {
// Unix/macOS: Use login shell to source .bashrc/.zshrc etc.
const userShell = process.env.SHELL || "/bin/bash";
return { shell: userShell, args: ["-l", "-c", command] };
}
}
import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import {
isProcessBackgrounded,
markProcessAsRunning,
removeBackgroundedProcess,
removeRunningProcess,
updateProcessOutput,
} from "../../util/processTerminalStates";
import { getBooleanArg, getStringArg } from "../parseArgs";
/**
* Resolves the working directory from workspace dirs.
* Falls back to home directory or temp directory if no workspace is available.
*/
function resolveWorkingDirectory(workspaceDirs: string[]): string {
// Handle file:// URIs (local workspaces)
const fileWorkspaceDir = workspaceDirs.find((dir) =>
dir.startsWith("file:/"),
);
if (fileWorkspaceDir) {
try {
return fileURLToPath(fileWorkspaceDir);
} catch {
// fileURLToPath can fail on malformed URIs or in some remote environments
// Fall through to default handling
}
}
// Handle other URI schemes (vscode-remote://wsl, vscode-remote://ssh-remote, etc.)
const remoteWorkspaceDir = workspaceDirs.find(
(dir) => dir.includes("://") && !dir.startsWith("file:/"),
);
if (remoteWorkspaceDir) {
try {
const url = new URL(remoteWorkspaceDir);
return decodeURIComponent(url.pathname);
} catch {
// Fall through to other handlers
}
}
// Default to user's home directory with fallbacks
try {
return process.env.HOME || process.env.USERPROFILE || process.cwd();
} catch {
// Final fallback if even process.cwd() fails - use system temp directory
return os.tmpdir();
}
}
// Add color-supporting environment variables
const getColorEnv = () => ({
...process.env,
FORCE_COLOR: "1",
COLORTERM: "truecolor",
TERM: "xterm-256color",
CLICOLOR: "1",
CLICOLOR_FORCE: "1",
});
// Only spawn processes locally when there is no remote workspace.
// With extensionKind: ["ui", "workspace"], the extension host almost always
// runs on the local machine. childProcess.spawn() executes on the extension
// host, so for any remote workspace it would run commands on the wrong machine
// (or fail with ENOENT when the local shell doesn't match the remote OS).
// All remote types delegate to ide.runCommand() which routes through VS Code's
// integrated terminal and executes in the correct remote environment.
const LOCAL_ONLY = ["", "local"];
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const command = getStringArg(args, "command");
// Default to waiting for completion if not specified
const waitForCompletion =
getBooleanArg(args, "waitForCompletion", false) ?? true;
const ideInfo = await extras.ide.getIdeInfo();
const toolCallId = extras.toolCallId || "";
if (LOCAL_ONLY.includes(ideInfo.remoteName)) {
// For streaming output
if (extras.onPartialOutput) {
try {
const workspaceDirs = await extras.ide.getWorkspaceDirs();
const cwd = resolveWorkingDirectory(workspaceDirs);
return new Promise((resolve, reject) => {
let terminalOutput = "";
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let sigkillTimeoutId: ReturnType<typeof setTimeout> | undefined;
if (!waitForCompletion) {
const status = "Command is running in the background...";
if (extras.onPartialOutput) {
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: "",
status: status,
},
],
});
}
}
// Use spawn with color environment
const { shell, args } = getShellCommand(command);
const childProc = childProcess.spawn(shell, args, {
cwd,
env: getColorEnv(), // Add enhanced environment for colors
});
// Track this process for foreground cancellation
if (toolCallId && waitForCompletion) {
markProcessAsRunning(
toolCallId,
childProc,
extras.onPartialOutput,
terminalOutput,
);
}
// Check if the child process is still running.
// `childProc.killed` only indicates that kill() was called,
// not that the process has actually exited.
const isRunning = () =>
childProc.exitCode === null && childProc.signalCode === null;
// Set up timeout for waitForCompletion mode
if (waitForCompletion) {
timeoutId = setTimeout(() => {
if (isRunning()) {
terminalOutput +=
"\n[Timeout: process killed after 2 minutes]\n";
// Update UI with timeout message
if (extras.onPartialOutput) {
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: "Command timed out",
},
],
});
}
// Try graceful termination first
childProc.kill("SIGTERM");
// Force kill after 5 seconds if still running
sigkillTimeoutId = setTimeout(() => {
if (isRunning()) {
childProc.kill("SIGKILL");
}
}, 5_000);
}
}, DEFAULT_TOOL_TIMEOUT_MS);
}
childProc.stdout?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Update the tracked output for potential cancellation notifications
if (toolCallId && waitForCompletion) {
updateProcessOutput(toolCallId, terminalOutput);
}
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion
? ""
: "Command is running in the background...";
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
],
});
}
});
childProc.stderr?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Update the tracked output for potential cancellation notifications
if (toolCallId && waitForCompletion) {
updateProcessOutput(toolCallId, terminalOutput);
}
// Send partial output to UI, status is not required
if (extras.onPartialOutput) {
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
},
],
});
}
});
// If we don't need to wait for completion, resolve immediately
if (!waitForCompletion) {
const status = "Command is running in the background...";
resolve([
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
]);
}
childProc.on("close", (code) => {
// Clear timeout on normal completion
if (timeoutId) {
clearTimeout(timeoutId);
}
// Clear inner SIGKILL timeout if process exits before grace period
if (sigkillTimeoutId) {
clearTimeout(sigkillTimeoutId);
}
// Clean up process tracking
if (toolCallId) {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
// Remove from foreground tracking if it was tracked
removeRunningProcess(toolCallId);
}
if (waitForCompletion) {
// Normal completion, resolve now
if (!code || code === 0) {
const status = "Command completed";
resolve([
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
]);
} else {
const status = `Command failed with exit code ${code}`;
resolve([
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
]);
}
} else {
// Already resolved, just update the UI with final output
if (extras.onPartialOutput) {
const status =
code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`;
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
],
});
}
}
});
childProc.on("error", (error: NodeJS.ErrnoException) => {
// Clear timeout on error
if (timeoutId) {
clearTimeout(timeoutId);
}
// Clear SIGKILL timeout to prevent delayed kill after rejection
if (sigkillTimeoutId) {
clearTimeout(sigkillTimeoutId);
}
// Clean up process tracking
if (toolCallId) {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
// Remove from foreground tracking if it was tracked
removeRunningProcess(toolCallId);
}
// If PowerShell failed to spawn on Windows (e.g., blocked by corporate policy),
// mark it unavailable so future calls fall back to cmd.exe automatically.
if (
process.platform === "win32" &&
(error.code === "UNKNOWN" || error.code === "ENOENT")
) {
_powershellUnavailable = true;
}
reject(error);
});
});
} catch (error: any) {
throw error;
}
} else {
// Fallback to non-streaming for older clients
const workspaceDirs = await extras.ide.getWorkspaceDirs();
const cwd = resolveWorkingDirectory(workspaceDirs);
if (waitForCompletion) {
// Standard execution, waiting for completion
try {
// Use spawn approach for consistency with streaming version
const { shell: nonStreamingShell, args: nonStreamingArgs } =
getShellCommand(command);
const output = await new Promise<{ stdout: string; stderr: string }>(
(resolve, reject) => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let sigkillTimeoutId: ReturnType<typeof setTimeout> | undefined;
const childProc = childProcess.spawn(
nonStreamingShell,
nonStreamingArgs,
{
cwd,
env: getColorEnv(),
},
);
// Track this process for foreground cancellation
if (toolCallId) {
markProcessAsRunning(toolCallId, childProc, undefined, "");
}
let stdout = "";
let stderr = "";
// Check if the child process is still running.
// `childProc.killed` only indicates that kill() was called,
// not that the process has actually exited.
const isRunning = () =>
childProc.exitCode === null && childProc.signalCode === null;
// Set up timeout
timeoutId = setTimeout(() => {
if (isRunning()) {
stderr += "\n[Timeout: process killed after 2 minutes]\n";
// Try graceful termination first
childProc.kill("SIGTERM");
// Force kill after 5 seconds if still running
sigkillTimeoutId = setTimeout(() => {
if (isRunning()) {
childProc.kill("SIGKILL");
}
}, 5_000);
}
}, DEFAULT_TOOL_TIMEOUT_MS);
childProc.stdout?.on("data", (data) => {
stdout += getDecodedOutput(data);
});
childProc.stderr?.on("data", (data) => {
stderr += getDecodedOutput(data);
});
childProc.on("close", (code) => {
// Clear outer timeout
if (timeoutId) {
clearTimeout(timeoutId);
}
// Clear inner SIGKILL timeout if process exits before grace period
if (sigkillTimeoutId) {
clearTimeout(sigkillTimeoutId);
}
// Clean up process tracking
if (toolCallId) {
removeRunningProcess(toolCallId);
}
if (code === 0) {
resolve({ stdout, stderr });
} else {
const error = new ContinueError(
ContinueErrorReason.CommandExecutionFailed,
`Command failed with exit code ${code}`,
);
(error as any).stderr = stderr;
reject(error);
}
});
childProc.on("error", (error: NodeJS.ErrnoException) => {
// Clear timeout on error
if (timeoutId) {
clearTimeout(timeoutId);
}
// Clear SIGKILL timeout to prevent delayed kill after rejection
if (sigkillTimeoutId) {
clearTimeout(sigkillTimeoutId);
}
// Clean up process tracking
if (toolCallId) {
removeRunningProcess(toolCallId);
}
// If PowerShell failed to spawn on Windows (e.g., blocked by corporate policy),
// mark it unavailable so future calls fall back to cmd.exe automatically.
if (
process.platform === "win32" &&
(error.code === "UNKNOWN" || error.code === "ENOENT")
) {
_powershellUnavailable = true;
}
reject(error);
});
},
);
const status = "Command completed";
return [
{
name: "Terminal",
description: "Terminal command output",
content: output.stdout ?? "",
status: status,
},
];
} catch (error: any) {
const status = `Command failed with: ${error.message || error.toString()}`;
return [
{
name: "Terminal",
description: "Terminal command output",
content: error.stderr ?? error.toString(),
status: status,
},
];
}
} else {
// For non-streaming but also not waiting for completion, use spawn
// but don't attach any listeners other than error
try {
// Use spawn with color environment
const { shell: detachedShell, args: detachedArgs } =
getShellCommand(command);
const childProc = childProcess.spawn(detachedShell, detachedArgs, {
cwd,
env: getColorEnv(), // Add color environment
// Detach the process so it's not tied to the parent
detached: true,
// Redirect to /dev/null equivalent (works cross-platform)
stdio: "ignore",
});
// Even for detached processes, add event handlers to clean up the background process map
childProc.on("close", () => {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
}
});
childProc.on("error", (error: NodeJS.ErrnoException) => {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
}
// If PowerShell failed to spawn on Windows, mark it unavailable for future calls.
if (
process.platform === "win32" &&
(error.code === "UNKNOWN" || error.code === "ENOENT")
) {
_powershellUnavailable = true;
}
});
// Unref the child to allow the Node.js process to exit
childProc.unref();
const status = "Command is running in the background...";
return [
{
name: "Terminal",
description: "Terminal command output",
content: status,
status: status,
},
];
} catch (error: any) {
const status = `Command failed with: ${error.message || error.toString()}`;
return [
{
name: "Terminal",
description: "Terminal command output",
content: status,
status: status,
},
];
}
}
}
}
// For remote environments (SSH, WSL, Dev Container, Codespaces, etc.),
// delegate to VS Code's integrated terminal which handles remote execution.
// Note: output capture and waitForCompletion are not yet supported for remotes.
await extras.ide.runCommand(command);
return [
{
name: "Terminal",
description: "Terminal command output",
content:
"Command executed in remote terminal. Output capture is not yet available for remote environments.",
status: "Command executed",
},
];
};