# Approval Gate

> 为前置 Create Task 节点所创建的任务配置审批关卡。通过 PATCH 将 payload.hitl 和 execution.app_slug 写入后端。

Source: https://docs.sommatic.ai/zh/nodes/human.approval.gate/

- 标识: `human.approval.gate`
- 类别: 人工介入
- 版本: 1.0.0
- 状态: 部分可用. 为已有任务配置审批关卡后，立即经由 `accepted` 端口返回。它不会挂起工作流，也不会等待人工决策；`rejected` 和 `timeout` 从不触发。
- 执行方式: sync

为前置 Create Task 节点所创建的任务配置审批关卡。通过 PATCH 将 payload.hitl 和 execution.app_slug 写入后端。

## 配置

- `approval_type` (object, 必填): Binary | Tool | Plan Review | Single-Select | Multi-Select | Review/Edit/Reject
- `title` (string, 必填, 支持表达式): 审批人认领任务时显示。支持 {{ $json.entity_name }} 等表达式。
- `description` (string, 可选, 支持表达式): 在任务详情中向审批人展示的上下文。支持表达式和多行文本。
- `hitl_config` (object, 可选): 子类型专属字段（tool、plan、options、content、min_selection 等）

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

## 输出端口

- `accepted` (默认): 审批人确认操作时触发（Approve / Allow / Confirm / Submit edits）。
- `rejected`: 审批人拒绝或取消时触发（Reject / Deny / Cancel）。
- `timeout`: 任务到期仍无决策时触发（违反 SLA）。
- `error`: 配置审批关卡期间发生技术故障时触发。

## 输入契约

- `task_id` (string, 可选): 由前置 Create Task 节点传入
- `approval_type` (object, 可选)
- `title` (string, 可选)
- `description` (string, 可选)
- `hitl_config` (object, 可选)

## 输出契约

- `task_id` (string, 可选)
- `approval_type` (object, 可选)
- `decision` (string, 可选): 实际的人工决策。实现挂起/恢复后才会填充；在当前的“发出即不管”模式下为 null。 可选值: `approved`, `rejected`, `edited`, `timeout`.
- `selected` (array, 可选): 用于 single_select / multi_select 审批类型。
- `edited_content` (object, 可选): 审批人在批准前编辑了计划步骤或审阅内容时填充。
- `comment` (string, 可选)
- `approver` (string, 可选)

## 在表达式中

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

- `$("Approval Gate").item.json.task_id` (string) = `"task-xxxxxxxxxxxxxxx"`
- `$("Approval Gate").item.json.approval_type` (object) = `{…}`
- `$("Approval Gate").item.json.decision` (string) = `null`: 实际的人工决策。实现挂起/恢复后才会填充；在当前的“发出即不管”模式下为 null。
- `$("Approval Gate").item.json.selected` (array): 用于 single_select / multi_select 审批类型。 **worker 不返回：读取结果为 undefined.**
- `$("Approval Gate").item.json.edited_content` (object): 审批人在批准前编辑了计划步骤或审阅内容时填充。 **worker 不返回：读取结果为 undefined.**
- `$("Approval Gate").item.json.comment` (string) **worker 不返回：读取结果为 undefined.**
- `$("Approval Gate").item.json.approver` (string) **worker 不返回：读取结果为 undefined.**
- `$("Approval Gate").item.json.port` (string) = `"accepted"` (编辑器不提示)
- `$("Approval Gate").item.json.approval_type.id` (number) = `1` (编辑器不提示)
- `$("Approval Gate").item.json.approval_type.name` (string) = `"binary_approval"` (编辑器不提示)
- `$("Approval Gate").item.json.approval_type.title` (string) = `"Binary Approval"` (编辑器不提示)
- `$("Approval Gate").item.json.approval_type.color` (string) = `"#1976d2"` (编辑器不提示)


## 工作原理

部分实现。为已有任务附加审批配置，使任务收件箱用人工审批门应用打开它，然后立即从 `accepted` 继续；不会等待决定。

