Elffuss BraidHub

kikocis/continue public

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