-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool-shell.mjs
More file actions
214 lines (188 loc) · 6.98 KB
/
Copy pathtool-shell.mjs
File metadata and controls
214 lines (188 loc) · 6.98 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
import { spawn } from 'node:child_process';
import { StringDecoder } from 'node:string_decoder';
import { MAX_TOOL_OUTPUT } from './tool-output.mjs';
import { getShellLaunchers, isMissingLauncherError } from './platform.mjs';
const DEFAULT_TIMEOUT_MS = 30_000;
const OUTPUT_TRUNCATION_NOTE = '\n[output truncated]';
function normalizeLimit(value, fallback = MAX_TOOL_OUTPUT) {
const number = Number(value);
return Number.isFinite(number) && number > 0 ? number : fallback;
}
function truncateText(text, limit) {
const string = String(text ?? '');
const max = normalizeLimit(limit);
if (string.length <= max) return string;
if (max <= OUTPUT_TRUNCATION_NOTE.length) return string.slice(0, max);
return `${string.slice(0, max - OUTPUT_TRUNCATION_NOTE.length)}${OUTPUT_TRUNCATION_NOTE}`;
}
function makeShellCommandOutput({ stdout = '', stderr = '', outcome, maxOutputLength }) {
return {
stdout: truncateText(stdout, maxOutputLength),
stderr: truncateText(stderr, maxOutputLength),
outcome,
};
}
function getLaunchPlan(command, platform = process.platform) {
return getShellLaunchers(platform).map((launcher) => ({
file: launcher.file,
args: [...launcher.args, command],
}));
}
function runLauncherCommand(plan, command, cwd, { timeoutMs, maxOutputLength, writeStdout, writeStderr, signal } = {}) {
return new Promise((resolve, reject) => {
const child = spawn(plan.file, plan.args, {
cwd,
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
const stdoutDecoder = new StringDecoder('utf8');
const stderrDecoder = new StringDecoder('utf8');
let stdout = '';
let stderr = '';
let finished = false;
let timedOut = false;
let interrupted = false;
let timer = null;
let onAbort = null;
const finalizeChunk = (chunk, channel) => {
if (!chunk) return;
if (channel === 'stdout') {
stdout = truncateText(`${stdout}${chunk}`, maxOutputLength);
writeStdout?.(chunk);
} else {
stderr = truncateText(`${stderr}${chunk}`, maxOutputLength);
writeStderr?.(chunk);
}
};
const flushStream = (channel) => {
const decoder = channel === 'stdout' ? stdoutDecoder : stderrDecoder;
const chunk = decoder.end();
finalizeChunk(chunk, channel);
};
const done = (result) => {
if (finished) return;
finished = true;
if (timer) clearTimeout(timer);
signal?.removeEventListener?.('abort', onAbort);
resolve(result);
};
child.on('error', (error) => {
if (finished) return;
if (timer) clearTimeout(timer);
if (isMissingLauncherError(error)) {
reject(error);
return;
}
const message = error?.message || 'Unable to execute shell command';
done(makeShellCommandOutput({ stdout, stderr: stderr || message, outcome: { type: 'exit', exit_code: 1 }, maxOutputLength }));
});
child.stdout?.on('data', (chunk) => {
finalizeChunk(stdoutDecoder.write(chunk), 'stdout');
});
child.stderr?.on('data', (chunk) => {
finalizeChunk(stderrDecoder.write(chunk), 'stderr');
});
child.on('close', (code, signal) => {
flushStream('stdout');
flushStream('stderr');
const outcome = interrupted
? { type: 'timeout' }
: (timedOut
? { type: 'timeout' }
: (signal
? { type: 'exit', exit_code: 1 }
: { type: 'exit', exit_code: Number.isFinite(code) ? Number(code) : 1 }));
done(makeShellCommandOutput({ stdout, stderr, outcome, maxOutputLength }));
});
const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_TIMEOUT_MS;
if (timeout > 0) {
timer = setTimeout(() => {
timedOut = true;
child.kill('SIGTERM');
}, timeout);
}
onAbort = () => {
if (finished) return;
interrupted = true;
child.kill('SIGTERM');
};
if (signal?.aborted) onAbort();
else signal?.addEventListener?.('abort', onAbort, { once: true });
});
}
async function executeWithLaunchers(command, cwd, { timeoutMs, maxOutputLength, platform = process.platform, writeStdout, writeStderr, signal } = {}) {
let lastError = null;
for (const plan of getLaunchPlan(command, platform)) {
try {
return await runLauncherCommand(plan, command, cwd, { timeoutMs, maxOutputLength, writeStdout, writeStderr, signal });
} catch (error) {
lastError = error;
if (isMissingLauncherError(error)) continue;
const stderr = error?.message || 'Unable to execute shell command';
return makeShellCommandOutput({ stdout: '', stderr, outcome: { type: 'exit', exit_code: 1 }, maxOutputLength });
}
}
const stderr = lastError?.message || 'Unable to locate a supported shell launcher';
return makeShellCommandOutput({ stdout: '', stderr, outcome: { type: 'exit', exit_code: 1 }, maxOutputLength });
}
function normalizeCommands(commands) {
if (Array.isArray(commands)) return commands.map((command) => String(command ?? ''));
if (typeof commands === 'string') return [commands];
return [];
}
function normalizeSteps(steps, defaultCwd = '', fallbackTimeoutMs = null, fallbackMaxOutputLength = null) {
if (!Array.isArray(steps)) return [];
return steps.map((step) => ({
command: String(step?.command ?? ''),
cwd: step?.cwd == null ? String(defaultCwd ?? '') : String(step.cwd),
timeoutMs: step?.timeoutMs ?? fallbackTimeoutMs,
maxOutputLength: step?.maxOutputLength ?? fallbackMaxOutputLength,
}));
}
export async function runShellCommandSequence(steps, { callId, defaultCwd = '', signal } = {}) {
const normalizedSteps = normalizeSteps(steps, defaultCwd);
const output = [];
let status = 'completed';
let maxOutputLength = null;
for (const step of normalizedSteps) {
const chunk = await executeWithLaunchers(step.command, step.cwd, {
timeoutMs: step.timeoutMs,
maxOutputLength: step.maxOutputLength,
signal,
});
output.push(chunk);
const stepLimit = Number(step.maxOutputLength);
if (Number.isFinite(stepLimit) && stepLimit > 0) {
maxOutputLength = maxOutputLength == null ? stepLimit : Math.max(maxOutputLength, stepLimit);
}
if (chunk.outcome?.type === 'timeout') {
status = 'incomplete';
break;
}
}
return {
type: 'shell_call_output',
call_id: callId || '',
status,
output,
max_output_length: maxOutputLength,
};
}
export async function runShellCommands(commands, cwd, { timeoutMs, maxOutputLength, callId, signal } = {}) {
const steps = normalizeCommands(commands).map((command) => ({
command,
cwd,
timeoutMs,
maxOutputLength,
}));
return await runShellCommandSequence(steps, { callId, defaultCwd: cwd, signal });
}
export async function shellExec(command, cwd) {
const result = await executeWithLaunchers(command, cwd, {
maxOutputLength: MAX_TOOL_OUTPUT,
writeStdout: (chunk) => process.stdout.write(chunk),
writeStderr: (chunk) => process.stderr.write(chunk),
});
return result;
}
export { getShellLaunchers };