# Workflow Chain

> 调用另一个工作流，并可选择等待其结果。

Source: https://docs.sommatic.ai/zh/nodes/workflow.chain/

- 标识: `workflow.chain`
- 类别: 编排
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

调用另一个工作流，并可选择等待其结果。

该算子支持对等的工作流链式调用。它会触发目标工作流，可以同步（等待结果）或异步（发出即不管）方式运行。

**功能特性：**
- **同步模式：** 等待目标工作流完成并返回其结果。
- **异步模式：** 触发目标工作流后立即携带实例 ID 继续执行。
- **可追溯性：** 关联 ID 将两个工作流实例关联起来，便于审计和调试。
- **载荷转发：** 精确定义要传给目标工作流的数据。

**适用场景：**
- 用可复用的工作流模块组合复杂流程。
- 将专项处理（例如校验、数据增强）委派给专用工作流。
- 扇出模式：一个工作流触发多个相互独立的工作流。

## 配置

- `target_flow_definition_id` (string, 必填): 本节点执行时要调用的工作流。
- `payload` (object, 可选): 发送给目标工作流的数据。使用 {{expressions}} 引用上游节点输出。留空则转发当前节点的输入（$json）。

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

## 输出端口

- `out` (默认): 目标工作流已成功完成（同步）或已派发（异步）。
- `error`: 目标工作流失败、超时或未找到。

## 输入契约

- `target_flow_definition_id` (string, 必填)
- `payload` (object, 可选)

## 输出契约

- `instance_id` (string, 可选): 所创建工作流实例的 ID。
- `status` (string, 可选): 目标工作流的最终状态（同步）或“running”（异步）。
- `result` (object, 可选): 目标工作流的结果（仅同步模式）。

## 在表达式中

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

- `$("Workflow Chain").item.json.instance_id` (string) = `"<flow_instance_id>"`: 所创建工作流实例的 ID。
- `$("Workflow Chain").item.json.status` (string) = `"completed"`: 目标工作流的最终状态（同步）或“running”（异步）。
- `$("Workflow Chain").item.json.result` (object) = `{…}`: 目标工作流的结果（仅同步模式）。
- `$("Workflow Chain").item.json.result.id` (string) = `"<flow_instance_result_id>"` (编辑器不提示)
- `$("Workflow Chain").item.json.result.flow_instance_id` (string) = `"<flow_instance_id>"` (编辑器不提示)
- `$("Workflow Chain").item.json.result.correlation_id` (string) = `"<correlation_id>"` (编辑器不提示)
- `$("Workflow Chain").item.json.result.status` (object) = `{…}` (编辑器不提示)
- `$("Workflow Chain").item.json.result.outcome_category` (string) = `"success"` (编辑器不提示)
- `$("Workflow Chain").item.json.result.duration_ms` (number) = `1840` (编辑器不提示)
- `$("Workflow Chain").item.json.result.error_summary` (null) = `null` (编辑器不提示)
- `$("Workflow Chain").item.json.result.final_output_envelope` (object) = `{…}` (编辑器不提示)
- `$("Workflow Chain").item.json.result.metrics` (object) = `{…}` (编辑器不提示)
- `$("Workflow Chain").item.json.steps` (null) = `null` (编辑器不提示)
- `$("Workflow Chain").item.json.correlation_id` (string) = `"chain-8f3k2m9q1x7v4b6n0z5c"` (编辑器不提示)


## 工作原理

按定义 id 启动同一组织中的另一个工作流，传入 payload 和链路上下文，然后等待其最终结果（`sync`），或在派发后立即继续（`async`）。

