Skip to content
Open
Show file tree
Hide file tree
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 Mar 5, 2026
2a8aae6
fix(execute-command): fix $-pattern substitution, maxBuffer vs timeou…
waleedlatif1 Mar 5, 2026
cf67966
fix(execute-command): address review feedback — double-substitution, …
waleedlatif1 Mar 5, 2026
24e1bfd
fix(execute-command): return partial output on timeout/maxBuffer inst…
waleedlatif1 Mar 5, 2026
5dc31b5
chore(execute-command): remove unused escapeRegExp import
waleedlatif1 Mar 5, 2026
0f293e8
fix(execute-command): normalize both sides of variable name compariso…
waleedlatif1 Mar 5, 2026
94679a6
fix(execute-command): sandbox child process env, fix maxBuffer detection
waleedlatif1 Mar 5, 2026
6774ad1
feat(execute-command): add wandConfig for AI command generation
waleedlatif1 Mar 5, 2026
8622ea4
fix(execute-command): prevent cascading variable resolution
waleedlatif1 Mar 5, 2026
281f5bb
fix(execute-command): fix ProcessEnv type for child process env
waleedlatif1 Mar 5, 2026
3d0b07b
fix(execute-command): throw on unresolved block refs, block env var o…
waleedlatif1 Mar 5, 2026
7b7ab8d
fix(execute-command): extend env blocklist, add error output, fix tag…
waleedlatif1 Mar 5, 2026
c4cb2aa
fix(execute-command): add JAVA_TOOL_OPTIONS and PERL5OPT to env block…
waleedlatif1 Mar 5, 2026
5782b68
fix(execute-command): static import, user-configurable timeout, overl…
waleedlatif1 Mar 5, 2026
448548e
fix(execute-command): cap timeout at MAX_DURATION, simplify error han…
waleedlatif1 Mar 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/sim/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,7 @@ API_ENCRYPTION_KEY=your_api_encryption_key # Use `openssl rand -hex 32` to gener
# Admin API (Optional - for self-hosted GitOps)
# ADMIN_API_KEY= # Use `openssl rand -hex 32` to generate. Enables admin API for workflow export/import.
# Usage: curl -H "x-admin-key: your_key" https://your-instance/api/v1/admin/workspaces

# Execute Command (Optional - self-hosted only)
# EXECUTE_COMMAND_ENABLED=true # Enable shell command execution in workflows
# NEXT_PUBLIC_EXECUTE_COMMAND_ENABLED=true # Show Execute Command block in the UI
337 changes: 337 additions & 0 deletions apps/sim/app/api/execute-command/run/route.ts
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)
Comment thread
waleedlatif1 marked this conversation as resolved.
Outdated
}

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 }
)
}
}
53 changes: 53 additions & 0 deletions apps/sim/blocks/blocks/execute-command.ts
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',
},
Comment thread
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)' },
},
}
Loading