Elffuss BraidHub

kikocis/continue public

890519d0e11e · 5.1 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 command: {
40 type: "string",
41 description: "The command to execute in the terminal.",
42 required: true,
43 },
44 },
45 readonly: false,
46 isBuiltIn: true,
47 evaluateToolCallPolicy: (
48 basePolicy: ToolPolicy,
49 parsedArgs: Record<string, unknown>,
50 ): ToolPolicy => {
51 return evaluateTerminalCommandSecurity(
52 basePolicy,
53 parsedArgs.command as string,
54 );
55 },
56 preprocess: async (args) => {
57 const command = args.command;
58 if (!command || typeof command !== "string") {
59 throw new Error("command arg is required and must be a non-empty string");
60 }
61 const truncatedCmd =
62 command.length > 60 ? command.substring(0, 60) + "..." : command;
63 return {
64 args,
65 preview: [
66 {
67 type: "text",
68 content: `Will run: ${truncatedCmd}`,
69 },
70 ],
71 };
72 },
73 run: async ({ command }: { command: string }): Promise<string> => {
74 return new Promise((resolve, reject) => {
75 // Use same shell logic as core implementation
76 const { shell, args } = getShellCommand(command);
77 const child = spawn(shell, args);
78 let stdout = "";
79 let stderr = "";
80 let timeoutId: NodeJS.Timeout;
81 let isResolved = false;
82
83 const TIMEOUT_MS =
84 process.env.NODE_ENV === "test" && process.env.TEST_TERMINAL_TIMEOUT
85 ? parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10)
86 : 30000; // 30 seconds default, configurable for tests
87
88 const resetTimeout = () => {
89 if (timeoutId) {
90 clearTimeout(timeoutId);
91 }
92 timeoutId = setTimeout(() => {
93 if (isResolved) return;
94 isResolved = true;
95 child.kill();
96 let output = stdout + (stderr ? `\nStderr: ${stderr}` : "");
97 output += `\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]`;
98
99 // Truncate output if it has too many lines
100 const lines = output.split("\n");
101 if (lines.length > 5000) {
102 const truncatedOutput = lines.slice(0, 5000).join("\n");
103 resolve(
104 truncatedOutput +
105 `\n\n[Output truncated to first 5000 lines of ${lines.length} total]`,
106 );
107 return;
108 }
109
110 resolve(output);
111 }, TIMEOUT_MS);
112 };
113
114 // Start the initial timeout
115 resetTimeout();
116
117 child.stdout.on("data", (data) => {
118 stdout += data.toString();
119 resetTimeout();
120 });
121
122 child.stderr.on("data", (data) => {
123 stderr += data.toString();
124 resetTimeout();
125 });
126
127 child.on("close", (code) => {
128 if (isResolved) return;
129 isResolved = true;
130
131 if (timeoutId) {
132 clearTimeout(timeoutId);
133 }
134
135 // Only reject on non-zero exit code if there's also stderr
136 if (code !== 0 && stderr) {
137 reject(`Error (exit code ${code}): ${stderr}`);
138 return;
139 }
140
141 // Track specific git operations only after successful execution
142 if (code === 0) {
143 if (isGitCommitCommand(command)) {
144 telemetryService.recordCommitCreated();
145 } else if (isPullRequestCommand(command)) {
146 telemetryService.recordPullRequestCreated();
147 }
148 }
149
150 let output = stdout;
151 if (stderr) {
152 output = stdout + `\nStderr: ${stderr}`;
153 }
154
155 // Truncate output if it has too many lines
156 const lines = output.split("\n");
157 if (lines.length > 5000) {
158 const truncatedOutput = lines.slice(0, 5000).join("\n");
159 resolve(
160 truncatedOutput +
161 `\n\n[Output truncated to first 5000 lines of ${lines.length} total]`,
162 );
163 return;
164 }
165
166 resolve(output);
167 });
168
169 child.on("error", (error) => {
170 if (isResolved) return;
171 isResolved = true;
172
173 if (timeoutId) {
174 clearTimeout(timeoutId);
175 }
176 reject(`Error: ${error.message}`);
177 });
178 });
179 },
180};