-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathbash-handler.ts
More file actions
360 lines (330 loc) · 10.1 KB
/
bash-handler.ts
File metadata and controls
360 lines (330 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import { spawn } from "child_process";
import { DEFAULT_BASH_TIMEOUT_MS, clampBashTimeoutMs } from "../common/bash-timeout";
import { killProcessTree } from "../common/process-tree";
import type { ProcessTimeoutControl, ProcessTimeoutInfo, ToolExecutionContext, ToolExecutionResult } from "./executor";
import {
buildDisableExtglobCommand,
buildShellEnv,
buildShellInitCommand,
resolveShellPath,
rewriteWindowsNullRedirect,
toNativeCwd,
} from "../common/shell-utils";
const MAX_OUTPUT_CHARS = 30000;
const MAX_CAPTURE_CHARS = 10 * 1024 * 1024;
const sessionWorkingDirs = new Map<string, string>();
type ToolCommandResult = {
ok: boolean;
output: string;
cwd: string | null;
exitCode: number | null;
signal: string | null;
truncated: boolean;
shellPath?: string;
startCwd?: string;
timedOut?: boolean;
timeoutMs?: number;
deadlineAt?: string;
};
export async function handleBashTool(
args: Record<string, unknown>,
context: ToolExecutionContext
): Promise<ToolExecutionResult> {
const command = typeof args.command === "string" ? args.command : "";
if (!command.trim()) {
return {
ok: false,
name: "bash",
error: 'Missing required "command" string.',
};
}
const startCwd = getSessionCwd(context.sessionId, context.projectRoot);
const { shellPath, shellArgs, marker } = buildShellCommand(command);
const execution = await executeShellCommand(shellPath, shellArgs, startCwd, command, context);
const result = buildToolCommandResult(
execution.stdout,
execution.stderr,
marker,
execution.exitCode,
execution.signal,
shellPath,
startCwd,
execution.timedOut,
execution.timeoutMs,
execution.deadlineAtMs
);
updateSessionCwd(context.sessionId, startCwd, result.cwd);
if (execution.error || result.exitCode !== 0 || result.signal !== null) {
const errorMessage = buildErrorMessage(result.exitCode, result.signal, execution.error, execution.timedOut);
return formatResult({ ...result, ok: false }, "bash", errorMessage);
}
return formatResult(result, "bash");
}
function getSessionCwd(sessionId: string, fallback: string): string {
return sessionWorkingDirs.get(sessionId) ?? fallback;
}
function updateSessionCwd(sessionId: string, fallback: string, cwd: string | null): void {
const nextCwd = cwd ?? fallback;
sessionWorkingDirs.set(sessionId, nextCwd);
}
function buildShellCommand(command: string): {
shellPath: string;
shellArgs: string[];
marker: string;
} {
const shellPath = resolveShellPath();
const marker = buildMarker();
const initCommand = buildShellInitCommand(shellPath);
const disableExtglobCommand = buildDisableExtglobCommand(shellPath);
const normalizedCommand = rewriteWindowsNullRedirect(command);
const wrappedParts = [];
if (initCommand) {
wrappedParts.push(initCommand);
}
if (disableExtglobCommand) {
wrappedParts.push(disableExtglobCommand);
}
wrappedParts.push(
normalizedCommand,
"__DEEPCODE_STATUS__=$?",
`printf '%s%s\\n' "${marker}" "$PWD"`,
"exit $__DEEPCODE_STATUS__"
);
const wrappedCommand = `{ ${wrappedParts.join("; ")}; } < /dev/null`;
return { shellPath, shellArgs: ["-c", wrappedCommand], marker };
}
async function executeShellCommand(
shellPath: string,
shellArgs: string[],
cwd: string,
command: string,
context: ToolExecutionContext
): Promise<{
stdout: string;
stderr: string;
exitCode: number | null;
signal: string | null;
error?: string;
timedOut: boolean;
timeoutMs: number;
deadlineAtMs: number;
}> {
return new Promise((resolve) => {
const detached = process.platform !== "win32";
const configuredEnv = context.createOpenAIClient?.().env ?? {};
const minTimeoutMs = context.bashMinTimeoutMs;
const initialTimeoutMs = clampBashTimeoutMs(context.bashTimeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, minTimeoutMs);
const startedAtMs = Date.now();
let timeoutMs = initialTimeoutMs;
let deadlineAtMs = startedAtMs + timeoutMs;
let timedOut = false;
let settled = false;
let timeoutTimer: ReturnType<typeof setTimeout> | null = null;
const child = spawn(shellPath, shellArgs, {
cwd,
env: buildShellEnv(shellPath, configuredEnv),
detached,
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"],
});
const pid = child.pid;
const getTimeoutInfo = (): ProcessTimeoutInfo => ({
timeoutMs,
startedAtMs,
deadlineAtMs,
timedOut,
});
const stopTimeoutTimer = () => {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
};
const triggerTimeout = () => {
if (settled || timedOut || typeof pid !== "number") {
return;
}
timedOut = true;
stopTimeoutTimer();
killProcessTree(pid, "SIGKILL");
};
const scheduleTimeout = () => {
stopTimeoutTimer();
if (settled) {
return;
}
const remainingMs = Math.max(0, deadlineAtMs - Date.now());
timeoutTimer = setTimeout(triggerTimeout, remainingMs);
};
const timeoutControl: ProcessTimeoutControl = {
getInfo: getTimeoutInfo,
setTimeoutMs: (nextTimeoutMs) => {
timeoutMs = clampBashTimeoutMs(nextTimeoutMs, minTimeoutMs);
deadlineAtMs = startedAtMs + timeoutMs;
if (deadlineAtMs <= Date.now()) {
triggerTimeout();
} else {
scheduleTimeout();
}
return getTimeoutInfo();
},
};
if (typeof pid === "number") {
context.onProcessStart?.(pid, command);
context.onProcessTimeoutControl?.(pid, timeoutControl);
scheduleTimeout();
}
let stdout = "";
let stderr = "";
let error: string | undefined;
child.stdout?.on("data", (chunk: string | Buffer) => {
stdout = appendChunk(stdout, chunk);
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
context.onProcessStdout?.(pid as number, text);
});
child.stderr?.on("data", (chunk: string | Buffer) => {
stderr = appendChunk(stderr, chunk);
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
context.onProcessStdout?.(pid as number, text);
});
child.on("error", (spawnError) => {
error = spawnError.message;
});
child.on("close", (code, signal) => {
settled = true;
stopTimeoutTimer();
if (typeof pid === "number") {
context.onProcessTimeoutControl?.(pid, null);
context.onProcessExit?.(pid);
}
resolve({
stdout,
stderr,
exitCode: typeof code === "number" ? code : null,
signal: signal ?? null,
error,
timedOut,
timeoutMs,
deadlineAtMs,
});
});
});
}
function appendChunk(existing: string, chunk: string | Buffer): string {
if (existing.length >= MAX_CAPTURE_CHARS) {
return existing;
}
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
const remaining = MAX_CAPTURE_CHARS - existing.length;
return `${existing}${text.slice(0, remaining)}`;
}
function buildMarker(): string {
const token = Math.random().toString(36).slice(2);
return `__DEEPCODE_PWD__${token}__`;
}
function buildToolCommandResult(
stdout: string,
stderr: string,
marker: string,
exitCode: number | null,
signal: string | null,
shellPath: string,
startCwd: string,
timedOut: boolean = false,
timeoutMs?: number,
deadlineAtMs?: number
): ToolCommandResult {
const { output: cleanedStdout, cwd } = stripMarker(stdout, marker);
const combined = joinOutput(cleanedStdout, stderr);
const { text, truncated } = truncateOutput(combined);
return {
ok: exitCode === 0 && signal === null,
output: text,
cwd,
exitCode,
signal,
truncated,
shellPath,
startCwd,
timedOut,
timeoutMs,
deadlineAt: typeof deadlineAtMs === "number" ? new Date(deadlineAtMs).toISOString() : undefined,
};
}
function stripMarker(stdout: string, marker: string): { output: string; cwd: string | null } {
if (!stdout) {
return { output: "", cwd: null };
}
const lines = stdout.split(/\r?\n/);
let markerIndex = -1;
for (let i = lines.length - 1; i >= 0; i -= 1) {
if (lines[i].startsWith(marker)) {
markerIndex = i;
break;
}
}
if (markerIndex === -1) {
return { output: stdout, cwd: null };
}
const markerLine = lines[markerIndex];
const shellCwd = markerLine.slice(marker.length).trim();
const cwd = shellCwd ? toNativeCwd(shellCwd) : null;
lines.splice(markerIndex, 1);
return { output: lines.join("\n"), cwd };
}
function joinOutput(stdout: string, stderr: string): string {
const trimmedStdout = stdout ?? "";
const trimmedStderr = stderr ?? "";
if (trimmedStdout && trimmedStderr) {
return `${trimmedStdout}\n${trimmedStderr}`;
}
return trimmedStdout || trimmedStderr;
}
function truncateOutput(output: string): { text: string; truncated: boolean } {
if (output.length <= MAX_OUTPUT_CHARS) {
return { text: output, truncated: false };
}
return { text: output.slice(0, MAX_OUTPUT_CHARS), truncated: true };
}
function buildErrorMessage(exitCode: number | null, signal: string | null, error?: string, timedOut = false): string {
if (error) {
return error;
}
if (timedOut) {
return "Command timed out.";
}
if (signal) {
return `Command terminated by signal ${signal}.`;
}
if (exitCode !== null) {
return `Command failed with exit code ${exitCode}.`;
}
return "Command failed.";
}
function formatResult(result: ToolCommandResult, name: string, errorMessage?: string): ToolExecutionResult {
const metadata: Record<string, unknown> = {
exitCode: result.exitCode,
signal: result.signal,
cwd: result.cwd,
truncated: result.truncated,
shellPath: result.shellPath,
startCwd: result.startCwd,
};
if (typeof result.timedOut === "boolean") {
metadata.timedOut = result.timedOut;
}
if (typeof result.timeoutMs === "number") {
metadata.timeoutMs = result.timeoutMs;
}
if (result.deadlineAt) {
metadata.deadlineAt = result.deadlineAt;
}
const outputValue = result.output ? result.output : undefined;
return {
ok: result.ok,
name,
output: outputValue,
error: errorMessage,
metadata,
};
}