Elffuss BraidHub

kikocis/continue public

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