-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbash.ts
More file actions
332 lines (313 loc) · 12.3 KB
/
Copy pathbash.ts
File metadata and controls
332 lines (313 loc) · 12.3 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
// Bash tool — execute a shell command with timeout, capture stdout+stderr+exitCode.
// Spec: docs/DEVELOPMENT_PLAN.md §3.2 (P0) + run_in_background param
// M3.5: optionally wrapped under platform sandbox via ctx.sandboxConfig
// M3.5-ext: when network.allowedDomains is a non-empty allowlist on Linux, run
// under the slirp4netns selective-network sandbox (spawnNetworkSandbox). If
// that can't be set up (e.g. can't bind the DNS proxy on :53), fail CLOSED to
// deny-all-net rather than running unrestricted.
import { spawn, type ChildProcess } from 'node:child_process';
import { promises as fs } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
denyAllNetwork,
needsNetworkSandbox,
NetworkSandboxUnavailable,
spawnNetworkSandbox,
wrapBashCommand,
} from '../sandbox/index.js';
import type { NetworkSandboxHandle, SpawnNetworkSandboxOpts } from '../sandbox/index.js';
import type { SandboxConfig, SandboxMode } from '../config/types.js';
import { BoundedCapture } from '../spill/bound.js';
import type { ToolContext, ToolHandler, ToolResult } from '../types.js';
interface BashInput {
command: string;
timeout?: number; // ms
description?: string; // shown in approval UI
run_in_background?: boolean; // detach + stream output to a log file
}
// ToolContext carries sandbox config (+ optional test seams) from the loop owner.
type SandboxCtx = ToolContext & {
sandboxConfig?: SandboxConfig;
/** Mode to apply when settings name none — hosts set workspace-write. */
sandboxDefaultMode?: SandboxMode;
/** Test seam: override the platform used for the net-sandbox decision. */
sandboxPlatform?: NodeJS.Platform;
/** Test seam: override the network-sandbox spawner. */
sandboxNetSpawn?: (opts: SpawnNetworkSandboxOpts) => Promise<NetworkSandboxHandle>;
};
const DEFAULT_TIMEOUT_MS = 120_000; // 2 minutes
// What one stream keeps in memory. This is NOT the model-visible limit — the
// spill policy bounds that centrally and saves the rest to a file the model can
// read. Capture has to exceed that limit for there to be anything worth saving,
// while staying small enough that a runaway command cannot exhaust memory.
const CAPTURE_HEAD_CHARS = 1_000_000;
const CAPTURE_TAIL_CHARS = 3_000_000;
type TerminationReason = 'timeout' | 'aborted';
// Monotonic suffix so two background spawns in the same millisecond from the
// same pid don't collide on a log filename.
let bgSeq = 0;
function newCapture(): BoundedCapture {
return new BoundedCapture(CAPTURE_HEAD_CHARS, CAPTURE_TAIL_CHARS);
}
/** Build the standard Bash ToolResult from captured output + exit info. */
function summarize(
out: BoundedCapture,
err: BoundedCapture,
terminationReason: TerminationReason | undefined,
code: number | null,
timeoutMs: number,
note?: string,
): ToolResult {
const parts: string[] = [];
const stdout = out.text();
const stderr = err.text();
if (note) parts.push(note);
if (stdout) parts.push(`<stdout>\n${stdout}\n</stdout>`);
if (stderr) parts.push(`<stderr>\n${stderr}\n</stderr>`);
if (terminationReason === 'timeout') parts.push(`[killed by timeout after ${timeoutMs}ms]`);
if (terminationReason === 'aborted') parts.push('[aborted by user]');
parts.push(`exit: ${code ?? 'unknown'}`);
return {
content: parts.join('\n'),
data: {
exitCode: code,
killed: terminationReason !== undefined,
terminationReason,
stdoutBytes: out.total,
stderrBytes: err.total,
},
isError: terminationReason !== undefined || (code !== null && code !== 0),
};
}
/** Kill the whole foreground process group on POSIX, not just its shell. */
function killProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {
if (process.platform !== 'win32' && child.pid !== undefined) {
try {
process.kill(-child.pid, signal);
return;
} catch {
// The group may already have exited; fall back to the direct child.
}
}
try {
child.kill(signal);
} catch {
// Process already exited.
}
}
/**
* Foreground run under the slirp4netns selective-network sandbox. Rejects with
* NetworkSandboxUnavailable if setup fails (caller falls back to deny-all-net).
*/
async function runForegroundNet(
command: string,
ctx: SandboxCtx,
config: SandboxConfig,
timeoutMs: number,
spawnFn: (opts: SpawnNetworkSandboxOpts) => Promise<NetworkSandboxHandle>,
): Promise<ToolResult> {
const handle = await spawnFn({ userCommand: command, cwd: ctx.cwd, config });
return new Promise<ToolResult>((resolve) => {
const stdout = newCapture();
const stderr = newCapture();
let terminationReason: TerminationReason | undefined;
let settled = false;
const finish = (r: ToolResult): void => {
if (!settled) {
settled = true;
resolve(r);
}
};
const timer = setTimeout(() => {
terminationReason = 'timeout';
void handle.close();
}, timeoutMs);
const onAbort = (): void => {
terminationReason = 'aborted';
void handle.close();
};
ctx.signal?.addEventListener('abort', onAbort, { once: true });
handle.child.stdout?.on('data', (c: Buffer) => {
stdout.push(c.toString('utf8'));
});
handle.child.stderr?.on('data', (c: Buffer) => {
stderr.push(c.toString('utf8'));
});
handle.exited
.then((code) => {
clearTimeout(timer);
ctx.signal?.removeEventListener('abort', onAbort);
finish(summarize(stdout, stderr, terminationReason, code, timeoutMs));
})
.catch((err: unknown) => {
clearTimeout(timer);
ctx.signal?.removeEventListener('abort', onAbort);
finish({ content: `Error running sandboxed command: ${String(err)}`, isError: true });
});
});
}
export const BashTool: ToolHandler = {
name: 'Bash',
definition: {
name: 'Bash',
render: 'terminal',
description:
'Executes a shell command. Captures stdout/stderr/exitCode. Default timeout 2 min.',
inputSchema: {
type: 'object',
properties: {
command: { type: 'string', description: 'Command line to execute via /bin/sh -c.' },
timeout: { type: 'number', description: 'Milliseconds (default 120000).' },
description: {
type: 'string',
description: 'Short description shown to user during approval.',
},
run_in_background: {
type: 'boolean',
description:
'Run detached and return immediately. Output streams to a log file whose path is in the result — Read that file to see progress/results. Use for long-running or watch processes (dev servers, tail -f, test watchers).',
},
},
required: ['command'],
},
},
async execute(rawInput: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult> {
const input = rawInput as unknown as BashInput;
if (!input?.command || typeof input.command !== 'string') {
return { content: 'Error: command is required (string).', isError: true };
}
if (ctx.signal?.aborted) {
return {
content: '[aborted by user]',
isError: true,
data: { terminationReason: 'aborted' },
};
}
const timeoutMs = Math.max(1_000, input.timeout ?? DEFAULT_TIMEOUT_MS);
// M3.5: wrap under platform sandbox if configured. ctx.sandboxConfig is
// populated by the agent loop owner (CLI REPL passes settings.sandbox).
const sctx = ctx as SandboxCtx;
const sandboxCfg = sctx.sandboxConfig;
const platform = sctx.sandboxPlatform ?? process.platform;
// M3.5-ext: does this command want the selective-allowlist network sandbox?
const useNet = needsNetworkSandbox(sandboxCfg, platform);
// Background: spawn detached, stream stdout+stderr into a log file, and
// return immediately. The agent reads the log path later (via Read) to see
// progress/output. The process survives this turn (own process group).
if (input.run_in_background) {
// The selective allowlist needs a slirp4netns helper that must outlive the
// turn — not supported for detached background commands. Fail CLOSED to
// deny-all-net so a background command can't escape the allowlist.
let bgCfg = sandboxCfg;
let bgNote = '';
if (useNet && sandboxCfg) {
bgCfg = denyAllNetwork(sandboxCfg);
bgNote =
'[sandbox] selective network allowlist is not supported for background commands; running with NO network.\n';
}
const wrapped = await wrapBashCommand({
userCommand: input.command,
cwd: ctx.cwd,
config: bgCfg,
defaultMode: sctx.sandboxDefaultMode,
});
const dir = join(ctx.sessionDir ?? tmpdir(), 'bg');
const id = `bg-${Date.now().toString(36)}-${process.pid}-${bgSeq++}`;
const logPath = join(dir, `${id}.log`);
try {
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(logPath, `${bgNote}$ ${input.command}\n`, 'utf8');
const fh = await fs.open(logPath, 'a');
try {
const child = spawn(wrapped.command, wrapped.args, {
cwd: ctx.cwd,
detached: true,
stdio: ['ignore', fh.fd, fh.fd],
});
const pid = child.pid;
child.unref();
return {
content: `${bgNote}Started in background (pid ${pid ?? 'unknown'}). Output streams to:\n${logPath}\nRead that file to check progress or results.`,
data: { background: true, pid, logPath, id },
};
} finally {
await fh.close(); // child holds its own dup of the fd
}
} catch (err) {
return {
content: `Error starting background command: ${(err as Error).message}`,
isError: true,
};
}
}
// Foreground. Effective config + an optional note (set on fail-closed).
let effectiveCfg = sandboxCfg;
let failNote: string | undefined;
if (useNet && sandboxCfg) {
const spawnFn = sctx.sandboxNetSpawn ?? spawnNetworkSandbox;
try {
return await runForegroundNet(input.command, sctx, sandboxCfg, timeoutMs, spawnFn);
} catch (err) {
if (!(err instanceof NetworkSandboxUnavailable)) {
return { content: `Error spawning sandboxed command: ${String(err)}`, isError: true };
}
// Fail CLOSED: run with no network rather than unrestricted.
effectiveCfg = denyAllNetwork(sandboxCfg);
failNote = `[sandbox] selective network allowlist unavailable (${err.message}); ran with NO network. See docs/security-model.md.`;
}
}
const wrapped = await wrapBashCommand({
userCommand: input.command,
cwd: ctx.cwd,
config: effectiveCfg,
defaultMode: sctx.sandboxDefaultMode,
});
return new Promise((resolvePromise) => {
const child = spawn(wrapped.command, wrapped.args, {
cwd: ctx.cwd,
detached: process.platform !== 'win32',
});
const stdout = newCapture();
const stderr = newCapture();
let terminationReason: TerminationReason | undefined;
let settled = false;
const finish = (result: ToolResult): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
ctx.signal?.removeEventListener('abort', onAbort);
resolvePromise(result);
};
const terminate = (reason: TerminationReason): void => {
if (terminationReason) return;
terminationReason = reason;
killProcessTree(child, 'SIGKILL');
// Descendants can inherit these descriptors; destroying them also
// prevents an orphan from keeping the Promise open indefinitely.
child.stdout?.destroy();
child.stderr?.destroy();
};
const timer = setTimeout(() => {
terminate('timeout');
}, timeoutMs);
const onAbort = (): void => terminate('aborted');
ctx.signal?.addEventListener('abort', onAbort, { once: true });
child.stdout.on('data', (chunk: Buffer) => {
stdout.push(chunk.toString('utf8'));
});
child.stderr.on('data', (chunk: Buffer) => {
stderr.push(chunk.toString('utf8'));
});
child.on('error', (err) => {
finish({
content: `Error spawning command: ${err.message}`,
isError: true,
});
});
child.on('close', (code) => {
finish(summarize(stdout, stderr, terminationReason, code, timeoutMs, failNote));
});
});
},
};