Elffuss BraidHub

kikocis/continue public

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