-
Notifications
You must be signed in to change notification settings - Fork 3.5k
feat(blocks): add execute command block for self-hosted shell execution #3426
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
waleedlatif1
wants to merge
15
commits into
staging
Choose a base branch
from
waleedlatif1/execute-command-block
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.
Open
Changes from 2 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
6802245
feat(blocks): add execute command block for self-hosted shell execution
waleedlatif1 2a8aae6
fix(execute-command): fix $-pattern substitution, maxBuffer vs timeou…
waleedlatif1 cf67966
fix(execute-command): address review feedback — double-substitution, …
waleedlatif1 24e1bfd
fix(execute-command): return partial output on timeout/maxBuffer inst…
waleedlatif1 5dc31b5
chore(execute-command): remove unused escapeRegExp import
waleedlatif1 0f293e8
fix(execute-command): normalize both sides of variable name compariso…
waleedlatif1 94679a6
fix(execute-command): sandbox child process env, fix maxBuffer detection
waleedlatif1 6774ad1
feat(execute-command): add wandConfig for AI command generation
waleedlatif1 8622ea4
fix(execute-command): prevent cascading variable resolution
waleedlatif1 281f5bb
fix(execute-command): fix ProcessEnv type for child process env
waleedlatif1 3d0b07b
fix(execute-command): throw on unresolved block refs, block env var o…
waleedlatif1 7b7ab8d
fix(execute-command): extend env blocklist, add error output, fix tag…
waleedlatif1 c4cb2aa
fix(execute-command): add JAVA_TOOL_OPTIONS and PERL5OPT to env block…
waleedlatif1 5782b68
fix(execute-command): static import, user-configurable timeout, overl…
waleedlatif1 448548e
fix(execute-command): cap timeout at MAX_DURATION, simplify error han…
waleedlatif1 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
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,337 @@ | ||
| import { exec } from 'child_process' | ||
| import { createLogger } from '@sim/logger' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { checkInternalAuth } from '@/lib/auth/hybrid' | ||
| import { isExecuteCommandEnabled } from '@/lib/core/config/feature-flags' | ||
| import { generateRequestId } from '@/lib/core/utils/request' | ||
| import { escapeRegExp, normalizeName, REFERENCE } from '@/executor/constants' | ||
| import { type OutputSchema, resolveBlockReference } from '@/executor/utils/block-reference' | ||
| import { | ||
| createEnvVarPattern, | ||
| createWorkflowVariablePattern, | ||
| } from '@/executor/utils/reference-validation' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
| export const runtime = 'nodejs' | ||
| export const MAX_DURATION = 210 | ||
|
|
||
| const logger = createLogger('ExecuteCommandAPI') | ||
|
|
||
| const MAX_BUFFER = 10 * 1024 * 1024 // 10MB | ||
|
|
||
| /** | ||
| * Resolves workflow variables (<variable.name>) by replacing them with their actual values | ||
| */ | ||
| function resolveWorkflowVariables(command: string, workflowVariables: Record<string, any>): string { | ||
| let resolved = command | ||
| const regex = createWorkflowVariablePattern() | ||
| let match: RegExpExecArray | null | ||
| const replacements: Array<{ match: string; index: number; value: string }> = [] | ||
|
|
||
| while ((match = regex.exec(command)) !== null) { | ||
| const variableName = match[1].trim() | ||
| const foundVariable = Object.entries(workflowVariables).find( | ||
| ([_, variable]) => normalizeName(variable.name || '') === variableName | ||
| ) | ||
|
|
||
| if (!foundVariable) { | ||
| const availableVars = Object.values(workflowVariables) | ||
| .map((v: any) => v.name) | ||
| .filter(Boolean) | ||
| throw new Error( | ||
| `Variable "${variableName}" doesn't exist.` + | ||
| (availableVars.length > 0 ? ` Available: ${availableVars.join(', ')}` : '') | ||
| ) | ||
| } | ||
|
|
||
| const variable = foundVariable[1] | ||
| let value = variable.value | ||
|
|
||
| if (typeof value === 'object' && value !== null) { | ||
| value = JSON.stringify(value) | ||
| } else { | ||
| value = String(value ?? '') | ||
| } | ||
|
|
||
| replacements.push({ match: match[0], index: match.index, value }) | ||
| } | ||
|
|
||
| for (let i = replacements.length - 1; i >= 0; i--) { | ||
| const { match: matchStr, index, value } = replacements[i] | ||
| resolved = resolved.slice(0, index) + value + resolved.slice(index + matchStr.length) | ||
| } | ||
|
|
||
| return resolved | ||
| } | ||
|
|
||
| /** | ||
| * Resolves environment variables ({{ENV_VAR}}) by replacing them with their actual values | ||
| */ | ||
| function resolveEnvironmentVariables(command: string, envVars: Record<string, string>): string { | ||
| let resolved = command | ||
| const regex = createEnvVarPattern() | ||
| let match: RegExpExecArray | null | ||
| const replacements: Array<{ match: string; index: number; value: string }> = [] | ||
|
|
||
| while ((match = regex.exec(command)) !== null) { | ||
| const varName = match[1].trim() | ||
| if (!(varName in envVars)) { | ||
| continue | ||
| } | ||
| replacements.push({ match: match[0], index: match.index, value: envVars[varName] }) | ||
| } | ||
|
|
||
| for (let i = replacements.length - 1; i >= 0; i--) { | ||
| const { match: matchStr, index, value } = replacements[i] | ||
| resolved = resolved.slice(0, index) + value + resolved.slice(index + matchStr.length) | ||
| } | ||
|
|
||
| return resolved | ||
| } | ||
|
|
||
| /** | ||
| * Resolves block reference tags (<blockName.field>) by replacing them with their actual values | ||
| */ | ||
| function resolveTagVariables( | ||
| command: string, | ||
| blockData: Record<string, unknown>, | ||
| blockNameMapping: Record<string, string>, | ||
| blockOutputSchemas: Record<string, OutputSchema> | ||
| ): string { | ||
| let resolved = command | ||
|
|
||
| const tagPattern = new RegExp( | ||
| `${REFERENCE.START}([a-zA-Z_](?:[a-zA-Z0-9_${REFERENCE.PATH_DELIMITER}]*[a-zA-Z0-9_])?)${REFERENCE.END}`, | ||
| 'g' | ||
| ) | ||
| const tagMatches = resolved.match(tagPattern) || [] | ||
|
|
||
| for (const match of tagMatches) { | ||
| const tagName = match.slice(REFERENCE.START.length, -REFERENCE.END.length).trim() | ||
| const pathParts = tagName.split(REFERENCE.PATH_DELIMITER) | ||
| const blockName = pathParts[0] | ||
| const fieldPath = pathParts.slice(1) | ||
|
|
||
| const result = resolveBlockReference(blockName, fieldPath, { | ||
| blockNameMapping, | ||
| blockData, | ||
| blockOutputSchemas, | ||
| }) | ||
|
|
||
| if (!result) { | ||
| continue | ||
| } | ||
|
|
||
| let stringValue: string | ||
| if (result.value === undefined || result.value === null) { | ||
| stringValue = '' | ||
| } else if (typeof result.value === 'object') { | ||
| stringValue = JSON.stringify(result.value) | ||
| } else { | ||
| stringValue = String(result.value) | ||
| } | ||
|
|
||
| resolved = resolved.replace(new RegExp(escapeRegExp(match), 'g'), () => stringValue) | ||
| } | ||
|
|
||
| return resolved | ||
| } | ||
|
|
||
| /** | ||
| * Resolves all variable references in a command string | ||
| */ | ||
| function resolveCommandVariables( | ||
| command: string, | ||
| envVars: Record<string, string>, | ||
| blockData: Record<string, unknown>, | ||
| blockNameMapping: Record<string, string>, | ||
| blockOutputSchemas: Record<string, OutputSchema>, | ||
| workflowVariables: Record<string, unknown> | ||
| ): string { | ||
| let resolved = command | ||
| resolved = resolveWorkflowVariables(resolved, workflowVariables) | ||
| resolved = resolveEnvironmentVariables(resolved, envVars) | ||
| resolved = resolveTagVariables(resolved, blockData, blockNameMapping, blockOutputSchemas) | ||
| return resolved | ||
| } | ||
|
|
||
| interface CommandResult { | ||
| stdout: string | ||
| stderr: string | ||
| exitCode: number | ||
| timedOut: boolean | ||
| maxBufferExceeded: boolean | ||
| } | ||
|
|
||
| /** | ||
| * Execute a shell command and return stdout, stderr, exitCode. | ||
| * Distinguishes between a process that exited with non-zero (normal) and one that was killed (timeout). | ||
| */ | ||
| function executeCommand( | ||
| command: string, | ||
| options: { timeout: number; cwd?: string; env?: Record<string, string> } | ||
| ): Promise<CommandResult> { | ||
| return new Promise((resolve) => { | ||
| const childProcess = exec( | ||
| command, | ||
| { | ||
| timeout: options.timeout, | ||
| cwd: options.cwd || undefined, | ||
| maxBuffer: MAX_BUFFER, | ||
| env: { ...process.env, ...options.env }, | ||
| }, | ||
| (error, stdout, stderr) => { | ||
| if (error) { | ||
| const killed = error.killed ?? false | ||
| const isMaxBuffer = killed && /maxBuffer/.test(error.message ?? '') | ||
| const exitCode = typeof error.code === 'number' ? error.code : 1 | ||
| resolve({ | ||
| stdout: stdout.trimEnd(), | ||
| stderr: stderr.trimEnd(), | ||
| exitCode, | ||
| timedOut: killed && !isMaxBuffer, | ||
| maxBufferExceeded: isMaxBuffer, | ||
| }) | ||
| return | ||
| } | ||
| resolve({ | ||
| stdout: stdout.trimEnd(), | ||
| stderr: stderr.trimEnd(), | ||
| exitCode: 0, | ||
| timedOut: false, | ||
| maxBufferExceeded: false, | ||
| }) | ||
| } | ||
| ) | ||
|
|
||
| childProcess.on('error', (err) => { | ||
| resolve({ | ||
| stdout: '', | ||
| stderr: err.message, | ||
| exitCode: 1, | ||
| timedOut: false, | ||
| maxBufferExceeded: false, | ||
| }) | ||
| }) | ||
| }) | ||
| } | ||
|
|
||
| export async function POST(req: NextRequest) { | ||
| const requestId = generateRequestId() | ||
|
|
||
| try { | ||
| if (!isExecuteCommandEnabled) { | ||
| logger.warn(`[${requestId}] Execute Command is disabled`) | ||
| return NextResponse.json( | ||
| { | ||
| success: false, | ||
| error: | ||
| 'Execute Command is not enabled. Set EXECUTE_COMMAND_ENABLED=true in your environment to use this feature. Only available for self-hosted deployments.', | ||
| }, | ||
| { status: 403 } | ||
| ) | ||
| } | ||
|
|
||
| const auth = await checkInternalAuth(req) | ||
| if (!auth.success || !auth.userId) { | ||
| logger.warn(`[${requestId}] Unauthorized execute command attempt`) | ||
| return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| const body = await req.json() | ||
| const { DEFAULT_EXECUTION_TIMEOUT_MS } = await import('@/lib/execution/constants') | ||
|
|
||
| const { | ||
| command, | ||
| timeout = DEFAULT_EXECUTION_TIMEOUT_MS, | ||
| workingDirectory, | ||
| envVars = {}, | ||
| blockData = {}, | ||
| blockNameMapping = {}, | ||
| blockOutputSchemas = {}, | ||
| workflowVariables = {}, | ||
| workflowId, | ||
| } = body | ||
|
|
||
| if (!command || typeof command !== 'string') { | ||
| return NextResponse.json( | ||
| { success: false, error: 'Command is required and must be a string' }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
|
|
||
| logger.info(`[${requestId}] Execute command request`, { | ||
| commandLength: command.length, | ||
| timeout, | ||
| workingDirectory: workingDirectory || '(default)', | ||
| workflowId, | ||
| }) | ||
|
|
||
| const resolvedCommand = resolveCommandVariables( | ||
| command, | ||
| envVars, | ||
| blockData, | ||
| blockNameMapping, | ||
| blockOutputSchemas, | ||
| workflowVariables | ||
| ) | ||
|
|
||
| const result = await executeCommand(resolvedCommand, { | ||
| timeout, | ||
| cwd: workingDirectory, | ||
| env: envVars, | ||
| }) | ||
|
|
||
| logger.info(`[${requestId}] Command completed`, { | ||
| exitCode: result.exitCode, | ||
| timedOut: result.timedOut, | ||
| stdoutLength: result.stdout.length, | ||
| stderrLength: result.stderr.length, | ||
| workflowId, | ||
| }) | ||
|
|
||
| if (result.timedOut) { | ||
| return NextResponse.json({ | ||
| success: false, | ||
| output: { | ||
| stdout: result.stdout, | ||
| stderr: result.stderr, | ||
| exitCode: result.exitCode, | ||
| }, | ||
| error: `Command timed out after ${timeout}ms`, | ||
| }) | ||
| } | ||
|
|
||
| if (result.maxBufferExceeded) { | ||
| return NextResponse.json({ | ||
| success: false, | ||
| output: { | ||
| stdout: result.stdout, | ||
| stderr: result.stderr, | ||
| exitCode: result.exitCode, | ||
| }, | ||
| error: `Command output exceeded maximum buffer size of ${MAX_BUFFER / 1024 / 1024}MB`, | ||
| }) | ||
| } | ||
|
|
||
| return NextResponse.json({ | ||
| success: true, | ||
| output: { | ||
| stdout: result.stdout, | ||
| stderr: result.stderr, | ||
| exitCode: result.exitCode, | ||
| }, | ||
| }) | ||
| } catch (error: unknown) { | ||
| const message = error instanceof Error ? error.message : 'Unknown error' | ||
| logger.error(`[${requestId}] Execute command failed`, { error: message }) | ||
| return NextResponse.json( | ||
| { | ||
| success: false, | ||
| output: { stdout: '', stderr: message, exitCode: 1 }, | ||
| error: message, | ||
| }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| } | ||
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,53 @@ | ||
| import { TerminalIcon } from '@/components/icons' | ||
| import { isTruthy } from '@/lib/core/config/env' | ||
| import type { BlockConfig } from '@/blocks/types' | ||
| import type { ExecuteCommandOutput } from '@/tools/execute-command/types' | ||
|
|
||
| export const ExecuteCommandBlock: BlockConfig<ExecuteCommandOutput> = { | ||
| type: 'execute_command', | ||
| name: 'Execute Command', | ||
| description: 'Run shell commands', | ||
| hideFromToolbar: !isTruthy(process.env.NEXT_PUBLIC_EXECUTE_COMMAND_ENABLED), | ||
| longDescription: | ||
| 'Execute shell commands on the host machine. Only available for self-hosted deployments with EXECUTE_COMMAND_ENABLED=true. Commands run in the default shell of the host OS.', | ||
| bestPractices: ` | ||
| - Commands execute in the default shell of the host machine (bash, zsh, cmd, PowerShell). | ||
| - Chain multiple commands with && to run them sequentially. | ||
| - Use <blockName.output> syntax to reference outputs from other blocks. | ||
| - Use {{ENV_VAR}} syntax to reference environment variables. | ||
| - The working directory defaults to the server process directory if not specified. | ||
| - A non-zero exit code is returned as data (exitCode > 0), not treated as a workflow error. Use a Condition block to branch on exitCode if needed. | ||
| `, | ||
| docsLink: 'https://docs.sim.ai/blocks/execute-command', | ||
| category: 'blocks', | ||
| bgColor: '#1E1E1E', | ||
| icon: TerminalIcon, | ||
| subBlocks: [ | ||
| { | ||
| id: 'command', | ||
| title: 'Command', | ||
| type: 'long-input', | ||
| required: true, | ||
| placeholder: 'echo "Hello, World!"', | ||
| }, | ||
| { | ||
| id: 'workingDirectory', | ||
| title: 'Working Directory', | ||
| type: 'short-input', | ||
| required: false, | ||
| placeholder: '/path/to/directory', | ||
| }, | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| ], | ||
| tools: { | ||
| access: ['execute_command_run'], | ||
| }, | ||
| inputs: { | ||
| command: { type: 'string', description: 'Shell command to execute' }, | ||
| workingDirectory: { type: 'string', description: 'Working directory for the command' }, | ||
| }, | ||
| outputs: { | ||
| stdout: { type: 'string', description: 'Standard output from the command' }, | ||
| stderr: { type: 'string', description: 'Standard error output from the command' }, | ||
| exitCode: { type: 'number', description: 'Exit code of the command (0 = success)' }, | ||
| }, | ||
| } | ||
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.