> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orcbot.buzzchat.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Shell & Code Execution

> Execute system commands, run TypeScript/Python code, and manage dependencies

# Shell & Code Execution

OrcBot provides powerful system-level execution capabilities including shell commands, TypeScript compilation, and Python virtual environments. All execution skills include safety guardrails and resource limits.

## run\_command

Execute shell commands on the host system.

### Parameters

<ParamField path="command" type="string" required>
  Shell command to execute. Uses PowerShell on Windows, bash/sh on Unix.
</ParamField>

<ParamField path="cwd" type="string">
  Working directory for command execution. Auto-extracted from `cd /path && command` patterns.
</ParamField>

### Return Value

<ResponseField name="output" type="string">
  Combined stdout + stderr. Capped at 8 KB with tail hint if truncated.
</ResponseField>

### Platform Detection

The skill automatically adapts to the host platform:

* **Windows**: Uses PowerShell via `powershell -Command`
* **Unix/Linux/macOS**: Uses `/bin/sh -c`

### Working Directory Auto-Extraction

The skill intelligently extracts working directory from common patterns:

```bash theme={null}
# Pattern 1: cd /path && command
cd /home/user/project && npm test
# Extracted: cwd="/home/user/project", command="npm test"

# Pattern 2: cd /path ; command
cd /tmp ; ls -la
# Extracted: cwd="/tmp", command="ls -la"
```

### Safety Features

1. **Command allow/deny lists**: Configured via `commandAllowList` / `commandDenyList`
2. **Stdout capping**: Output limited to 8 KB to prevent memory overflow
3. **Process tree kill**: Reliable termination on timeout (uses `taskkill /T /F` on Windows)
4. **Safe mode enforcement**: Disabled when `safeMode: true`

### Example Usage

**Run npm test:**

```json theme={null}
{
  "skill": "run_command",
  "args": {
    "command": "npm test",
    "cwd": "/home/user/project"
  }
}
```

**List directory:**

```json theme={null}
{
  "skill": "run_command",
  "args": {
    "command": "ls -la /tmp"
  }
}
```

**Git status:**

```json theme={null}
{
  "skill": "run_command",
  "args": {
    "command": "cd /home/user/project && git status"
  }
}
```

### Response Examples

**Success:**

```
$ npm test

> project@1.0.0 test
> vitest run

 ✓ src/utils.test.ts (3 tests) 24ms
 ✓ src/api.test.ts (5 tests) 31ms

 Test Files  2 passed (2)
      Tests  8 passed (8)
   Start at  10:30:00
   Duration  412ms
```

**Error:**

```
$ npm test
npm ERR! missing script: test

Exit code: 1
```

**Truncated output:**

```
$ npm run build
[... 8000 lines of webpack output ...]

[Output truncated at 8 KB. Full output saved to /tmp/command_output_12345.log]
```

### Configuration Options

**Allow specific commands:**

```yaml theme={null}
commandAllowList:
  - npm
  - git
  - docker
  - python
```

**Deny dangerous commands:**

```yaml theme={null}
commandDenyList:
  - rm -rf /
  - format
  - dd if=/dev/zero
```

**Disable all command execution:**

```yaml theme={null}
safeMode: true
```

### Metadata

* **isDeep**: `true` - Commands are substantive work
* **isDangerous**: `true` - Requires admin approval in autonomy mode

<Warning>
  **Command execution is powerful and dangerous.** Always validate commands before running. Enable `safeMode` in production unless command execution is explicitly required.
</Warning>

## execute\_typescript

Write, compile, and execute TypeScript code on the fly.

### Parameters

<ParamField path="code" type="string" required>
  TypeScript code to compile and execute
</ParamField>

<ParamField path="filename" type="string">
  Optional filename to save/reuse the script. If omitted, saves to `scratchpad.ts`.
</ParamField>

<ParamField path="args" type="array">
  Command-line arguments to pass to the script
</ParamField>

### Return Value

<ResponseField name="output" type="string">
  Combined stdout + stderr from the compiled and executed JavaScript
</ResponseField>

### Features

* **Persistent scratchpad**: If `filename` is omitted, code is saved to a reusable `scratchpad.ts`
* **Named scripts**: Provide `filename` to save for future reuse
* **Execute saved scripts**: Call with only `filename` (no `code`) to re-run
* **TypeScript compilation**: Automatically compiles to JavaScript via `tsc`
* **Full Node.js API access**: Import any installed package

### Example Usage

**Execute TypeScript snippet:**

