# Shell Command

> 在工作流中执行 shell 命令。

Source: https://docs.sommatic.ai/zh/nodes/code.shell/

- 标识: `code.shell`
- 类别: 代码
- 版本: 2.0.0
- 状态: 可用
- 执行方式: async

在工作流中执行 shell 命令。

运行任意 shell 命令（bash、sh）并捕获输出。适用于系统操作、文件处理、CLI 工具和脚本编写。

**功能特性：**
- 完整的 shell 访问，可配置工作目录和超时。
- 分别捕获 stdout 和 stderr。
- 命令字段支持 {{expressions}}，可注入上游节点的数据。

**示例：**
- `curl -s https://api.example.com/data | jq '.results'`
- `ls -la /tmp/uploads/ | wc -l`
- `echo "{{$json.message}}" | base64`

## 配置

- `command` (string, 必填): 要执行的 shell 命令。支持 {{expressions}}。
- `args` (array<string>, 可选): Arguments passed to the program as-is. Each one supports {{expressions}}. 默认值: `[]`.
- `cwd` (string, 可选): 运行命令的目录。默认为应用根目录。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): 命令执行成功（退出码为 0）。
- `error`: 命令返回非零退出码或超时。

## 输入契约

- `command` (string, 必填)
- `args` (array<string>, 可选)
- `cwd` (string, 可选)
- `timeout` (number, 可选)

## 输出契约

- `stdout` (string, 可选): 命令的标准输出。
- `stderr` (string, 可选): 命令的标准错误输出。

## 在表达式中

后续节点可通过 `$("Shell Command").item.json.<路径>` 读取此节点输出中的内容（请把 `Shell Command` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Shell Command").item.json.stdout` (string) = `"total 16\n-rw-r--r--  1 app  app  18342 Nov …"`: 命令的标准输出。
- `$("Shell Command").item.json.stderr` (string) = `""`: 命令的标准错误输出。


## 工作原理

在运行 worker 的主机上，不经 shell 以参数列表运行一个程序，返回去除首尾空白后的 stdout 和 stderr。

