# Wait / Delay

> Pausa el flujo de ejecución durante un tiempo determinado o hasta una fecha y hora concretas.

Source: https://docs.sommatic.ai/es/nodes/flow.wait/

- Slug: `flow.wait`
- Familia: Control de flujo
- Versión: 1.0.0
- Estado: Parcial. El modo `duration` sí pausa la ejecución, con un máximo de 10 segundos; el modo `timestamp` no espera y sigue de inmediato por `out`.
- Ejecución: async

Pausa el flujo de ejecución durante un tiempo determinado o hasta una fecha y hora concretas.

Este operador sirve para introducir retrasos o programar la ejecución en un momento futuro. Depende del motor de orquestación para suspender el workflow y reanudarlo a la hora de reactivación calculada.

**Modos:**
- **Duración:** Espera un tiempo relativo (p. ej., "5 minutos").
- **Marca de tiempo:** Espera hasta una fecha y hora absolutas (p. ej., "2025-12-31T23:59:59Z").

**Casos de uso:**
- Enviar un correo de seguimiento 24 horas después del registro.
- Esperar el intervalo de reintento de una conexión.
- Pausar un workflow hasta una fecha hábil concreta.

## Configuración

- `type` (string, opcional): Por defecto: `duration`. Valores permitidos: `duration`, `timestamp`.
- `duration_seconds` (integer, opcional): Número de segundos de espera (se usa cuando Type es "duration"). Por defecto: `60`.
- `timestamp_expr` (string, opcional, acepta expresiones): Marca de tiempo ISO-8601 o expresión que se evalúe como una (se usa cuando Type es "timestamp").

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): La ejecución se reanuda aquí tras la espera.
- `error`: Se activa si la marca de tiempo no es válida.

## Contrato de entrada

- `payload` (object, opcional)

## Contrato de salida