```json theme={null}
{
  "skill": "execute_typescript",
  "args": {
    "code": "const sum = [1, 2, 3, 4, 5].reduce((a, b) => a + b, 0);\nconsole.log('Sum:', sum);"
  }
}
```

**Save and execute:**

```json theme={null}
{
  "skill": "execute_typescript",
  "args": {
    "code": "import fs from 'fs';\nconst data = fs.readFileSync('/tmp/data.json', 'utf-8');\nconsole.log(JSON.parse(data));",
    "filename": "read_data.ts"
  }
}
```

**Re-run saved script:**

```json theme={null}
{
  "skill": "execute_typescript",
  "args": {
    "filename": "read_data.ts"
  }
}
```

**Pass arguments:**

```json theme={null}
{
  "skill": "execute_typescript",
  "args": {
    "code": "const [arg1, arg2] = process.argv.slice(2);\nconsole.log('Args:', arg1, arg2);",
    "args": ["hello", "world"]
  }
}
```

### Response Example

```
Sum: 15
```

### Use Cases

* **Data processing**: Parse CSV, JSON, or XML files
* **API calls**: Hit undocumented endpoints with custom logic
* **Calculations**: Complex math or statistics
* **Prototyping**: Test algorithms before implementing as skills
* **One-off tasks**: Tasks that don't warrant a full skill

### Metadata

* **isDeep**: `true`
* **isDangerous**: `false` (sandboxed to Node.js API)

<Tip>
  **Use `execute_typescript` for custom logic.** When standard skills can't handle a task, TypeScript execution provides unlimited flexibility without modifying the codebase.
</Tip>

## execute\_python\_code

Execute Python code in an isolated virtual environment.

### Parameters

<ParamField path="code" type="string" required>
  Python code to execute
</ParamField>

<ParamField path="filename" type="string">
  Optional filename to save/reuse the script (e.g., `"script.py"`)
</ParamField>

### Return Value

<ResponseField name="output" type="string">
  Combined stdout + stderr from the Python interpreter
</ResponseField>

### Features

* **Isolated virtual environment**: Uses `~/.orcbot/python-venv/`
* **Persistent environment**: Installed packages persist across runs
* **Auto-activation**: Virtual environment activated automatically
* **Named scripts**: Save scripts for reuse with `filename`
* **Re-execution**: Call with only `filename` to re-run saved scripts

### Example Usage

**Data analysis:**

```json theme={null}
{
  "skill": "execute_python_code",
  "args": {
    "code": "import pandas as pd\ndf = pd.read_csv('/tmp/data.csv')\nprint(df.describe())"
  }
}
```

**Math calculation:**

```json theme={null}
{
  "skill": "execute_python_code",
  "args": {
    "code": "import numpy as np\nresult = np.linalg.inv([[1,2],[3,4]])\nprint(result)"
  }
}
```

**Save script:**

```json theme={null}
{
  "skill": "execute_python_code",
  "args": {
    "code": "print('Hello from Python')",
    "filename": "hello.py"
  }
}
```

### Response Example

```
            A          B          C
count  100.0  100.0  100.0
mean    50.5   75.3   92.1
std     28.9   15.2   10.5
min      1.0   45.0   70.0
max    100.0  105.0  115.0
```

### Metadata

* **isDeep**: `true`
* **isDangerous**: `false`

<Note>
  **Only use Python for tasks requiring Python libraries.** Prefer `execute_typescript` for general scripting since Node.js is already available.
</Note>

## install\_npm\_dependency

Install an NPM package for use in custom skills or TypeScript execution.

### Parameters

<ParamField path="packageName" type="string" required>
  NPM package name (e.g., `"axios"`, `"lodash"`, `"@types/node"`)
</ParamField>

### Return Value

<ResponseField name="result" type="string">
  npm install output
</ResponseField>

### Example Usage

```json theme={null}
{
  "skill": "install_npm_dependency",
  "args": {
    "packageName": "axios"
  }
}
```

### Response Example

```
$ npm install axios
added 5 packages in 2s
```

### Metadata

* **isDeep**: `false`
* **isDangerous**: `false`

## install\_python\_package

Install a Python package via pip into the isolated virtual environment.

### Parameters

<ParamField path="package" type="string" required>
  Package name (e.g., `"pandas"`, `"numpy"`, `"requests"`)
</ParamField>

### Return Value

<ResponseField name="result" type="string">
  pip install output
</ResponseField>

### Example Usage

```json theme={null}
{
  "skill": "install_python_package",
  "args": {
    "package": "pandas"
  }
}
```

### Response Example

```
Collecting pandas
  Downloading pandas-2.1.4-cp311-cp311-linux_x86_64.whl (12.3 MB)
Installing collected packages: pandas
Successfully installed pandas-2.1.4
```