1. 解析配置。`target_flow_definition_id` 为空时从 `error` 失败输出。发送的 payload 为配置的 `payload`；未设置时为节点输入（`$json`）。
2. 从当前运行中获取组织（`$organization_id`，否则取运行输入或节点输入中的 `organization_id`），并确定子工作流的环境：父工作流运行已发布版本时为 `prod`，否则为 `test`。
3. 构建链路上下文：调用方的定义 id、实例 id、slug 和节点 id，新的 `correlation_id`（`chain-…`），以及整条链路的 `root_flow_instance_result_id`（若父工作流本身也是被链式调用的，则原样继承）。
4. 请求后端运行目标工作流。`prod` 环境下，后端使用目标的默认已发布版本（否则使用最新版本）；子工作流收到的 `$input` 为 `{ data: <payload>, chain_context }`。
5. `sync`：读取流式响应，将子工作流各节点的进度转发到父工作流时间线，并以最终结果结束。`async`：子工作流派发后即返回。
6. 2xx 响应以 `{ instance_id, status, result, steps: null, correlation_id }` 从 `out` 输出；其他情况从 `error` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-score-applicant",
  "label": "Score applicant",
  "operator_slug": "workflow.chain",
  "operator_version": "1.0.0",
  "config": {
    "target_flow_definition_id": "<flow_definition_id>",
    "payload": {
      "applicant_id": "{{ $json.applicant_id }}",
      "amount": "{{ $json.amount }}"
    },
    "execution": {
      "mode": "sync",
      "timeout_ms": 30000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "instance_id": "<flow_instance_id>",
    "status": "completed",
    "result": {
      "id": "<flow_instance_result_id>",
      "flow_instance_id": "<flow_instance_id>",
      "correlation_id": "<correlation_id>",
      "status": {
        "id": 5,
        "name": "completed",
        "title": "Completed",
        "color": "#2e7d32"
      },
      "outcome_category": "success",
      "duration_ms": 1840,
      "error_summary": null,
      "final_output_envelope": {
        "node_id": "node-score",
        "port": "out",
        "payload": {
          "score": 0.92,
          "approved": true
        }
      },
      "metrics": {}
    },
    "steps": null,
    "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
  },
  "meta": {
    "target_flow_definition_id": "<flow_definition_id>",
    "mode": "sync",
    "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
  },
  "port": "out"
}
```

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

### `out`

后端已接受链式调用。`sync` 模式下，`status` 为子工作流最终状态的名称，`result` 为精简后的运行结果（其自身的 `status` 为状态对象），其 `final_output_envelope.payload` 包含子工作流的最后输出；子工作流以 `failed` 结束时此端口同样会触发，请检查 `status`。`async` 模式下，`status` 为 `running`，`result` 为 `null`。`steps` 始终为 `null`；`meta` 包含 `target_flow_definition_id`、`mode` 和 `correlation_id`。

```json
{
  "instance_id": "<flow_instance_id>",
  "status": "completed",
  "result": {
    "id": "<flow_instance_result_id>",
    "flow_instance_id": "<flow_instance_id>",
    "correlation_id": "<correlation_id>",
    "status": {
      "id": 5,
      "name": "completed",
      "title": "Completed",
      "color": "#2e7d32"
    },
    "outcome_category": "success",
    "duration_ms": 1840,
    "error_summary": null,
    "final_output_envelope": {
      "node_id": "node-score",
      "port": "out",
      "payload": {
        "score": 0.92,
        "approved": true
      }
    },
    "metrics": {}
  },
  "steps": null,
  "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
}
```

### `error`

后端拒绝了链式调用（数据为 `{ status, message, correlation_id }`）、调用失败（`{ error, response }`）或超时（`{ error: "TIMEOUT", message }`）。缺少目标、后端 URL 或组织时信封中没有 `data`，因此下一个节点收到 `{ ok: false, errors: [...], port: "error" }`。

```json
{
  "status": 500,
  "message": "No published version found for the target workflow",
  "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
}
```

## 代码中的行为

- `target_flow_definition_id`: 选择目标的唯一方式：同一组织内的工作流定义 id。worker 不支持按 slug 解析目标。
- `payload`: 作为模板对象解析，并作为子工作流的 `$input.data` 发送。节点未设置 `payload` 时，按原样发送节点输入。
- `execution.timeout_ms`: 代码中默认为 30000 毫秒（schema 显示的 300000 不会被代码采用）。在 `sync` 流式模式下，它是空闲超时，每收到一个事件或保活信号就会重置，因此只要后端保持流活跃，长时间运行的子工作流不会超时。`async` 模式忽略此值，固定使用 10 秒。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing target_flow_definition_id` | `error` | 未选择目标工作流。 |
| `Cannot resolve organization_id from execution state` | `error` | 运行状态、运行输入和节点输入中都没有组织信息。启动运行时请在输入中加入 `organization_id`。 |
| `No published version found for the target workflow` | `error` | 父工作流运行的是已发布版本（`prod`），但目标工作流没有已发布版本。请先发布目标工作流。 |
| `Workflow chain timed out waiting for target workflow` | `error` | `async` 模式下派发超过 10 秒；在非流式的 `sync` 路径中，子工作流运行时间超过 `execution.timeout_ms`。 |
| `Workflow execution failed: <detail>` | `error` | 后端无法运行子工作流（例如目标工作流图中没有节点）。 |

## 说明与限制

