# Workflow Chain Receiver

> Recibe solicitudes de ejecución desde el nodo Chain de otro workflow.

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

- Slug: `workflow.trigger`
- Familia: Triggers
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Recibe solicitudes de ejecución desde el nodo Chain de otro workflow.

Este trigger es el punto de entrada de un workflow que otro workflow invoca mediante el nodo `workflow.chain`. Permite encadenar workflows de igual a igual sin crear una jerarquía padre-hijo.

**Características:**
- **Filtro de invocadores:** Opcionalmente, restringe qué workflows pueden encadenarse con este.
- **Paso directo del payload:** El payload del workflow invocador está disponible como `$json` en los nodos posteriores.
- **Trazabilidad:** El contexto de la cadena (instancia invocadora, nodo, ID de correlación) se conserva para auditoría.

**Casos de uso:**
- Composición modular de workflows (p. ej., un workflow de validación compartido al que invocan varios workflows).
- Encadenamiento basado en eventos, en el que el workflow A termina una fase y delega en el workflow B.
- Subprocesos reutilizables que se pueden probar y desplegar de forma independiente.

## Configuración

- `accepted_caller_ids` (array<string>, opcional): Elige qué workflows pueden invocar a este. Déjalo vacío para aceptar llamadas de cualquier workflow. Por defecto: `[]`.

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): Payload de la cadena recibido y validado.
- `error`: Invocador no autorizado o validación fallida.

## Contrato de salida

