Elffuss BraidHub

kikocis/continue public

ad9b2d0f49b2 · 4.7 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: Use login shell to source .bashrc/.zshrc etc.
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 let stdout = "";
65 let stderr = "";
66 let timeoutId: NodeJS.Timeout;
67 let isResolved = false;
68
69 const TIMEOUT_MS =
70 process.env.NODE_ENV === "test" && process.env.TEST_TERMINAL_TIMEOUT
71 ? parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10)
72 : 30000; // 30 seconds default, configurable for tests
73
74 const resetTimeout = () => {
75 if (timeoutId) {
76 clearTimeout(timeoutId);
77 }
78 timeoutId = setTimeout(() => {
79 if (isResolved) return;
80 isResolved = true;
81 child.kill();
82 let output = stdout + (stderr ? `\nStderr: ${stderr}` : "");
83 output += `\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]`;
84
85 // Truncate output if it has too many lines
86 const lines = output.split("\n");
87 if (lines.length > 5000) {
88 const truncatedOutput = lines.slice(0, 5000).join("\n");
89 resolve(
90 truncatedOutput +
91 `\n\n[Output truncated to first 5000 lines of ${lines.length} total]`,
92 );
93 return;
94 }
95
96 resolve(output);
97 }, TIMEOUT_MS);
98 };
99
100 // Start the initial timeout
101 resetTimeout();
102
103 child.stdout.on("data", (data) => {
104 stdout += data.toString();
105 resetTimeout();
106 });
107
108 child.stderr.on("data", (data) => {
109 stderr += data.toString();
110 resetTimeout();
111 });
112
113 child.on("close", (code) => {
114 if (isResolved) return;
115 isResolved = true;
116
117 if (timeoutId) {
118 clearTimeout(timeoutId);
119 }
120
121 // Only reject on non-zero exit code if there's also stderr
122 if (code !== 0 && stderr) {
123 reject(`Error (exit code ${code}): ${stderr}`);
124 return;
125 }
126
127 // Track specific git operations only after successful execution
128 if (code === 0) {
129 if (isGitCommitCommand(command)) {
130 telemetryService.recordCommitCreated();
131 } else if (isPullRequestCommand(command)) {
132 telemetryService.recordPullRequestCreated();
133 }
134 }
135
136 let output = stdout;
137 if (stderr) {
138 output = stdout + `\nStderr: ${stderr}`;
139 }
140
141 // Truncate output if it has too many lines
142 const lines = output.split("\n");
143 if (lines.length > 5000) {
144 const truncatedOutput = lines.slice(0, 5000).join("\n");
145 resolve(
146 truncatedOutput +
147 `\n\n[Output truncated to first 5000 lines of ${lines.length} total]`,
148 );
149 return;
150 }
151
152 resolve(output);
153 });
154
155 child.on("error", (error) => {
156 if (isResolved) return;
157 isResolved = true;
158
159 if (timeoutId) {
160 clearTimeout(timeoutId);
161 }
162 reject(`Error: ${error.message}`);
163 });
164 });
165 },
166};