-
Notifications
You must be signed in to change notification settings - Fork 3.2k
feat(block): add command line executor block #2745
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
Open
jgranesa
wants to merge
7
commits into
simstudioai:staging
Choose a base branch
from
jgranesa:feat/command
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+334
−0
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c89ac0f
add commandline executor block
jgranesa e7553d1
Update apps/sim/app/api/tools/command/exec/route.ts
jgranesa d945e65
Update apps/sim/app/api/tools/command/exec/route.ts
jgranesa c385c9f
Update apps/sim/app/api/tools/command/exec/route.ts
jgranesa adc7986
Update apps/sim/tools/command/chat.ts
jgranesa 67b0831
feat use sim logger rather than console log
jgranesa 0da0016
chore(block): remove unused and unnecessary code
jgranesa 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
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,165 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { spawn } from "child_process"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import type { CommandInput, CommandOutput } from "@/tools/command/types"; | ||
| import { getSession } from '@/lib/auth' | ||
|
|
||
| const logger = createLogger('CommandExecAPI') | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| try { | ||
| const session = await getSession() | ||
| if (!session?.user?.id) { | ||
| return NextResponse.json( | ||
| { error: 'Unauthorized' }, | ||
| { status: 401 }, | ||
| ) | ||
| } | ||
|
|
||
| const params: CommandInput = await request.json() | ||
|
|
||
| import { validatePathSegment } from '@/lib/core/security/input-validation' | ||
|
|
||
| // Validate input | ||
| if (!params.command) { | ||
| return NextResponse.json( | ||
| { error: "Command is required" }, | ||
| { status: 400 }, | ||
| ) | ||
| } | ||
|
|
||
| // Validate workingDirectory if provided | ||
| if (params.workingDirectory) { | ||
| const validation = validatePathSegment(params.workingDirectory, { | ||
| paramName: 'workingDirectory', | ||
| allowDots: true // Allow relative paths like ../ | ||
| }) | ||
| if (!validation.isValid) { | ||
| return NextResponse.json( | ||
| { error: validation.error }, | ||
| { status: 400 }, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| // Validate shell if provided - only allow safe shells | ||
| const allowedShells = ['/bin/bash', '/bin/sh', '/bin/zsh'] | ||
| if (params.shell && !allowedShells.includes(params.shell)) { | ||
| return NextResponse.json( | ||
| { error: 'Invalid shell. Allowed shells: ' + allowedShells.join(', ') }, | ||
| { status: 400 }, | ||
| ) | ||
| } | ||
|
|
||
| // Set default values | ||
| const workingDirectory = params.workingDirectory || process.cwd() | ||
| const timeout = params.timeout || 30000 | ||
| const shell = params.shell || '/bin/bash' | ||
| // Execute command | ||
| const startTime = Date.now(); | ||
| const result = await executeCommand( | ||
| params.command, | ||
| workingDirectory, | ||
| timeout, | ||
| shell, | ||
| ); | ||
| const duration = Date.now() - startTime; | ||
|
|
||
| const output: CommandOutput = { | ||
| stdout: result.stdout, | ||
| stderr: result.stderr, | ||
| exitCode: result.exitCode, | ||
| duration, | ||
| command: params.command, | ||
| workingDirectory, | ||
| timedOut: result.timedOut, | ||
| }; | ||
|
|
||
| return NextResponse.json(output); | ||
| } catch (error) { | ||
| logger.error('Command execution error:', { error }) | ||
| return NextResponse.json( | ||
| { | ||
| error: error instanceof Error ? error.message : "Unknown error occurred", | ||
| }, | ||
| { status: 500 }, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| interface ExecutionResult { | ||
| stdout: string; | ||
| stderr: string; | ||
| exitCode: number; | ||
| timedOut: boolean; | ||
| } | ||
|
|
||
| function executeCommand( | ||
| command: string, | ||
| workingDirectory: string, | ||
| timeout: number, | ||
| shell: string, | ||
| ): Promise<ExecutionResult> { | ||
| return new Promise((resolve) => { | ||
| let stdout = ""; | ||
| let stderr = ""; | ||
| let timedOut = false; | ||
|
|
||
| // Merge environment variables | ||
| const env = { | ||
| ...process.env, | ||
| }; | ||
|
|
||
| // Spawn the process | ||
| const proc = spawn(shell, ["-c", command], { | ||
| cwd: workingDirectory, | ||
| env, | ||
| timeout, | ||
| }); | ||
|
|
||
| // Set up timeout | ||
| const timeoutId = setTimeout(() => { | ||
| timedOut = true; | ||
| proc.kill("SIGTERM"); | ||
|
|
||
| // Force kill after 5 seconds if still running | ||
| setTimeout(() => { | ||
| if (!proc.killed) { | ||
| proc.kill("SIGKILL"); | ||
| } | ||
| }, 5000); | ||
| }, timeout); | ||
|
|
||
| // Capture stdout | ||
| proc.stdout?.on("data", (data: Buffer) => { | ||
| stdout += data.toString(); | ||
| }); | ||
|
|
||
| // Capture stderr | ||
| proc.stderr?.on("data", (data: Buffer) => { | ||
| stderr += data.toString(); | ||
| }); | ||
|
|
||
| // Handle process completion | ||
| proc.on("close", (code: number | null) => { | ||
| clearTimeout(timeoutId); | ||
| resolve({ | ||
| stdout, | ||
| stderr, | ||
| exitCode: code ?? -1, | ||
| timedOut, | ||
| }); | ||
| }); | ||
|
|
||
| // Handle process errors | ||
| proc.on("error", (error: Error) => { | ||
| clearTimeout(timeoutId); | ||
| resolve({ | ||
| stdout, | ||
| stderr: stderr + `\nProcess error: ${error.message}`, | ||
| exitCode: -1, | ||
| timedOut, | ||
| }); | ||
| }); | ||
| }); | ||
| } |
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,86 @@ | ||
| import { Terminal } from "lucide-react"; | ||
| import type { BlockConfig } from "@/blocks/types"; | ||
|
|
||
| export const commandBlock: BlockConfig = { | ||
| type: "command", | ||
| name: "Command", | ||
| description: "Execute bash commands in a specified working directory with optional timeout and shell configuration.", | ||
| category: "tools", | ||
| bgColor: "#10B981", | ||
| icon: Terminal, | ||
| subBlocks: [ | ||
| { | ||
| id: "command", | ||
| title: "Command", | ||
| type: "long-input", | ||
| placeholder: 'echo "Hello World"', | ||
| required: true, | ||
| }, | ||
| { | ||
| id: "workingDirectory", | ||
| title: "Working Directory", | ||
| type: "short-input", | ||
| placeholder: "/path/to/directory (optional)", | ||
| required: false, | ||
| }, | ||
| { | ||
| id: "timeout", | ||
| title: "Timeout (ms)", | ||
| type: "short-input", | ||
| placeholder: "30000", | ||
| value: () => "30000", | ||
| required: false, | ||
| }, | ||
| { | ||
| id: "shell", | ||
| title: "Shell", | ||
| type: "short-input", | ||
| placeholder: "/bin/bash", | ||
| value: () => "/bin/bash", | ||
| required: false, | ||
| }, | ||
| ], | ||
| tools: { | ||
| access: ["command_exec"], | ||
| config: { | ||
| tool: () => "command_exec", | ||
| params: (params: Record<string, any>) => { | ||
| const transformed: Record<string, any> = { | ||
| command: params.command, | ||
| }; | ||
|
|
||
| if (params.workingDirectory) { | ||
| transformed.workingDirectory = params.workingDirectory; | ||
| } | ||
|
|
||
| if (params.timeout) { | ||
| const timeoutNum = Number.parseInt(params.timeout as string, 10); | ||
| if (!Number.isNaN(timeoutNum)) { | ||
| transformed.timeout = timeoutNum; | ||
| } | ||
| } | ||
|
|
||
| if (params.shell) { | ||
| transformed.shell = params.shell; | ||
| } | ||
|
|
||
| return transformed; | ||
| }, | ||
| }, | ||
| }, | ||
| inputs: { | ||
| command: { type: "string", description: "The bash command to execute" }, | ||
| workingDirectory: { type: "string", description: "Directory where the command will be executed" }, | ||
| timeout: { type: "number", description: "Maximum execution time in milliseconds" }, | ||
| shell: { type: "string", description: "Shell to use for execution" }, | ||
| }, | ||
| outputs: { | ||
| stdout: { type: "string", description: "Standard output from the command" }, | ||
| stderr: { type: "string", description: "Standard error from the command" }, | ||
| exitCode: { type: "number", description: "Command exit code (0 = success)" }, | ||
| duration: { type: "number", description: "Execution time in milliseconds" }, | ||
| command: { type: "string", description: "The executed command" }, | ||
| workingDirectory: { type: "string", description: "The directory where command was executed" }, | ||
| timedOut: { type: "boolean", description: "Whether the command exceeded the timeout" }, | ||
| }, | ||
| }; |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import type { CommandInput, CommandOutput } from '@/tools/command/types' | ||
| import type { ToolConfig } from '@/tools/types' | ||
|
|
||
| export const commandExecTool: ToolConfig<CommandInput, CommandOutput> = { | ||
| id: 'command_exec', | ||
| name: 'Command', | ||
| description: 'Execute bash commands with custom environment variables', | ||
| version: '1.0.0', | ||
|
|
||
| params: { | ||
| command: { | ||
| type: 'string', | ||
| required: true, | ||
| visibility: 'user-or-llm', | ||
| description: 'The bash command to execute', | ||
| }, | ||
| workingDirectory: { | ||
| type: 'string', | ||
| required: false, | ||
| visibility: 'user-only', | ||
| description: 'Directory where the command will be executed', | ||
| }, | ||
| timeout: { | ||
| type: 'number', | ||
| required: false, | ||
| visibility: 'user-only', | ||
| description: 'Maximum execution time in milliseconds', | ||
| }, | ||
| shell: { | ||
| type: 'string', | ||
| required: false, | ||
| visibility: 'user-only', | ||
| description: 'Shell to use for execution', | ||
| }, | ||
| }, | ||
|
|
||
| request: { | ||
| url: '/api/tools/command/exec', | ||
| method: 'POST', | ||
| headers: () => ({ | ||
| 'Content-Type': 'application/json', | ||
| }), | ||
| body: (params) => ({ | ||
| command: params.command, | ||
| workingDirectory: params.workingDirectory, | ||
| timeout: params.timeout || 30000, | ||
| shell: params.shell || '/bin/bash', | ||
| }), | ||
| }, | ||
| }, | ||
|
|
||
| outputs: { | ||
| stdout: { type: 'string', description: 'Standard output from the command' }, | ||
| stderr: { type: 'string', description: 'Standard error from the command' }, | ||
| exitCode: { type: 'number', description: 'Command exit code (0 = success)' }, | ||
| duration: { type: 'number', description: 'Execution time in milliseconds' }, | ||
| command: { type: 'string', description: 'The executed command' }, | ||
| workingDirectory: { type: 'string', description: 'The directory where command was executed' }, | ||
| timedOut: { type: 'boolean', description: 'Whether the command exceeded the timeout' }, | ||
| }, | ||
| }; | ||
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,2 @@ | ||
| export * from './chat' | ||
| export * from './types' |
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,16 @@ | ||
| export interface CommandInput { | ||
| command: string; // The bash command to execute | ||
| workingDirectory?: string; // Optional working directory (defaults to workspace root) | ||
| timeout?: number; // Optional timeout in milliseconds (default: 30000) | ||
| shell?: string; // Optional shell to use (default: /bin/bash) | ||
| } | ||
|
|
||
| export interface CommandOutput { | ||
| stdout: string; // Standard output from the command | ||
| stderr: string; // Standard error from the command | ||
| exitCode: number; // Exit code of the command | ||
| duration: number; // Execution duration in milliseconds | ||
| command: string; // The executed command | ||
| workingDirectory: string; // The directory where command was executed | ||
| timedOut: boolean; // Whether the command timed out | ||
| } |
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
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.