-
Notifications
You must be signed in to change notification settings - Fork 749
feat(chat): Add executeBash tool for Amazon Q Agentic Chat #6848
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mr-lee
merged 1 commit into
aws:feature/agentic-chat
from
tsmithsz:feature/agentic-chat
Mar 25, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
208 changes: 208 additions & 0 deletions
208
packages/core/src/codewhispererChat/tools/executeBash.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,208 @@ | ||
| /*! | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import { Writable } from 'stream' | ||
| import { getLogger } from '../../shared/logger/logger' | ||
| import { fs } from '../../shared/fs/fs' // e.g. for getUserHomeDir() | ||
| import { ChildProcess, ChildProcessOptions } from '../../shared/utilities/processUtils' | ||
| import { InvokeOutput, OutputKind, sanitizePath } from './toolShared' | ||
|
|
||
| export const readOnlyCommands: string[] = ['ls', 'cat', 'echo', 'pwd', 'which', 'head', 'tail'] | ||
| export const maxBashToolResponseSize: number = 1024 * 1024 // 1MB | ||
| export const lineCount: number = 1024 | ||
| export const dangerousPatterns: string[] = ['|', '<(', '$(', '`', '>', '&&', '||'] | ||
|
|
||
| export interface ExecuteBashParams { | ||
| command: string | ||
| cwd?: string | ||
| } | ||
|
|
||
| export class ExecuteBash { | ||
| private readonly command: string | ||
| private readonly workingDirectory?: string | ||
| private readonly logger = getLogger('executeBash') | ||
|
|
||
| constructor(params: ExecuteBashParams) { | ||
| this.command = params.command | ||
| this.workingDirectory = params.cwd ? sanitizePath(params.cwd) : fs.getUserHomeDir() | ||
| } | ||
|
|
||
| public async validate(): Promise<void> { | ||
| if (!this.command.trim()) { | ||
| throw new Error('Bash command cannot be empty.') | ||
| } | ||
|
|
||
| const args = ExecuteBash.parseCommand(this.command) | ||
| if (!args || args.length === 0) { | ||
| throw new Error('No command found.') | ||
| } | ||
|
|
||
| try { | ||
| await ExecuteBash.whichCommand(args[0]) | ||
| } catch { | ||
| throw new Error(`Command "${args[0]}" not found on PATH.`) | ||
| } | ||
| } | ||
|
|
||
| public requiresAcceptance(): boolean { | ||
| try { | ||
| const args = ExecuteBash.parseCommand(this.command) | ||
| if (!args || args.length === 0) { | ||
| return true | ||
| } | ||
|
|
||
| if (args.some((arg) => dangerousPatterns.some((pattern) => arg.includes(pattern)))) { | ||
| return true | ||
| } | ||
|
|
||
| const command = args[0] | ||
| return !readOnlyCommands.includes(command) | ||
| } catch (error) { | ||
| this.logger.warn(`Error while checking acceptance: ${(error as Error).message}`) | ||
| return true | ||
| } | ||
| } | ||
|
|
||
| public async invoke(updates: Writable): Promise<InvokeOutput> { | ||
| this.logger.info(`Invoking bash command: "${this.command}" in cwd: "${this.workingDirectory}"`) | ||
|
|
||
| return new Promise(async (resolve, reject) => { | ||
| this.logger.debug(`Spawning process with command: bash -c "${this.command}" (cwd=${this.workingDirectory})`) | ||
|
|
||
| const stdoutBuffer: string[] = [] | ||
| const stderrBuffer: string[] = [] | ||
|
|
||
| const childProcessOptions: ChildProcessOptions = { | ||
| spawnOptions: { | ||
| cwd: this.workingDirectory, | ||
| stdio: ['pipe', 'pipe', 'pipe'], | ||
| }, | ||
| collect: false, | ||
| waitForStreams: true, | ||
| onStdout: (chunk: string) => { | ||
| ExecuteBash.handleChunk(chunk, stdoutBuffer, updates) | ||
| }, | ||
| onStderr: (chunk: string) => { | ||
| ExecuteBash.handleChunk(chunk, stderrBuffer, updates) | ||
| }, | ||
| } | ||
|
|
||
| const childProcess = new ChildProcess('bash', ['-c', this.command], childProcessOptions) | ||
tsmithsz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| try { | ||
| const result = await childProcess.run() | ||
| const exitStatus = result.exitCode ?? 0 | ||
| const stdout = stdoutBuffer.join('\n') | ||
| const stderr = stderrBuffer.join('\n') | ||
| const [stdoutTrunc, stdoutSuffix] = ExecuteBash.truncateSafelyWithSuffix( | ||
| stdout, | ||
| maxBashToolResponseSize / 3 | ||
| ) | ||
| const [stderrTrunc, stderrSuffix] = ExecuteBash.truncateSafelyWithSuffix( | ||
| stderr, | ||
| maxBashToolResponseSize / 3 | ||
| ) | ||
|
|
||
| const outputJson = { | ||
| exitStatus: exitStatus.toString(), | ||
| stdout: stdoutTrunc + (stdoutSuffix ? ' ... truncated' : ''), | ||
| stderr: stderrTrunc + (stderrSuffix ? ' ... truncated' : ''), | ||
| } | ||
|
|
||
| return { | ||
| output: { | ||
| kind: OutputKind.Json, | ||
| content: outputJson, | ||
| }, | ||
| } | ||
| } catch (err: any) { | ||
| this.logger.error(`Failed to execute bash command '${this.command}': ${err.message}`) | ||
| throw new Error(`Failed to execute command: ${err.message}`) | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| private static handleChunk(chunk: string, buffer: string[], updates: Writable) { | ||
| const lines = chunk.split(/\r?\n/) | ||
| for (const line of lines) { | ||
| updates.write(`${line}\n`) | ||
| buffer.push(line) | ||
| if (buffer.length > lineCount) { | ||
| buffer.shift() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static truncateSafelyWithSuffix(str: string, maxLength: number): [string, boolean] { | ||
| if (str.length > maxLength) { | ||
| return [str.substring(0, maxLength), true] | ||
| } | ||
| return [str, false] | ||
| } | ||
|
|
||
| private static async whichCommand(cmd: string): Promise<string> { | ||
| const cp = new ChildProcess('which', [cmd], { | ||
| collect: true, | ||
| waitForStreams: true, | ||
| }) | ||
| const result = await cp.run() | ||
|
|
||
| if (result.exitCode !== 0) { | ||
| throw new Error(`Command "${cmd}" not found on PATH.`) | ||
laileni-aws marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| const output = result.stdout.trim() | ||
| if (!output) { | ||
| throw new Error(`Command "${cmd}" found but 'which' returned empty output.`) | ||
| } | ||
| return output | ||
| } | ||
|
|
||
| private static parseCommand(command: string): string[] | undefined { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Parsing bash/shell commands is non-trivial. Is this intended to support arbitrary bash command, or only very simple cases?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here's an example: #7230 |
||
| const result: string[] = [] | ||
| let current = '' | ||
| let inQuote: string | undefined | ||
| let escaped = false | ||
|
|
||
| for (const char of command) { | ||
| if (escaped) { | ||
| current += char | ||
| escaped = false | ||
| } else if (char === '\\') { | ||
| escaped = true | ||
| } else if (inQuote) { | ||
| if (char === inQuote) { | ||
| inQuote = undefined | ||
| } else { | ||
| current += char | ||
| } | ||
| } else if (char === '"' || char === "'") { | ||
| inQuote = char | ||
| } else if (char === ' ' || char === '\t') { | ||
| if (current) { | ||
| result.push(current) | ||
| current = '' | ||
| } | ||
| } else { | ||
| current += char | ||
| } | ||
| } | ||
|
|
||
| if (current) { | ||
| result.push(current) | ||
| } | ||
|
|
||
| return result | ||
| } | ||
|
|
||
| public queueDescription(updates: Writable): void { | ||
| updates.write(`I will run the following shell command: `) | ||
|
|
||
| if (this.command.length > 20) { | ||
| updates.write('\n') | ||
| } | ||
| updates.write(`\x1b[32m${this.command}\x1b[0m\n`) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
packages/core/src/test/codewhispererChat/tools/executeBash.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| /*! | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import { strict as assert } from 'assert' | ||
| import sinon from 'sinon' | ||
| import { ExecuteBash } from '../../../codewhispererChat/tools/executeBash' | ||
| import { ChildProcess } from '../../../shared/utilities/processUtils' | ||
|
|
||
| describe('ExecuteBash Tool', () => { | ||
| let runStub: sinon.SinonStub | ||
| let invokeStub: sinon.SinonStub | ||
|
|
||
| beforeEach(() => { | ||
| runStub = sinon.stub(ChildProcess.prototype, 'run') | ||
| invokeStub = sinon.stub(ExecuteBash.prototype, 'invoke') | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| sinon.restore() | ||
| }) | ||
|
|
||
| it('pass validation for a safe command (read-only)', async () => { | ||
| runStub.resolves({ | ||
| exitCode: 0, | ||
| stdout: '/bin/ls', | ||
| stderr: '', | ||
| error: undefined, | ||
| signal: undefined, | ||
| }) | ||
| const execBash = new ExecuteBash({ command: 'ls' }) | ||
| await execBash.validate() | ||
| }) | ||
|
|
||
| it('fail validation if the command is empty', async () => { | ||
| const execBash = new ExecuteBash({ command: ' ' }) | ||
| await assert.rejects( | ||
| execBash.validate(), | ||
| /Bash command cannot be empty/i, | ||
| 'Expected an error for empty command' | ||
| ) | ||
| }) | ||
|
|
||
| it('set requiresAcceptance=true if the command has dangerous patterns', () => { | ||
| const execBash = new ExecuteBash({ command: 'ls && rm -rf /' }) | ||
| const needsAcceptance = execBash.requiresAcceptance() | ||
| assert.equal(needsAcceptance, true, 'Should require acceptance for dangerous pattern') | ||
| }) | ||
|
|
||
| it('set requiresAcceptance=false if it is a read-only command', () => { | ||
| const execBash = new ExecuteBash({ command: 'cat file.txt' }) | ||
| const needsAcceptance = execBash.requiresAcceptance() | ||
| assert.equal(needsAcceptance, false, 'Read-only command should not require acceptance') | ||
| }) | ||
|
|
||
| it('whichCommand cannot find the first arg', async () => { | ||
| runStub.resolves({ | ||
| exitCode: 1, | ||
| stdout: '', | ||
| stderr: '', | ||
| error: undefined, | ||
| signal: undefined, | ||
| }) | ||
|
|
||
| const execBash = new ExecuteBash({ command: 'noSuchCmd' }) | ||
| await assert.rejects(execBash.validate(), /not found on PATH/i, 'Expected not found error from whichCommand') | ||
| }) | ||
|
|
||
| it('whichCommand sees first arg on PATH', async () => { | ||
| runStub.resolves({ | ||
| exitCode: 0, | ||
| stdout: '/usr/bin/noSuchCmd\n', | ||
| stderr: '', | ||
| error: undefined, | ||
| signal: undefined, | ||
| }) | ||
|
|
||
| const execBash = new ExecuteBash({ command: 'noSuchCmd' }) | ||
| await execBash.validate() | ||
| }) | ||
|
|
||
| it('stub invoke() call', async () => { | ||
| invokeStub.resolves({ | ||
| output: { | ||
| kind: 'json', | ||
| content: { | ||
| exitStatus: '0', | ||
| stdout: 'mocked stdout lines', | ||
| stderr: '', | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| const execBash = new ExecuteBash({ command: 'ls' }) | ||
|
|
||
| const dummyWritable = { write: () => {} } as any | ||
| const result = await execBash.invoke(dummyWritable) | ||
|
|
||
| assert.strictEqual(result.output.kind, 'json') | ||
| const out = result.output.content as unknown as { | ||
| exitStatus: string | ||
| stdout: string | ||
| stderr: string | ||
| } | ||
| assert.strictEqual(out.exitStatus, '0') | ||
| assert.strictEqual(out.stdout, 'mocked stdout lines') | ||
| assert.strictEqual(out.stderr, '') | ||
|
|
||
| assert.strictEqual(invokeStub.callCount, 1) | ||
| }) | ||
| }) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.