1. 解析配置并合并到输入 payload 之上（配置优先）。
2. 从配置或输入 payload 读取 `task_id`，通常是前一个 `human.task.create` 的输出。
3. 检查 `task_id`、`approval_type.name` 和 `title`，然后构建 `hitl`：`{ approval_type, title, description, ...hitl_config }`。
4. 从 Work Management API 读取任务；不存在时失败。
5. 将整个任务写回，并把 `payload.hitl` 和 `execution` `{ app_slug: "human-approval-gate", launch_mode: "embedded" }` 合并到现有值中。
6. 通过 `accepted` 返回 `{ task_id, approval_type, decision: null }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-approve-refund",
  "label": "Approve refund",
  "operator_slug": "human.approval.gate",
  "operator_version": "1.0.0",
  "config": {
    "approval_type": {
      "id": 1,
      "name": "binary_approval",
      "title": "Binary Approval",
      "color": "#1976d2"
    },
    "title": "Approve refund for {{ $json.task_title }}",
    "description": "Confirm the refund before it is issued.",
    "hitl_config": {}
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "accepted",
  "task_id": "task-xxxxxxxxxxxxxxx",
  "approval_type": {
    "id": 1,
    "name": "binary_approval",
    "title": "Binary Approval",
    "color": "#1976d2"
  },
  "decision": null
}
```

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

### `accepted`

已在任务上配置审批门。并不表示有人已批准。

```json
{
  "port": "accepted",
  "task_id": "task-xxxxxxxxxxxxxxx",
  "approval_type": {
    "id": 1,
    "name": "binary_approval",
    "title": "Binary Approval",
    "color": "#1976d2"
  },
  "decision": null
}
```

### `rejected`

从不触发：worker 不会等待决定。

### `timeout`

从不触发。

### `error`

缺少输入、任务不存在或后端调用失败。

```json
{
  "port": "error",
  "error": "Missing 'approval_type' or invalid approval type object"
}
```

## 代码中的行为

