Elffuss BraidHub

kikocis/continue public

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