- `payload` (object, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Wait / Delay").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Wait / Delay`). **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.

- `$("Wait / Delay").item.json.payload` (object) **El worker no la devuelve: se lee como undefined.**
- `$("Wait / Delay").item.json.ticket_id` (string) = `"tk_9"` (El editor no la sugiere)
- `$("Wait / Delay").item.json.due_at` (string) = `"2026-12-01T09:00:00Z"` (El editor no la sugiere)


## Cómo funciona

Experimental. En modo `duration` duerme de verdad, con un tope de 10 segundos, y luego continúa; en modo `timestamp` solo calcula la hora de reanudación y continúa de inmediato. El flujo nunca se suspende.

1. Resuelve la configuración; `type` vale `duration` por defecto. Si falta `duration_seconds`, el código usa 0, no el 60 del esquema.
2. `duration`: fija `resume_at` en ahora más `duration_seconds` y duerme `min(duration, 10 s)` dentro del worker.
3. `timestamp`: si el `timestamp_expr` original contiene `{{`, usa el valor resuelto; si no, lo evalúa como JSONata sobre el payload (`due_at`). Lo interpreta con `new Date()` y calcula `delay_ms`. No duerme.
4. Devuelve el payload sin cambios por `out` con `meta` `{ action: "suspend", resume_at, delay_ms }`. El motor ignora `meta.action` y ejecuta el siguiente nodo de inmediato.

## En un workflow

### Nodo

```json
{
  "node_id": "node-wait-due",
  "label": "Wait until due",
  "operator_slug": "flow.wait",
  "operator_version": "1.0.0",
  "config": {
    "type": "timestamp",
    "timestamp_expr": "{{ $json.due_at }}"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "ticket_id": "tk_9",
    "due_at": "2026-12-01T09:00:00Z"
  },
  "port": "out",
  "meta": {
    "action": "suspend",
    "resume_at": "2026-12-01T09:00:00.000Z",
    "delay_ms": 410400000
  }
}
```

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

### `out`

Tras la espera con tope (`duration`) o de inmediato (`timestamp`).

```json
{
  "ticket_id": "tk_9",
  "due_at": "2026-12-01T09:00:00Z"
}
```

### `error`

Solo cuando el worker lanza un error inesperado; una marca de tiempo no válida sale por `out` (ver errores).

```json
{
  "error": "<message>"
}
```

## Comportamiento en el código

- `timestamp_expr`: Usa `{{ $json.due_at }}`, una ruta JSONata como `due_at` o un literal entre comillas `"2026-12-01T09:00:00Z"`. Sin `timestamp_expr`, el modo `timestamp` devuelve `resume_at: null` y `delay_ms: 0`.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Wait timestamp error: <message>` | `out` | `timestamp_expr` no es una fecha válida, o es una cadena ISO sin `{{ }}` ni comillas (JSONata no puede interpretar `2026-12-01T09:00:00Z`). El sobre no tiene puerto, así que el motor lo envía a `out` y el siguiente nodo recibe `{ ok: false, errors: [...] }` como payload. |

## Notas y límites

- No hay temporizador persistente: una espera de más de 10 segundos se recorta a 10 segundos, y el nodo retiene la ejecución mientras duerme.
- `meta` solo queda en los pasos de la ejecución: los nodos siguientes reciben `data` como payload y no pueden leer `meta` con `$json` ni con `$("Node")`.


## Contratos (JSON Schema)

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

```json
{
  "slug": "flow.wait",
  "name": "Wait / Delay",
  "category": "flow",
  "version": "1.0.0",
  "description": "Pauses the execution flow for a specified duration or until a specific timestamp.\n\n  This operator is used to introduce delays or schedule execution for a future time. It relies on the orchestration engine to suspend the workflow and resume it at the calculated wake-up time.\n\n  **Modes:**\n  - **Duration:** Waits for a relative amount of time (e.g., \"5 minutes\").\n  - **Timestamp:** Waits until a specific absolute date/time (e.g., \"2025-12-31T23:59:59Z\").\n\n  **Use Cases:**\n  - Sending a follow-up email 24 hours after sign-up.\n  - Waiting for a connection retry backoff.\n  - Pausing a workflow until a specific business date.",
  "capabilities": [
    "delay",
    "schedule",
    "time",
    "suspend"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "duration",
          "timestamp"
        ],
        "default": "duration",
        "title": "Wait Type"
      },
      "duration_seconds": {
        "type": "integer",
        "title": "Duration (Seconds)",
        "default": 60,
        "description": "Number of seconds to wait (used when Type is \"duration\")."
      },
      "timestamp_expr": {
        "type": "string",
        "title": "Until (Timestamp)",
        "format": "expression",
        "description": "ISO-8601 Timestamp or expression evaluating to one (used when Type is \"timestamp\")."
      },
      "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",
    "description": "Payload passed into the wait state.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Payload passed out after resumption (usually unchanged).",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Resume",
      "is_default": true,
      "description": "Execution resumes here after the delay."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Activated if the timestamp is invalid."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "time",
    "sleep",
    "control-flow",
    "schedule"
  ],
  "is_stateful": true,
  "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": {
    "type": {
      "type": "string",
      "enum": [
        "duration",
        "timestamp"
      ],
      "default": "duration",
      "title": "Wait Type"
    },
    "duration_seconds": {
      "type": "integer",
      "title": "Duration (Seconds)",
      "default": 60,
      "description": "Number of seconds to wait (used when Type is \"duration\")."
    },
    "timestamp_expr": {
      "type": "string",
      "title": "Until (Timestamp)",
      "format": "expression",
      "description": "ISO-8601 Timestamp or expression evaluating to one (used when Type is \"timestamp\")."
    },
    "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",
  "description": "Payload passed into the wait state.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Payload passed out after resumption (usually unchanged).",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Resume",
    "is_default": true,
    "description": "Execution resumes here after the delay."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Activated if the timestamp is invalid."
  }
]
```
