# Workflow Chain

> Invoca otro workflow y, opcionalmente, espera su resultado.

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

- Slug: `workflow.chain`
- Familia: Composición
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Invoca otro workflow y, opcionalmente, espera su resultado.

Este operador permite encadenar workflows de igual a igual. Dispara un workflow de destino y puede funcionar en modo síncrono (espera el resultado) o asíncrono (disparar y olvidar).

**Características:**
- **Modo síncrono:** Espera a que termine el workflow de destino y devuelve su resultado.
- **Modo asíncrono:** Dispara el workflow de destino y continúa de inmediato con el ID de la instancia.
- **Trazabilidad:** Un ID de correlación vincula ambas instancias de workflow para auditoría y depuración.
- **Reenvío del payload:** Define exactamente qué datos se pasan al workflow de destino.

**Casos de uso:**
- Componer procesos complejos a partir de módulos de workflow reutilizables.
- Delegar procesamiento especializado (p. ej., validación, enriquecimiento) en workflows dedicados.
- Patrones de fan-out en los que un workflow dispara varios workflows independientes.

## Configuración

- `target_flow_definition_id` (string, obligatorio): El workflow que se invoca cuando se ejecuta este nodo.
- `payload` (object, opcional): Datos que se envían al workflow de destino. Usa {{expressions}} para referenciar las salidas de nodos anteriores. Si está vacío, se reenvía la entrada del nodo actual ($json).

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): El workflow de destino terminó correctamente (síncrono) o fue despachado (asíncrono).
- `error`: El workflow de destino falló, agotó el tiempo o no se encontró.

## Contrato de entrada

- `target_flow_definition_id` (string, obligatorio)
- `payload` (object, opcional)

## Contrato de salida

- `instance_id` (string, opcional): El ID de la instancia de workflow creada.
- `status` (string, opcional): Estado final del workflow de destino (síncrono) o "running" (asíncrono).
- `result` (object, opcional): El resultado del workflow de destino (solo en modo síncrono).

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Workflow Chain").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Workflow Chain`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Workflow Chain").item.json.instance_id` (string) = `"<flow_instance_id>"`: El ID de la instancia de workflow creada.
- `$("Workflow Chain").item.json.status` (string) = `"completed"`: Estado final del workflow de destino (síncrono) o "running" (asíncrono).
- `$("Workflow Chain").item.json.result` (object) = `{…}`: El resultado del workflow de destino (solo en modo síncrono).
- `$("Workflow Chain").item.json.result.id` (string) = `"<flow_instance_result_id>"` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.flow_instance_id` (string) = `"<flow_instance_id>"` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.correlation_id` (string) = `"<correlation_id>"` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.status` (object) = `{…}` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.outcome_category` (string) = `"success"` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.duration_ms` (number) = `1840` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.error_summary` (null) = `null` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.final_output_envelope` (object) = `{…}` (El editor no la sugiere)
- `$("Workflow Chain").item.json.result.metrics` (object) = `{…}` (El editor no la sugiere)
- `$("Workflow Chain").item.json.steps` (null) = `null` (El editor no la sugiere)
- `$("Workflow Chain").item.json.correlation_id` (string) = `"chain-8f3k2m9q1x7v4b6n0z5c"` (El editor no la sugiere)


## Cómo funciona

Inicia otro flujo de la misma organización por su id de definición, con un payload y un contexto de encadenamiento, y espera su resultado final (`sync`) o continúa en cuanto se despacha (`async`).