### Metadata

* **isDeep**: `false`
* **isDangerous**: `false`

<Tip>
  Install packages on-demand as needed. The virtual environment persists, so packages only need to be installed once.
</Tip>

## get\_system\_info

Get platform, OS, Node version, shell, and command guidance.

### Parameters

None.

### Return Value

<ResponseField name="info" type="object">
  System information:

  * `platform`: OS platform (linux, darwin, win32)
  * `arch`: CPU architecture
  * `nodeVersion`: Node.js version
  * `shell`: Default shell
  * `timestamp`: Current date/time
  * `guidance`: Platform-specific command tips
</ResponseField>

### Example Usage

```json theme={null}
{
  "skill": "get_system_info",
  "args": {}
}
```

### Response Example

```json theme={null}
{
  "platform": "linux",
  "arch": "x64",
  "nodeVersion": "v20.10.0",
  "shell": "/bin/bash",
  "timestamp": "2025-01-15T10:30:00.000Z",
  "guidance": "Use bash commands. Package manager: apt. Path separator: /"
}
```

### Metadata

* **isDeep**: `false`

## system\_check

Verify that commands, shared libraries, and file paths exist.

### Parameters

<ParamField path="commands" type="array">
  Command names to check (e.g., `["node", "git", "docker"]`)
</ParamField>

<ParamField path="libraries" type="array">
  Shared library names (e.g., `["libssl.so", "libcrypto.so"]`)
</ParamField>

<ParamField path="paths" type="array">
  File paths to verify (e.g., `["/etc/hosts", "/usr/bin/python3"]`)
</ParamField>

### Return Value

<ResponseField name="results" type="object">
  Verification results for each category with pass/fail status
</ResponseField>

### Example Usage

```json theme={null}
{
  "skill": "system_check",
  "args": {
    "commands": ["node", "npm", "git"],
    "paths": ["/etc/hosts"]
  }
}
```

### Response Example

```json theme={null}
{
  "commands": {
    "node": "found at /usr/bin/node",
    "npm": "found at /usr/bin/npm",
    "git": "found at /usr/bin/git"
  },
  "paths": {
    "/etc/hosts": "exists"
  }
}
```

### Metadata

* **isDeep**: `false`

## Best Practices

<Tip>
  **Execution skill priority:**

  1. Use `run_command` for existing CLI tools (npm, git, docker)
  2. Use `execute_typescript` for custom JavaScript/TypeScript logic
  3. Use `execute_python_code` for data science (pandas, numpy) or Python-specific libs
  4. Consider creating a custom skill for frequently-used operations
</Tip>

<Warning>
  **Security considerations:**

  * Never pass untrusted user input directly to `run_command`
  * Enable `commandDenyList` to block dangerous operations
  * Set `safeMode: true` in production to disable command execution
  * Use `execute_typescript` / `execute_python_code` for sandboxed logic
</Warning>

## Common Workflows

### Git Operations

```typescript theme={null}
// Check git status
run_command("git status")

// Create branch and commit
run_command("cd /project && git checkout -b feature && git add . && git commit -m 'Add feature'")
```

### NPM Project Management

```typescript theme={null}
// Install dependencies
run_command("npm install")

// Run tests
run_command("npm test")

// Build project
run_command("npm run build")
```

### Data Processing Pipeline

```typescript theme={null}
// 1. Download data
download_file("https://example.com/data.csv")

// 2. Process with Python
execute_python_code(`
import pandas as pd
df = pd.read_csv('~/.orcbot/downloads/data.csv')
result = df.groupby('category').sum()
result.to_json('output.json')
`)

// 3. Read and deliver
read_file("output.json")
send_file(chatId, "output.json")
```

## Troubleshooting

### "Command not found"

* **Cause**: Command not installed or not in PATH
* **Fix**: Use `system_check` to verify, then install missing command or use absolute path

### "Permission denied"

* **Cause**: Insufficient file permissions
* **Fix**: Use `chmod +x` or run with appropriate user permissions

### "Timeout"

* **Cause**: Command took too long
* **Fix**: Increase timeout in config or split into smaller operations

### "Output truncated"

* **Cause**: Command output exceeded 8 KB
* **Fix**: Redirect output to file, then read file in chunks

## Related Skills

<CardGroup cols={2}>
  <Card title="File Operations" icon="folder" href="/api/skills/files">
    Read, write, and process files
  </Card>

  <Card title="Configuration" icon="gear" href="/api/skills/configuration">
    Manage system settings
  </Card>
</CardGroup>
