Open History to see the last commit
1import { tmpdir } from 'node:os'
2import { dirname, join, posix, resolve } from 'node:path'
3import { describe, expect, it } from 'vitest'
4import {
5 bashResources,
6 bashTools,
7 splitCommand,
8} from '../src/first-party/coding/bash'
9import { decidePermission } from '../src/first-party/permissions'
10import type {
11 ToolEnv,
12 WorkspaceBackend,
13} from '../src/first-party/coding/backend'
14import type { PermissionRule } from '../src/first-party/permissions'
15
16type ExecOptions = Parameters<WorkspaceBackend['exec']>[1]
17type BashOptions = Parameters<typeof bashTools>[1]
18
19const root = resolve(tmpdir(), 'harness-bash')
20const OK = { exitCode: 0, stdout: 'ok', stderr: '' }
21// 3000 lines: the model gets only the last 1000.
22const LONG = {
23 exitCode: 1,
24 stdout: 'old\n'.repeat(2000) + 'new\n'.repeat(1000),
25 stderr: '',
26}
27const LONG_RESULT = `exit code: 1\n[Output cut. Showing the last 1000 of 3000 lines, 4000 of 12000 bytes.]\n\n${'new\n'.repeat(1000)}`
28
29/**
30 * A workspace whose commands all give back `result`. It records each
31 * command and each written file. `backend` replaces parts of the backend.
32 */
33function workspace(
34 result: { exitCode: number; stdout: string; stderr: string },
35 backend: Partial<WorkspaceBackend> = {},
36) {
37 const execs: Array<{ command: string; options: ExecOptions }> = []
38 const files = new Map<string, string | Uint8Array>()
39 const env: ToolEnv = {
40 backend: {
41 readFile: async (path) => {
42 throw new Error(`No file ${path}`)
43 },
44 writeFile: async (path, data) => {
45 files.set(path, data)
46 },
47 stat: async () => undefined,
48 // No links: each path is its own real path.
49 realpath: async (path) => path,
50 readdir: async () => [],
51 exec: async (command, options) => {
52 execs.push({ command, options })
53 return result
54 },
55 ...backend,
56 },
57 root,
58 hooks: () => [],
59 lock: (_path, fn) => fn(),
60 // Like the real one: a path in the workspace, from the root.
61 reach: async (path) => resolve(root, path),
62 shown: (full) => full,
63 }
64 return { env, execs, files }
65}
66
67/** Run the `bash` tool once. */
68async function bash(env: ToolEnv, args: object, options?: BashOptions) {
69 const [tool] = bashTools(env, options)
70 if (!tool?.execute) throw new Error('No bash tool')
71 return tool.execute(args)
72}
73
74/** A background job that ends when the test calls `end`, or when killed. */
75function fakeJob(output: string) {
76 let end!: (exitCode: number) => void
77 const exited = new Promise<{ exitCode: number }>((done) => {
78 end = (exitCode) => done({ exitCode })
79 })
80 const job = {
81 killed: false,
82 wait: () => exited,
83 kill: () => {
84 job.killed = true
85 end(143)
86 },
87 output: () => output,
88 }
89 return { job, end }
90}
91
92/** A `note` option that keeps each note. */
93function collectNotes() {
94 const notes: Array<string> = []
95 const note = async (text: string) => {
96 notes.push(text)
97 }
98 return { notes, note }
99}
100
101/** Wait until the promises that are ready now have run. */
102const settle = () => new Promise((done) => setTimeout(done, 0))
103
104describe('splitCommand', () => {
105 it.each([
106 { command: 'ls && rm -rf x', parts: ['ls', 'rm -rf x'] },
107 { command: 'a | b; c || d', parts: ['a', 'b', 'c', 'd'] },
108 { command: 'ls\npwd', parts: ['ls', 'pwd'] },
109 { command: 'echo "a && b"', parts: ['echo "a && b"'] },
110 { command: "echo 'a; b' && ls", parts: ["echo 'a; b'", 'ls'] },
111 { command: 'echo "a \\" b" && ls', parts: ['echo "a \\" b"', 'ls'] },
112 { command: 'echo a\\;b', parts: ['echo a\\;b'] },
113 { command: "echo $'a\\'b' && ls", parts: ["echo $'a\\'b'", 'ls'] },
114 ])('splits `$command`', ({ command, parts }) => {
115 expect(splitCommand(command)).toEqual(parts)
116 })
117
118 it.each([
119 { name: 'a command substitution', command: 'echo $(rm x) && ls' },
120 { name: 'a backtick', command: 'echo `rm x` && ls' },
121 { name: 'an input process substitution', command: 'diff <(ls a) b' },
122 { name: 'an output process substitution', command: 'ls | tee >(rm x)' },
123 { name: 'a heredoc', command: 'cat <<EOF && ls\nrm x\nEOF' },
124 { name: 'a quote that does not close', command: "echo 'a && rm x" },
125 { name: 'a function body', command: 'ls() ( rm -rf x ); ls' },
126 ])('gives back the whole command for $name', ({ command }) => {
127 expect(splitCommand(command)).toEqual([command])
128 })
129})
130
131describe('bash permissions', () => {
132 const rules: Array<PermissionRule> = [
133 { tool: 'bash', decision: 'ask', kind: 'execute' },
134 { tool: 'bash', resource: 'ls*', decision: 'allow' },
135 ]
136
137 it.each([
138 { command: 'ls -la && ls src', expected: 'allow' },
139 { command: 'ls && rm -rf x', expected: 'ask' },
140 { command: 'ls $(rm -rf x)', expected: 'ask' },
141 { command: 'ls() ( rm -rf x ); ls', expected: 'ask' },
142 ])('$expected for `$command`, with an allow rule for ls*', (example) => {
143 const commands = bashResources({ command: example.command })
144 expect(
145 decidePermission(rules, 'bash', 'default', { resources: { commands } }),
146 ).toBe(example.expected)
147 })
148
149 it('refuses a call without a command string', () => {
150 expect(() => bashResources({ command: 1 })).toThrow(
151 'Argument "command" must be a string.',
152 )
153 })
154})
155
156describe('bash', () => {
157 it('runs the command in the workspace, with AGENT=1 and the default timeout', async () => {
158 const { env, execs } = workspace(OK)
159 expect(await bash(env, { command: 'make' })).toBe('exit code: 0\nok')
160 expect(execs).toEqual([
161 {
162 command: 'make',
163 options: {
164 cwd: root,
165 env: { AGENT: '1' },
166 timeoutMs: 120_000,
167 signal: expect.any(AbortSignal),
168 onStart: expect.any(Function),
169 },
170 },
171 ])
172 })
173
174 it.each([
175 { name: 'the factory timeout without one', args: {}, expected: 30_000 },
176 {
177 name: 'the timeout of the call',
178 args: { timeoutMs: 5_000 },
179 expected: 5_000,
180 },
181 {
182 name: 'at most 10 minutes',
183 args: { timeoutMs: 3_600_000 },
184 expected: 600_000,
185 },
186 {
187 name: 'the factory timeout for 0',
188 args: { timeoutMs: 0 },
189 expected: 30_000,
190 },
191 ])('gives exec $name', async ({ args, expected }) => {
192 const { env, execs } = workspace(OK)
193 await bash(env, { command: 'make', ...args }, { timeoutMs: 30_000 })
194 expect(execs[0]?.options?.timeoutMs).toBe(expected)
195 })
196
197 it('keeps the last lines of long output, with a note, and saves no file', async () => {
198 const { env, files } = workspace(LONG)
199 expect(await bash(env, { command: 'test' })).toBe(LONG_RESULT)
200 expect(files.size).toBe(0)
201 })
202
203 it('saves the full output in spillDir, and gives its path', async () => {
204 const { env, files } = workspace(LONG)
205 const result = await bash(
206 env,
207 { command: 'test' },
208 { spillDir: '.agent/bash' },
209 )
210 const [path = ''] = files.keys()
211 expect(files.size).toBe(1)
212 expect(dirname(path)).toBe(join(root, '.agent', 'bash'))
213 expect(files.get(path)).toBe(LONG.stdout)
214 expect(result).toBe(`${LONG_RESULT}\n[Full output saved to ${path}.]`)
215 })
216
217 it('saves the output that scrub gives, so the file keeps no secret', async () => {
218 const { env, files } = workspace({
219 ...LONG,
220 stdout: 'key=sk-secret\n'.repeat(3000),
221 })
222 await bash(
223 env,
224 { command: 'test' },
225 {
226 spillDir: '.agent/bash',
227 scrub: (text) => text.replaceAll('sk-secret', '[redacted]'),
228 },
229 )
230 const [saved] = files.values()
231 expect(saved).toBe('key=[redacted]\n'.repeat(3000))
232 })
233
234 it('saves it with a POSIX path in a sandbox, also on a Windows host', async () => {
235 const { env, files } = workspace(LONG, { shell: 'sh' })
236 await bash(
237 { ...env, root: '/workspace' },
238 { command: 'test' },
239 { spillDir: '.agent/bash' },
240 )
241 const [path = ''] = files.keys()
242 expect(posix.dirname(path)).toBe('/workspace/.agent/bash')
243 })
244
245 it('still gives the output when the save fails', async () => {
246 const { env } = workspace(LONG, {
247 writeFile: async () => {
248 throw new Error('disk full')
249 },
250 })
251 expect(
252 await bash(env, { command: 'test' }, { spillDir: '.agent/bash' }),
253 ).toBe(`${LONG_RESULT}\n[The full output was not saved: Error: disk full]`)
254 })
255})
256
257describe('bash in the background', () => {
258 it('returns at once, and notes the exit code and output when the job ends', async () => {
259 const { job, end } = fakeJob('built\n')
260 const spawned: Array<{ command: string; options: unknown }> = []
261 const { env } = workspace(OK, {
262 spawn: (command, options) => {
263 spawned.push({ command, options })
264 return job
265 },
266 })
267 const { notes, note } = collectNotes()
268 expect(
269 await bash(env, { command: 'npm run build', background: true }, { note }),
270 ).toEqual({ jobId: 'bash-1', status: 'started' })
271 expect(spawned).toEqual([
272 {
273 command: 'npm run build',
274 options: { cwd: root, env: { AGENT: '1' } },
275 },
276 ])
277 await settle()
278 expect(notes).toEqual([])
279 end(2)
280 await settle()
281 expect(notes).toEqual([
282 'Background job bash-1 ended.\nexit code: 2\nbuilt\n',
283 ])
284 })
285
286 it('kills running jobs when the signal aborts, and sends no note', async () => {
287 const { job } = fakeJob('')
288 const { env } = workspace(OK, { spawn: () => job })
289 const { notes, note } = collectNotes()
290 const controller = new AbortController()
291 await bash(
292 env,
293 { command: 'npm run dev', background: true },
294 { note, signal: controller.signal },
295 )
296 controller.abort()
297 await settle()
298 expect(job.killed).toBe(true)
299 expect(notes).toEqual([])
300 })
301
302 it('gives a tool error when the backend cannot start background commands', async () => {
303 const { env } = workspace(OK)
304 await expect(
305 bash(env, { command: 'npm run dev', background: true }),
306 ).rejects.toThrow('This workspace cannot run commands in the background.')
307 })
308})