- 若 `sync` 流失败（收到 `error` 事件、未返回结果即关闭，或达到空闲超时），worker 会将请求重新发送到非流式端点，这可能导致子工作流再次启动。请将链式工作流设计为可安全重复执行。
- 关联：`correlation_id` 关联父子工作流；`root_flow_instance_result_id` 会原样传递到每一层，因此最深层的子工作流也能报告入口运行的 id。
- 子工作流的完整步骤列表不会复制到父工作流：请从 `result.final_output_envelope.payload` 读取输出，并通过 `instance_id` 打开子运行查看详情。
- 若目标工作流在该环境下处于暂停状态，后端会返回暂停响应，而不会运行它。


## 契约（JSON Schema）

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

```json
{
  "slug": "workflow.chain",
  "name": "Workflow Chain",
  "category": "workflow",
  "version": "1.0.0",
  "description": "Invokes another workflow and optionally waits for its result.\n\n  This operator enables peer-to-peer workflow chaining. It triggers a target workflow and can operate in synchronous (wait for result) or asynchronous (fire-and-forget) mode.\n\n  **Features:**\n  - **Sync Mode:** Waits for the target workflow to complete and returns its result.\n  - **Async Mode:** Fires the target workflow and continues immediately with the instance ID.\n  - **Traceability:** Correlation ID links both workflow instances for audit and debugging.\n  - **Payload Forwarding:** Define exactly what data to pass to the target workflow.\n\n  **Use Cases:**\n  - Composing complex processes from reusable workflow modules.\n  - Delegating specialized processing (e.g., validation, enrichment) to dedicated workflows.\n  - Fan-out patterns where one workflow triggers multiple independent workflows.",
  "capabilities": [
    "workflow",
    "chain",
    "composition",
    "orchestration"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "target_flow_definition_id": {
        "type": "string",
        "title": "Target Workflow",
        "description": "The workflow to invoke when this node executes.",
        "x-ui-widget": "flow-definition-picker"
      },
      "payload": {
        "type": "object",
        "title": "Payload",
        "description": "Data to send to the target workflow. Use {{expressions}} to reference upstream node outputs. If empty, the current node input ($json) is forwarded."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "mode": {
            "type": "string",
            "enum": [
              "sync",
              "async"
            ],
            "default": "sync",
            "title": "Execution Mode",
            "description": "Sync: wait for the target workflow to complete and return its result. Async: dispatch and continue without waiting."
          },
          "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
          },
          "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
          }
        }
      }
    },
    "required": [
      "target_flow_definition_id"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "target_flow_definition_id": {
        "type": "string"
      },
      "payload": {
        "type": "object"
      }
    },
    "required": [
      "target_flow_definition_id"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "instance_id": {
        "type": "string",
        "description": "The ID of the created workflow instance."
      },
      "status": {
        "type": "string",
        "description": "Final status of the target workflow (sync) or \"running\" (async)."
      },
      "result": {
        "type": "object",
        "description": "The target workflow result (sync mode only)."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Completed",
      "description": "Target workflow completed successfully (sync) or dispatched (async).",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Target workflow failed, timed out, or could not be found.",
      "is_default": false,
      "supports_condition": true
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io"
  ],
  "tags": [
    "workflow",
    "chain",
    "composition",
    "orchestration"
  ],
  "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": {
    "target_flow_definition_id": {
      "type": "string",
      "title": "Target Workflow",
      "description": "The workflow to invoke when this node executes.",
      "x-ui-widget": "flow-definition-picker"
    },
    "payload": {
      "type": "object",
      "title": "Payload",
      "description": "Data to send to the target workflow. Use {{expressions}} to reference upstream node outputs. If empty, the current node input ($json) is forwarded."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "mode": {
          "type": "string",
          "enum": [
            "sync",
            "async"
          ],
          "default": "sync",
          "title": "Execution Mode",
          "description": "Sync: wait for the target workflow to complete and return its result. Async: dispatch and continue without waiting."
        },
        "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
        },
        "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
        }
      }
    }
  },
  "required": [
    "target_flow_definition_id"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "target_flow_definition_id": {
      "type": "string"
    },
    "payload": {
      "type": "object"
    }
  },
  "required": [
    "target_flow_definition_id"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "instance_id": {
      "type": "string",
      "description": "The ID of the created workflow instance."
    },
    "status": {
      "type": "string",
      "description": "Final status of the target workflow (sync) or \"running\" (async)."
    },
    "result": {
      "type": "object",
      "description": "The target workflow result (sync mode only)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Completed",
    "description": "Target workflow completed successfully (sync) or dispatched (async).",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Target workflow failed, timed out, or could not be found.",
    "is_default": false,
    "supports_condition": true
  }
]
```
