-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathrun-commands.ts
More file actions
179 lines (162 loc) · 4.85 KB
/
Copy pathrun-commands.ts
File metadata and controls
179 lines (162 loc) · 4.85 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
import { spawn } from "node:child_process";
import { addBreadcrumb } from "@sentry/node-core/light";
import { whichSync } from "../../which.js";
import { DEFAULT_COMMAND_TIMEOUT_MS } from "../constants.js";
import type { RunCommandsPayload, ToolResult } from "../types.js";
import {
parseCommand,
readSpawnOutput,
validateCommand as validateToolCommand,
} from "./command-utils.js";
import type { InitToolDefinition, ToolContext } from "./types.js";
const WINDOWS_BATCH_SHIM_RE = /\.(?:cmd|bat)$/iu;
type SpawnCommand = {
executable: string;
args: string[];
windowsVerbatimArguments?: true;
};
function isWindowsBatchShim(executable: string): boolean {
return process.platform === "win32" && WINDOWS_BATCH_SHIM_RE.test(executable);
}
function quoteWindowsCommandArg(value: string): string {
return `"${value.replace(/"/g, '""')}"`;
}
function buildWindowsBatchCommand(executable: string, args: string[]): string {
const commandLine = [executable, ...args]
.map(quoteWindowsCommandArg)
.join(" ");
// cmd.exe /s strips the outer quote pair, leaving a quoted exe + argv.
return `"${commandLine}"`;
}
/**
* Validate and execute a batch of commands.
*/
export async function runCommands(
payload: RunCommandsPayload,
context: Pick<ToolContext, "dryRun">
): Promise<ToolResult> {
const timeoutMs = payload.params.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
const parsedCommands: ReturnType<typeof parseCommand>[] = [];
for (const command of payload.params.commands) {
const validationError = validateToolCommand(command);
if (validationError) {
return { ok: false, error: validationError };
}
parsedCommands.push(parseCommand(command));
}
const results: Array<{
command: string;
exitCode: number;
stdout: string;
stderr: string;
}> = [];
for (const command of parsedCommands) {
if (context.dryRun) {
results.push({
command: command.original,
exitCode: 0,
stdout: "(dry-run: skipped)",
stderr: "",
});
continue;
}
const result = await runSingleCommand(command, payload.cwd, timeoutMs);
results.push(result);
if (result.exitCode !== 0) {
addBreadcrumb({
level: "error",
message: `Command failed: ${command.original}`,
data: {
exitCode: result.exitCode,
stdout: result.stdout.slice(0, 500),
stderr: result.stderr.slice(0, 500),
cwd: payload.cwd,
},
});
return {
ok: false,
error: `Command "${command.original}" failed with exit code ${result.exitCode}: ${result.stderr}`,
data: { results },
};
}
}
return { ok: true, data: { results } };
}
async function runSingleCommand(
command: ReturnType<typeof parseCommand>,
cwd: string,
timeoutMs: number
): Promise<{
command: string;
exitCode: number;
stdout: string;
stderr: string;
}> {
const executable = whichSync(command.executable) ?? command.executable;
const spawnCommand: SpawnCommand = isWindowsBatchShim(executable)
? {
executable: process.env.ComSpec ?? "cmd.exe",
args: [
"/d",
"/s",
"/c",
buildWindowsBatchCommand(executable, command.args),
],
windowsVerbatimArguments: true,
}
: { executable, args: command.args };
try {
const child = spawn(spawnCommand.executable, spawnCommand.args, {
cwd,
shell: false,
stdio: ["ignore", "pipe", "pipe"],
...(spawnCommand.windowsVerbatimArguments
? { windowsVerbatimArguments: true }
: {}),
});
const exited = new Promise<number>((resolve) => {
child.on("close", (code) => resolve(code ?? 1));
child.on("error", () => resolve(1));
});
let timedOut = false;
const timer = globalThis.setTimeout(() => {
timedOut = true;
child.kill();
}, timeoutMs);
const [exitCode, stdout, stderr] = await Promise.all([
exited,
readSpawnOutput(child.stdout),
readSpawnOutput(child.stderr),
]);
clearTimeout(timer);
return {
command: command.original,
exitCode: timedOut ? 1 : exitCode,
stdout,
stderr: timedOut
? stderr || `Command timed out after ${timeoutMs}ms`
: stderr,
};
} catch (error) {
return {
command: command.original,
exitCode: 1,
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Tool definition for sandboxed command execution.
*/
export const runCommandsTool: InitToolDefinition<"run-commands"> = {
operation: "run-commands",
describe: (payload) => {
const [first] = payload.params.commands;
if (payload.params.commands.length === 1 && first) {
return `Running \`${first}\`...`;
}
return `Running ${payload.params.commands.length} commands (\`${first ?? "..."}\`, ...)...`;
},
execute: runCommands,
};