Elffuss BraidHub

kikocis/continue public

88f9397dc3b6 · 4.9 KiBRawPermalink
1import { spawn } from "child_process";
2
3import { telemetryService } from "../telemetry/telemetryService.js";
4import {
5 isGitCommitCommand,
6 isPullRequestCommand,
7} from "../telemetry/utils.js";
8
9import { Tool } from "./types.js";
10
11// Helper function to use login shell on Unix/macOS and PowerShell on Windows
12function getShellCommand(command: string): { shell: string; args: string[] } {
13 if (process.platform === "win32") {
14 // Windows: Use PowerShell
15 return {
16 shell: "powershell.exe",
17 args: ["-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", command],
18 };
19 } else {
20 // Unix/macOS: Just run the user's shell as a login shell
21 const userShell = process.env.SHELL || "/bin/bash";
22 return { shell: userShell, args: ["-l", "-c", command] };
23 }
24}
25
26export const runTerminalCommandTool: Tool = {
27 name: "Bash",
28 displayName: "Bash",
29 description: `Executes a terminal command and returns the output
30
31The command will be executed from the current working directory: ${process.cwd()}
32`,
33 parameters: {
34 command: {
35 type: "string",
36 description: "The command to execute in the terminal.",
37 required: true,
38 },
39 },
40 readonly: false,
41 isBuiltIn: true,
42 preprocess: async (args) => {
43 const command = args.command;
44 if (!command || typeof command !== "string") {
45 throw new Error("command arg is required and must be a non-empty string");
46 }
47 const truncatedCmd =
48 command.length > 60 ? command.substring(0, 60) + "..." : command;
49 return {
50 args,
51 preview: [
52 {
53 type: "text",
54 content: `Will run: ${truncatedCmd}`,
55 },
56 ],
57 };
58 },
59 run: async ({ command }: { command: string }): Promise<string> => {
60 return new Promise((resolve, reject) => {
61 // Use same shell logic as core implementation
62 const { shell, args } = getShellCommand(command);
63 const child = spawn(shell, args, {
64 cwd: process.cwd(),
65 env: process.env,
66 stdio: ["ignore", "pipe", "pipe"], // prevent child from reading TTY input
67 detached: false,
68 });
69 let stdout = "";
70 let stderr = "";
71 let timeoutId: NodeJS.Timeout;
72 let isResolved = false;
73
74 const TIMEOUT_MS =
75 process.env.NODE_ENV === "test" && process.env.TEST_TERMINAL_TIMEOUT
76 ? parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10)
77 : 30000; // 30 seconds default, configurable for tests
78
79 const resetTimeout = () => {
80 if (timeoutId) {
81 clearTimeout(timeoutId);
82 }
83 timeoutId = setTimeout(() => {
84 if (isResolved) return;
85 isResolved = true;
86 child.kill();
87 let output = stdout + (stderr ? `\nStderr: ${stderr}` : "");
88 output += `\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]`;
89
90 // Truncate output if it has too many lines
91 const lines = output.split("\n");
92 if (lines.length > 5000) {
93 const truncatedOutput = lines.slice(0, 5000).join("\n");
94 resolve(
95 truncatedOutput +
96 `\n\n[Output truncated to first 5000 lines of ${lines.length} total]`,
97 );
98 return;
99 }
100
101 resolve(output);
102 }, TIMEOUT_MS);
103 };
104
105 // Start the initial timeout
106 resetTimeout();
107
108 child.stdout.on("data", (data) => {
109 stdout += data.toString();
110 resetTimeout();
111 });
112
113 child.stderr.on("data", (data) => {
114 stderr += data.toString();
115 resetTimeout();
116 });
117
118 child.on("close", (code) => {
119 if (isResolved) return;
120 isResolved = true;
121
122 if (timeoutId) {
123 clearTimeout(timeoutId);
124 }
125
126 // Only reject on non-zero exit code if there's also stderr
127 if (code !== 0 && stderr) {
128 reject(`Error (exit code ${code}): ${stderr}`);
129 return;
130 }
131
132 // Track specific git operations only after successful execution
133 if (code === 0) {
134 if (isGitCommitCommand(command)) {
135 telemetryService.recordCommitCreated();
136 } else if (isPullRequestCommand(command)) {
137 telemetryService.recordPullRequestCreated();
138 }
139 }
140
141 let output = stdout;
142 if (stderr) {
143 output = stdout + `\nStderr: ${stderr}`;
144 }
145
146 // Truncate output if it has too many lines
147 const lines = output.split("\n");
148 if (lines.length > 5000) {
149 const truncatedOutput = lines.slice(0, 5000).join("\n");
150 resolve(
151 truncatedOutput +
152 `\n\n[Output truncated to first 5000 lines of ${lines.length} total]`,
153 );
154 return;
155 }
156
157 resolve(output);
158 });
159
160 child.on("error", (error) => {
161 if (isResolved) return;
162 isResolved = true;
163
164 if (timeoutId) {
165 clearTimeout(timeoutId);
166 }
167 reject(`Error: ${error.message}`);
168 });
169 });
170 },
171};