1. 解析配置；`args` 中的每个元素都可以使用 `{{ }}` 表达式。
2. 校验 `command`：必填，只能是由字母、数字和 `_ . / @ + -` 组成的程序名或路径（不含空格、引号、管道或运算符）。`args` 必须为数组（默认 `[]`）。
3. 将每个非字符串参数转换为其 JSON 文本。
4. 在 `cwd`（默认为编排器进程的工作目录）中运行程序，超时取 `execution.timeout`，其次 `timeout`，否则为 10000 毫秒。
5. 退出码为 0 时从 `out` 输出去除首尾空白的 `{ stdout, stderr }`；非零退出、超时或启动失败时从 `error` 输出未处理的原始输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-list-uploads",
  "label": "List uploads",
  "operator_slug": "code.shell",
  "operator_version": "2.0.0",
  "config": {
    "command": "ls",
    "args": [
      "-la",
      "{{ $json.folder }}"
    ],
    "cwd": "/tmp",
    "execution": {
      "timeout": 10000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "stdout": "total 16\n-rw-r--r--  1 app  app  18342 Nov 25 14:12 orders.csv",
    "stderr": ""
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

程序以退出码 0 结束。

```json
{
  "stdout": "total 16\n-rw-r--r--  1 app  app  18342 Nov 25 14:12 orders.csv",
  "stderr": ""
}
```

### `error`

校验失败（数据为 `{ error }`），或程序以非零码退出、超时、超出输出缓冲区、无法启动（数据为 `{ error, stderr, stdout }`）。

```json
{
  "error": "Command failed: ls -la /tmp/missing\nls: /tmp/missing: No such file or directory\n",
  "stderr": "ls: /tmp/missing: No such file or directory\n",
  "stdout": ""
}
```

## 代码中的行为

- `execution.timeout`: 超时时间（毫秒，默认 10000）。为空时使用未在 schema 中声明的顶层 `timeout`。此节点会忽略通用执行设置中的 `execution.timeout_ms`。
- `args`: 每个元素按解析后的原样作为一个参数传给程序：不进行通配符展开、变量展开或引号处理。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `command must be a program name or path without a shell (no spaces, pipes or operators); pass its arguments in args` | `error` | `command` 包含空格或 shell 语法，例如 `ls -la`。请将 `ls` 写入 `command`，将 `["-la"]` 写入 `args`。 |
| `args must be an array` | `error` | `args` 是字符串或对象。请写成字符串的 JSON 数组。 |
| `command is required` | `error` | `command` 为空或不是字符串。 |
| `spawn <command> ENOENT` | `error` | 运行 worker 的主机未安装该程序，或程序不在其 `PATH` 中。 |
| `Command failed: <command> <args>
<stderr>` | `error` | 程序以非零码退出，或因超时被终止。请查看 `stderr`；对耗时较长的程序请调大 `execution.timeout`。 |

## 说明与限制

- 不支持管道、重定向和 `&&`；请串联多个节点，或改用 `code.js`、`code.python`。
- 程序只接收语言区域、路径和代理相关的环境变量。stdout 或 stderr 输出超过约 1 MB 会导致运行失败。输出中不包含退出码。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "code.shell",
  "name": "Shell Command",
  "category": "code",
  "version": "2.0.0",
  "description": "Run a program within the workflow, without a shell.\n\n  The program runs with its arguments as a list: values from upstream nodes are passed as arguments and are never interpreted by a shell, so they cannot inject commands. The process does not inherit the service environment.\n\n  **Features:**\n  - Program and arguments as separate fields; each argument supports {{expressions}}.\n  - Stdout and stderr captured separately, with a configurable working directory and timeout.\n\n  **Examples:**\n  - command `ls`, args `[\"-la\", \"/tmp/uploads\"]`\n  - command `base64`, args `[\"--decode\", \"{{ $json.file }}\"]`\n\n  Pipes, redirections and `&&` are not available: chain nodes, or use code.js / code.python.",
  "capabilities": [
    "shell",
    "process",
    "terminal",
    "script"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "command": {
        "type": "string",
        "title": "Program",
        "description": "Program name or path (no spaces, pipes or shell operators)."
      },
      "args": {
        "type": "array",
        "title": "Arguments",
        "description": "Arguments passed to the program as-is. Each one supports {{expressions}}.",
        "items": {
          "type": "string"
        },
        "default": []
      },
      "cwd": {
        "type": "string",
        "title": "Working Directory",
        "description": "Directory to run the program in. Defaults to the application root."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "timeout": {
            "type": "number",
            "default": 10000,
            "title": "Timeout (ms)",
            "description": "Maximum time to wait for the program to finish."
          },
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "command"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "command": {
        "type": "string"
      },
      "args": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "cwd": {
        "type": "string"
      },
      "timeout": {
        "type": "number"
      }
    },
    "required": [
      "command"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "stdout": {
        "type": "string",
        "description": "Standard output from the program."
      },
      "stderr": {
        "type": "string",
        "description": "Standard error output from the program."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Output",
      "description": "Program exited with code 0.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Program returned a non-zero exit code, could not start or timed out.",
      "is_default": false,
      "supports_condition": true
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "desktop-agent",
    "local-agent"
  ],
  "tags": [
    "shell",
    "bash",
    "terminal",
    "script",
    "code"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "command": {
      "type": "string",
      "title": "Program",
      "description": "Program name or path (no spaces, pipes or shell operators)."
    },
    "args": {
      "type": "array",
      "title": "Arguments",
      "description": "Arguments passed to the program as-is. Each one supports {{expressions}}.",
      "items": {
        "type": "string"
      },
      "default": []
    },
    "cwd": {
      "type": "string",
      "title": "Working Directory",
      "description": "Directory to run the program in. Defaults to the application root."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "timeout": {
          "type": "number",
          "default": 10000,
          "title": "Timeout (ms)",
          "description": "Maximum time to wait for the program to finish."
        },
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "command"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "command": {
      "type": "string"
    },
    "args": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "cwd": {
      "type": "string"
    },
    "timeout": {
      "type": "number"
    }
  },
  "required": [
    "command"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "stdout": {
      "type": "string",
      "description": "Standard output from the program."
    },
    "stderr": {
      "type": "string",
      "description": "Standard error output from the program."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Output",
    "description": "Program exited with code 0.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Program returned a non-zero exit code, could not start or timed out.",
    "is_default": false,
    "supports_condition": true
  }
]
```