1. Resuelve la configuración. Falla por `error` cuando `target_flow_definition_id` está vacío. El payload que se envía es el `payload` configurado o, si no está definido, la entrada del nodo (`$json`).
2. Obtiene la organización de la ejecución (`$organization_id` o, si no, `organization_id` de la entrada de la ejecución o del nodo) y el entorno del hijo: `prod` cuando el padre ejecuta una versión publicada y `test` en otro caso.
3. Construye el contexto de encadenamiento: id de definición, id de instancia, slug e id de nodo del llamador, un `correlation_id` nuevo (`chain-…`) y el `root_flow_instance_result_id` de toda la cadena, heredado sin cambios del padre cuando este también fue encadenado.
4. Pide al backend que ejecute el destino. En `prod`, el backend usa la versión publicada predeterminada del destino (o la más reciente); el hijo recibe `$input` = `{ data: <payload>, chain_context }`.
5. `sync`: consume una respuesta en streaming que retransmite el progreso de cada nodo del hijo a la línea de tiempo del padre y termina con el resultado final. `async`: regresa en cuanto se despacha el hijo.
6. Una respuesta 2xx sale por `out` con `{ instance_id, status, result, steps: null, correlation_id }`; cualquier otra, por `error`.

## En un workflow

### Nodo

```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"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

El backend aceptó la cadena. En `sync`, `status` es el nombre del estado final del hijo y `result` un resultado de ejecución reducido (su propio `status` es un objeto de estado) cuyo `final_output_envelope.payload` contiene la última salida del hijo; este puerto también se emite cuando el hijo terminó `failed`, así que revisa `status`. En `async`, `status` es `running` y `result` es `null`. `steps` siempre es `null`; `meta` incluye `target_flow_definition_id`, `mode` y `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`

El backend rechazó la cadena (los datos son `{ status, message, correlation_id }`), la llamada falló (`{ error, response }`) o se agotó el tiempo (`{ error: "TIMEOUT", message }`). Si falta el destino, la URL del backend o la organización, el sobre no tiene `data`, así que el nodo siguiente recibe `{ ok: false, errors: [...], port: "error" }`.

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

## Comportamiento en el código

- `target_flow_definition_id`: La única forma de elegir el destino: un id de definición de flujo de la misma organización. El worker no resuelve destinos por slug.
- `payload`: Se resuelve como objeto con plantillas y se envía como `$input.data` del hijo. Si el nodo no tiene `payload`, se envía la entrada del nodo tal cual.
- `execution.timeout_ms`: Por defecto 30000 ms en el código (el esquema muestra 300000, que el código no aplica). En `sync` con streaming es un límite de inactividad que se reinicia con cada evento y señal de actividad, así que un hijo largo no agota el tiempo mientras el backend mantenga vivo el stream. Se ignora en `async`, que usa 10 s.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing target_flow_definition_id` | `error` | No hay flujo de destino seleccionado. |
| `Cannot resolve organization_id from execution state` | `error` | La ejecución no tiene organización ni en su estado, ni en su entrada, ni en la entrada del nodo. Incluye `organization_id` en la entrada al iniciar la ejecución. |
| `No published version found for the target workflow` | `error` | El padre ejecuta una versión publicada (`prod`), pero el destino no tiene ninguna. Publica primero el flujo de destino. |
| `Workflow chain timed out waiting for target workflow` | `error` | En `async`, el despacho tardó más de 10 s; en la ruta `sync` sin streaming, el hijo tardó más que `execution.timeout_ms`. |
| `Workflow execution failed: <detail>` | `error` | El backend no pudo ejecutar el hijo (por ejemplo, el grafo del destino no tiene nodos). |

## Notas y límites

- Si el stream `sync` falla (un evento `error`, un cierre sin resultado o el límite de inactividad), el worker reenvía la petición al endpoint sin streaming, lo que puede iniciar el hijo una segunda vez. Diseña los flujos encadenados para que se puedan repetir sin riesgo.
- Correlación: `correlation_id` vincula padre e hijo; `root_flow_instance_result_id` se propaga sin cambios por todos los niveles, de modo que el hijo más profundo puede informar el id de la ejecución de entrada.
- La lista completa de pasos del hijo nunca se copia en el padre: lee las salidas en `result.final_output_envelope.payload` y abre la ejecución del hijo por `instance_id` para ver el detalle.
- Si el destino está en pausa para ese entorno, el backend responde con su respuesta de pausa en lugar de ejecutarlo.


## Contratos (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
  }
]
```