- `approval_type`: 取值之一：`binary_approval`（1）、`tool_approval`（2）、`plan_review`（3）、`single_select_decision`（4）、`multi_select_decision`（5）、`review_edit_reject`（6），格式为 `{ id, name, title, color }`。
- `hitl_config`: 会展开到 `hitl` 中，因此其键可覆盖 `approval_type`、`title` 和 `description`。各类型结构：`tool_approval` `{ tool: { name, args, risk_level } }`；`plan_review` `{ plan: { steps: [{ id, title, detail }] } }`；选择类 `{ options: [{ id, name, title }] }`；`review_edit_reject` `{ content: { text, editable } }`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'task_id'. This node must be chained after a Human Task Create node. If you are testing with 'Execute step', run the preceding Create Task node first or provide sample data that includes task_id.` | `error` | 配置和 payload 中都没有 `task_id`。 |
| `Missing 'approval_type' or invalid approval type object` | `error` | `approval_type` 缺失或没有 `name`。 |
| `Missing 'title'` | `error` | 解析表达式后 `title` 为空。 |
| `Task '<task_id>' not found. Cannot configure approval gate on a non-existent task.` | `error` | 该任务 id 在 Work Management 中不存在。 |
| `Backend rejected the update` | `error` | 更新响应中没有 `success`；如有后端消息则使用该消息。 |
| `Request failed with status code <status>` | `error` | 后端拒绝了读取或更新请求。 |
| `services.apiManager.uri is not resolved in dependencies.config — check Link Loom Cloud environment config.` | `error` | 编排器未配置后端地址。这是服务配置问题，与节点无关。 |

## 说明与限制

- 尚未实现：挂起运行并按决定路由。`decision` 始终为 `null`；输出契约中的 `selected`、`edited_content`、`comment` 和 `approver` 从不返回；`rejected` 和 `timeout` 从不触发。
- 更新采用“读取-修改-写回”整个任务的方式：读取与写回之间对任务的修改会被覆盖。任务状态不会改变。
- worker 将字段直接放在信封顶层、不使用 `data`，因此引擎把整个信封（包括 `port` 键）作为下一个节点的 payload。
- worker 不设置 `ok`（示例中显示为 `true`）；引擎只按 `port` 路由。


## 契约（JSON Schema）

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

```json
{
  "slug": "human.approval.gate",
  "name": "Approval Gate",
  "category": "hitl",
  "version": "1.0.0",
  "description": "Configures the approval gate on a task created by a preceding Create Task node. Writes payload.hitl + execution.app_slug via PATCH to the backend.",
  "capabilities": [
    "approval",
    "gate",
    "human"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "approval_type",
      "title"
    ],
    "properties": {
      "approval_type": {
        "type": "object",
        "title": "Approval Type",
        "ui_widget": "hitl_approval_type_picker",
        "description": "Binary | Tool | Plan Review | Single-Select | Multi-Select | Review/Edit/Reject"
      },
      "title": {
        "type": "string",
        "title": "Title",
        "format": "expression",
        "description": "Shown to the approver when the task is claimed. Supports expressions like {{ $json.entity_name }}."
      },
      "description": {
        "type": "string",
        "title": "Description",
        "format": "expression",
        "description": "Context shown to the approver inside the task detail. Supports expressions and multi-line text."
      },
      "hitl_config": {
        "type": "object",
        "title": "Approval configuration",
        "ui_widget": "hitl_config",
        "ui_options": {
          "depends_on": "approval_type"
        },
        "description": "Subtype-specific fields (tool, plan, options, content, min_selection, etc.)"
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "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
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "task_id": {
        "type": "string",
        "description": "Propagated from preceding Create Task node"
      },
      "approval_type": {
        "type": "object"
      },
      "title": {
        "type": "string"
      },
      "description": {
        "type": "string"
      },
      "hitl_config": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "task_id": {
        "type": "string"
      },
      "approval_type": {
        "type": "object"
      },
      "decision": {
        "type": "string",
        "enum": [
          "approved",
          "rejected",
          "edited",
          "timeout"
        ],
        "description": "The actual human decision. Populated when suspend/resume is implemented; null in the current fire-and-forget mode."
      },
      "selected": {
        "type": "array",
        "description": "Populated for single_select / multi_select approval types."
      },
      "edited_content": {
        "type": "object",
        "description": "Populated when the approver edited plan steps or review content before approving."
      },
      "comment": {
        "type": "string"
      },
      "approver": {
        "type": "string"
      }
    }
  },
  "ports": [
    {
      "port_id": "accepted",
      "label": "Accepted",
      "is_default": true,
      "description": "Emitted when the approver confirms the action (Approve / Allow / Confirm / Submit edits)."
    },
    {
      "port_id": "rejected",
      "label": "Rejected",
      "description": "Emitted when the approver denies or cancels (Reject / Deny / Cancel)."
    },
    {
      "port_id": "timeout",
      "label": "Timeout",
      "description": "Emitted when the task expires without a decision (SLA breached)."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Emitted on technical failures during approval gate configuration."
    }
  ],
  "chain_constraints": {
    "prev": {
      "required_slug": "human.task.create",
      "message": "Human Approval Gate requires a preceding Create Task node to receive the task_id."
    }
  },
  "execution_mode": "sync",
  "tags": [
    "approval",
    "gate",
    "human",
    "hitl"
  ],
  "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",
  "required": [
    "approval_type",
    "title"
  ],
  "properties": {
    "approval_type": {
      "type": "object",
      "title": "Approval Type",
      "ui_widget": "hitl_approval_type_picker",
      "description": "Binary | Tool | Plan Review | Single-Select | Multi-Select | Review/Edit/Reject"
    },
    "title": {
      "type": "string",
      "title": "Title",
      "format": "expression",
      "description": "Shown to the approver when the task is claimed. Supports expressions like {{ $json.entity_name }}."
    },
    "description": {
      "type": "string",
      "title": "Description",
      "format": "expression",
      "description": "Context shown to the approver inside the task detail. Supports expressions and multi-line text."
    },
    "hitl_config": {
      "type": "object",
      "title": "Approval configuration",
      "ui_widget": "hitl_config",
      "ui_options": {
        "depends_on": "approval_type"
      },
      "description": "Subtype-specific fields (tool, plan, options, content, min_selection, etc.)"
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "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
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "task_id": {
      "type": "string",
      "description": "Propagated from preceding Create Task node"
    },
    "approval_type": {
      "type": "object"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "hitl_config": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "task_id": {
      "type": "string"
    },
    "approval_type": {
      "type": "object"
    },
    "decision": {
      "type": "string",
      "enum": [
        "approved",
        "rejected",
        "edited",
        "timeout"
      ],
      "description": "The actual human decision. Populated when suspend/resume is implemented; null in the current fire-and-forget mode."
    },
    "selected": {
      "type": "array",
      "description": "Populated for single_select / multi_select approval types."
    },
    "edited_content": {
      "type": "object",
      "description": "Populated when the approver edited plan steps or review content before approving."
    },
    "comment": {
      "type": "string"
    },
    "approver": {
      "type": "string"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "accepted",
    "label": "Accepted",
    "is_default": true,
    "description": "Emitted when the approver confirms the action (Approve / Allow / Confirm / Submit edits)."
  },
  {
    "port_id": "rejected",
    "label": "Rejected",
    "description": "Emitted when the approver denies or cancels (Reject / Deny / Cancel)."
  },
  {
    "port_id": "timeout",
    "label": "Timeout",
    "description": "Emitted when the task expires without a decision (SLA breached)."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Emitted on technical failures during approval gate configuration."
  }
]
```