- `data` (object, opcional): Los datos de entrada de la cadena.
- `chain_context` (object, opcional): Metadatos de trazabilidad del invocador.
  - `caller_flow_definition_id` (string, opcional)
  - `caller_flow_instance_id` (string, opcional)
  - `caller_flow_slug` (string, opcional)
  - `caller_node_id` (string, opcional)
  - `correlation_id` (string, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Workflow Chain Receiver").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Workflow Chain Receiver`). **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 Receiver").item.json.data` (object): Los datos de entrada de la cadena. **El worker no la devuelve: se lee como undefined.**
- `$("Workflow Chain Receiver").item.json.chain_context` (object) = `{…}`: Metadatos de trazabilidad del invocador.
- `$("Workflow Chain Receiver").item.json.chain_context.caller_flow_definition_id` (string) = `"<flow_definition_id>"`
- `$("Workflow Chain Receiver").item.json.chain_context.caller_flow_instance_id` (string) = `"<flow_instance_id>"`
- `$("Workflow Chain Receiver").item.json.chain_context.caller_flow_slug` (string) = `"order-intake"`
- `$("Workflow Chain Receiver").item.json.chain_context.caller_node_id` (string) = `"node-call-billing"`
- `$("Workflow Chain Receiver").item.json.chain_context.correlation_id` (string) = `"chain-8f2k1m9x0q4w7e3r5t6y"`
- `$("Workflow Chain Receiver").item.json.order_id` (string) = `"ord_123"` (El editor no la sugiere)
- `$("Workflow Chain Receiver").item.json.customer_email` (string) = `"ana@example.com"` (El editor no la sugiere)
- `$("Workflow Chain Receiver").item.json.chain_context.root_flow_instance_result_id` (string) = `"<flow_instance_result_id>"` (El editor no la sugiere)


## Cómo funciona

Nodo de entrada para subworkflows llamados por `workflow.chain`. Opcionalmente restringe qué workflows pueden llamarlo y luego entrega los datos enviados por quien llama junto con `chain_context`.

1. Qué lo inicia: un nodo `workflow.chain` de otro workflow. El backend ejecuta el borrador cuando quien llama es a su vez una ejecución de borrador (`test`) y la versión publicada predeterminada cuando quien llama ejecuta una versión publicada (`prod`); `prod` falla si este workflow no tiene versión publicada. La entrada de la ejecución es `{ data, chain_context }`.
2. Resuelve la configuración del nodo. Si `accepted_caller_ids` no está vacío y `chain_context.caller_flow_definition_id` no está en la lista, devuelve `error`.
3. En otro caso expande `data` en la raíz, agrega `chain_context` y devuelve `meta` con el id de definición, el slug y el id de instancia de quien llama, y el id de correlación de la cadena.

## En un workflow

### Nodo

```json
{
  "node_id": "node-from-parent",
  "label": "Called by order intake",
  "operator_slug": "workflow.trigger",
  "operator_version": "1.0.0",
  "config": {
    "accepted_caller_ids": [
      "<flow_definition_id>"
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "customer_email": "ana@example.com",
    "chain_context": {
      "caller_flow_definition_id": "<flow_definition_id>",
      "caller_flow_instance_id": "<flow_instance_id>",
      "caller_flow_slug": "order-intake",
      "caller_node_id": "node-call-billing",
      "correlation_id": "chain-8f2k1m9x0q4w7e3r5t6y",
      "root_flow_instance_result_id": "<flow_instance_result_id>"
    }
  },
  "port": "out",
  "meta": {
    "caller_flow_definition_id": "<flow_definition_id>",
    "caller_flow_slug": "order-intake",
    "caller_flow_instance_id": "<flow_instance_id>",
    "correlation_id": "chain-8f2k1m9x0q4w7e3r5t6y"
  }
}
```

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

### `out`

Quien llama es aceptado.

```json
{
  "order_id": "ord_123",
  "customer_email": "ana@example.com",
  "chain_context": {
    "caller_flow_definition_id": "<flow_definition_id>",
    "caller_flow_instance_id": "<flow_instance_id>",
    "caller_flow_slug": "order-intake",
    "caller_node_id": "node-call-billing",
    "correlation_id": "chain-8f2k1m9x0q4w7e3r5t6y",
    "root_flow_instance_result_id": "<flow_instance_result_id>"
  }
}
```

### `error`

Quien llama no está en `accepted_caller_ids`. La salida es el sobre `{ ok, errors, port, meta: { rejected_caller_id, rejected_caller_slug } }`.

```json
{
  "ok": false,
  "errors": [
    "Caller workflow 'order-intake' is not in the accepted callers list"
  ],
  "port": "error",
  "meta": {
    "rejected_caller_id": "<flow_definition_id>",
    "rejected_caller_slug": "order-intake"
  }
}
```

## Comportamiento en el código

- `accepted_caller_ids`: Se compara con `chain_context.caller_flow_definition_id` (ids de definición de workflow, no slugs). Vacío acepta a cualquier llamador.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Caller workflow '<caller_flow_slug or caller_flow_definition_id>' is not in the accepted callers list` | `error` | Agrega el id de definición del workflow que llama a `accepted_caller_ids`, o deja la lista vacía para aceptar a cualquiera. Una ejecución iniciada sin `chain_context` (por ejemplo, a mano) también se rechaza si la lista no está vacía. |

## Notas y límites

- Las claves de los datos de quien llama se expanden en la raíz, así que léelas más adelante como `$json.<field>`; una clave `data.chain_context` sería reemplazada por el `chain_context` real.
- `chain_context.root_flow_instance_result_id` se mantiene igual en todos los saltos de una cadena, así que cualquier subworkflow puede informar el id de la ejecución principal.
- Con datos de muestra el motor omite el nodo y entrega la entrada de muestra sin cambios por `out` (sin expandir `data`).


## Contratos (JSON Schema)

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

```json
{
  "slug": "workflow.trigger",
  "name": "Workflow Chain Receiver",
  "category": "triggers",
  "version": "1.0.0",
  "description": "Receives execution requests from another workflow's Chain node.\n\n  This trigger acts as the entry point for a workflow that is invoked by another workflow via the `workflow.chain` node. It enables peer-to-peer workflow chaining without creating a parent-child hierarchy.\n\n  **Features:**\n  - **Caller Filtering:** Optionally restrict which workflows can chain into this one.\n  - **Payload Passthrough:** The calling workflow's payload is available as `$json` in downstream nodes.\n  - **Traceability:** Chain context (caller instance, node, correlation ID) is preserved for audit.\n\n  **Use Cases:**\n  - Modular workflow composition (e.g., shared validation workflow invoked by multiple callers).\n  - Event-driven chaining where Workflow A completes a phase and delegates to Workflow B.\n  - Reusable sub-processes that remain independently testable and deployable.",
  "capabilities": [
    "workflow",
    "chain",
    "composition",
    "trigger"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "accepted_caller_ids": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "title": "Accepted Callers",
        "description": "Select which workflows are allowed to invoke this one. Leave empty to accept calls from any workflow.",
        "default": [],
        "x-ui-widget": "flow-definition-multi-picker"
      },
      "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": null,
  "output_contract_schema": {
    "type": "object",
    "description": "The payload sent by the calling workflow.",
    "properties": {
      "data": {
        "type": "object",
        "description": "The chain input data."
      },
      "chain_context": {
        "type": "object",
        "description": "Traceability metadata from the caller.",
        "properties": {
          "caller_flow_definition_id": {
            "type": "string"
          },
          "caller_flow_instance_id": {
            "type": "string"
          },
          "caller_flow_slug": {
            "type": "string"
          },
          "caller_node_id": {
            "type": "string"
          },
          "correlation_id": {
            "type": "string"
          }
        }
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Received",
      "is_default": true,
      "description": "Chain payload received and validated."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Caller not authorized or validation failed."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "workflow",
    "chain",
    "trigger",
    "composition"
  ],
  "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": {
    "accepted_caller_ids": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "title": "Accepted Callers",
      "description": "Select which workflows are allowed to invoke this one. Leave empty to accept calls from any workflow.",
      "default": [],
      "x-ui-widget": "flow-definition-multi-picker"
    },
    "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
        }
      }
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The payload sent by the calling workflow.",
  "properties": {
    "data": {
      "type": "object",
      "description": "The chain input data."
    },
    "chain_context": {
      "type": "object",
      "description": "Traceability metadata from the caller.",
      "properties": {
        "caller_flow_definition_id": {
          "type": "string"
        },
        "caller_flow_instance_id": {
          "type": "string"
        },
        "caller_flow_slug": {
          "type": "string"
        },
        "caller_node_id": {
          "type": "string"
        },
        "correlation_id": {
          "type": "string"
        }
      }
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Received",
    "is_default": true,
    "description": "Chain payload received and validated."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Caller not authorized or validation failed."
  }
]
```
