# Triage Classifier

> Realiza un triaje jerárquico de recepción con reglas de decisión basadas en políticas.

Source: https://docs.sommatic.ai/es/nodes/ai.classify.triage/

- Slug: `ai.classify.triage`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Realiza un triaje jerárquico de recepción con reglas de decisión basadas en políticas.

Este operador clasifica el texto en una taxonomía de **categoría + subcategoría**, produce un nivel de **confianza** y una **distribución de probabilidad** completa entre categorías, genera **indicaciones de enrutamiento** y devuelve tanto **notas** como una **justificación** más extensa, apta para auditorías y revisión humana.

**Casos de uso típicos**
- Triaje de recepción gubernamental o jurídica (PQRS, tutela, hábeas corpus, etc.)
- Enrutamiento de incidentes empresariales con reglas de política
- Clasificación en taxonomías de varios niveles con una justificación trazable

## Configuración

- `knowledge_resource_id` (string, obligatorio): Recurso de conocimiento (tipo: taxonomy) que contiene las categorías y subcategorías del triaje.
- `general_considerations` (array<string>, opcional): Reglas generales que siempre deben tenerse en cuenta durante el triaje. Por defecto: `[]`.
- `decision_rules` (array<string>, opcional): Reglas explícitas de decisión y enrutamiento (especificidad, precedencia, excepciones). Por defecto: `[]`.
- `routing_hints_catalog` (array<string>, opcional): Indicaciones de enrutamiento permitidas que el modelo puede sugerir (opcional). Por defecto: `[]`.
- `confidence_threshold` (number, opcional): Si la confianza queda por debajo de este umbral, la salida se marca como needs_review. Por defecto: `0.7`.
- `language` (string, opcional): Idioma de las notas, de la justificación y de la interpretación. Ejemplo: "es", "en". Por defecto: `es`.
- `llm_provider_id` (string, opcional): El `id` de un registro `LlmProviderModel` (p. ej. `wf-llm-provider-*`). El orquestador delega en el backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` en modo sync, o `POST /chat/conversation/execute/stream-ephemeral` (SSE) en modo stream. El backend resuelve endpoint + api-key + deployment a partir del registro y enruta al adaptador correspondiente (Azure OpenAI, Azure Foundry, OpenAI, AWS Bedrock, Google Vertex, Link Loom Cloud, Generic). Se gestiona en la webapp en `/cognitive-assets/llm-provider/*`.
- `invocation_mode` (string, opcional): Transporte de la llamada al LLM. `sync` abre una solicitud HTTP corta y se bloquea hasta recibir la respuesta completa (ideal para inferencias rápidas: clasificación, generación breve). `stream` consume los tokens mediante SSE a medida que llegan (necesario para generaciones largas o salidas que superarían el tiempo límite de HTTP). Predeterminado: `sync`. Por defecto: `sync`. Valores permitidos: `sync`, `stream`.
- `timeout_ms` (integer, opcional): Tiempo máximo de espera para que termine la invocación (o, en modo stream, tiempo máximo de inactividad entre fragmentos). Predeterminado: 30000 en sync, 600000 en stream.
- `llm_retry_max_attempts` (integer, opcional): Intentos totales de la llamada al LLM ante fallos transitorios (HTTP 5xx, 429, red o tiempo agotado). 1 desactiva los reintentos. Si no se indica, usa execution.maxTries y, en su defecto, 3. Tope fijo de 5. Por defecto: `3`.
- `llm_retry_backoff_ms` (integer, opcional): Espera base del backoff exponencial entre reintentos al LLM (espera = base * 2^(intento-1) + jitter, con tope en llm_retry_max_wait_ms). Si no se indica, usa execution.waitBetweenTries y, en su defecto, 1500. Por defecto: `1500`.
- `llm_retry_max_wait_ms` (integer, opcional): Tope de una sola espera de backoff entre reintentos al LLM. Tope fijo de 30000. Por defecto: `20000`.

Admite los ajustes de ejecución compartidos: reintentos (`retryOnFail`, `maxTries`, `waitBetweenTries`) y timeout.

## Puertos de salida

- `success` (por defecto): Classified
- `error`: Error

## Contrato de entrada

- `text` (string, opcional): Contenido de texto principal que se clasifica.
- `subject` (string, opcional): Asunto opcional (correo o formulario).
- `body` (string, opcional): Contenido opcional del cuerpo.
- `sender` (string, opcional): Remitente opcional (correo, dominio o identificador).
- `channel` (string, opcional): Identificador opcional del canal (email, form, api, etc.).
- `metadata` (object, opcional): Metadatos arbitrarios opcionales (encabezados, etiquetas, etc.).

## Contrato de salida

- `category` (string, obligatorio): Categoría principal seleccionada.
- `subcategory` (string | null, obligatorio): Subcategoría seleccionada cuando aplica; en caso contrario, null.
- `confidence` (number, obligatorio): Puntuación de confianza (0-1) de la categoría seleccionada.
- `probabilities` (object, obligatorio): Distribución de probabilidad entre categorías. Los valores deberían sumar aproximadamente 1.
- `routing_hints` (array<string>, opcional): Destinos o indicaciones de enrutamiento sugeridos para orientar los workflows posteriores.
- `notes` (string, opcional): Explicación concisa de 1-2 líneas que menciona las señales y reglas clave.
- `justification` (string, opcional): Justificación más extensa que explica el razonamiento y la precedencia de las reglas.
- `needs_review` (boolean, opcional): True cuando la confianza está por debajo de confidence_threshold, la validación de la salida es débil o falló una compuerta jerárquica de la taxonomía.
- `gate_failed` (array<object>, opcional): Compuertas jerárquicas que la entrada NO cumplió. Una categoría o subcategoría de la taxonomía puede declarar un `gate` ({ requires_any_regex, forbids_any_regex, on_fail }); cuando el texto de entrada no lo cumple, la subcategoría elegida se anula y se fuerza needs_review. Arreglo vacío cuando no falló ninguna compuerta.
- `raw` (object, opcional): Respuesta en bruto del proveedor para auditoría o depuración (opcional).

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Triage Classifier").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Triage Classifier`). **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 `success`, según la salida que muestra Puertos.

- `$("Triage Classifier").item.json.category` (string) = `"Billing"`: Categoría principal seleccionada.
- `$("Triage Classifier").item.json.subcategory` (string | null) = `"Refund"`: Subcategoría seleccionada cuando aplica; en caso contrario, null.
- `$("Triage Classifier").item.json.confidence` (number) = `0.82`: Puntuación de confianza (0-1) de la categoría seleccionada.
- `$("Triage Classifier").item.json.probabilities` (object) = `{…}`: Distribución de probabilidad entre categorías. Los valores deberían sumar aproximadamente 1.
- `$("Triage Classifier").item.json.routing_hints` (array) = `[…] (1)`: Destinos o indicaciones de enrutamiento sugeridos para orientar los workflows posteriores.
- `$("Triage Classifier").item.json.notes` (string) = `"Explicit refund request with an order number."`: Explicación concisa de 1-2 líneas que menciona las señales y reglas clave.
- `$("Triage Classifier").item.json.justification` (string) = `"The sender asks to reverse a charge on a pai…"`: Justificación más extensa que explica el razonamiento y la precedencia de las reglas.
- `$("Triage Classifier").item.json.needs_review` (boolean) = `false`: True cuando la confianza está por debajo de confidence_threshold, la validación de la salida es débil o falló una compuerta jerárquica de la taxonomía.
- `$("Triage Classifier").item.json.gate_failed` (array) = `[…] (0)`: Compuertas jerárquicas que la entrada NO cumplió. Una categoría o subcategoría de la taxonomía puede declarar un `gate` ({ requires_any_regex, forbids_any_regex, on_fail }); cuando el texto de entrada no lo cumple, la subcategoría elegida se anula y se fuerza needs_review. Arreglo vacío cuando no falló ninguna compuerta.
- `$("Triage Classifier").item.json.raw` (object) = `null`: Respuesta en bruto del proveedor para auditoría o depuración (opcional).
- `$("Triage Classifier").item.json.probabilities.Billing` (number) = `0.82` (El editor no la sugiere)
- `$("Triage Classifier").item.json.probabilities.Technical` (number) = `0.12` (El editor no la sugiere)
- `$("Triage Classifier").item.json.probabilities.Sales` (number) = `0.06` (El editor no la sugiere)
- `$("Triage Classifier").item.json.port` (string) = `"success"` (El editor no la sugiere)


## Cómo funciona

Clasifica un elemento de entrada en una categoría y subcategoría de un recurso de taxonomía con el modelo y luego normaliza la respuesta: probabilidades, confianza, pistas de enrutamiento, compuertas de la taxonomía y la marca `needs_review`. Reintenta fallos transitorios del modelo.

1. Combina el payload anterior con la configuración del nodo (gana la configuración). Carga las categorías de `knowledge_resource_id` (`content.structured_data.categories`); sin él, usa un `taxonomy.categories` en línea.
2. Construye la entrada: `text` si es un texto no vacío; si no, líneas `Channel:`, `Sender:`, `Subject:` y `Body:` a partir de `channel`, `sender`, `subject` y `body` (o `body.data.email.body`).
3. Envía un prompt de sistema con cada categoría, su definición y su árbol de subcategorías aplanado, más `general_considerations`, `decision_rules` y `routing_hints_catalog`, pidiendo JSON estricto, a `temperature: 0`.
4. Llama al modelo con reintentos acotados ante HTTP 5xx, 429 y errores sin estado (espera exponencial con variación aleatoria).
5. Interpreta la respuesta como JSON (sin bloques de código; como respaldo, del primer `{` al último `}`). Empareja `category` con la taxonomía sin distinguir mayúsculas (un nombre desconocido se deja tal cual) y solo conserva `subcategory` si pertenece a esa categoría.
6. Aplica las compuertas de la taxonomía: una categoría o subcategoría puede declarar `gate.requires_any_regex` / `gate.forbids_any_regex` (sin distinguir mayúsculas). Una compuerta fallida anula la subcategoría (salvo `on_fail.null_subcategory: false`), puede fijar `on_fail.set_category` / `set_subcategory`, queda registrada en `gate_failed` y fuerza `needs_review: true`.
7. Completa con 0 las probabilidades faltantes, las reescala para que sumen 1, fija `confidence` en la probabilidad de la categoría elegida, conserva solo las pistas de enrutamiento del catálogo y sale por `success`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-triage-intake",
  "label": "Triage intake",
  "operator_slug": "ai.classify.triage",
  "operator_version": "1.0.0",
  "config": {
    "knowledge_resource_id": "<knowledge_resource_id>",
    "subject": "{{ $json.subject }}",
    "body": "{{ $json.body }}",
    "sender": "{{ $json.from }}",
    "channel": "email",
    "general_considerations": [
      "Prefer the most specific category."
    ],
    "decision_rules": [
      "Refund requests are Billing, even when they mention a product."
    ],
    "routing_hints_catalog": [
      "finance-queue",
      "support-queue"
    ],
    "confidence_threshold": 0.7,
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync",
    "llm_retry_max_attempts": 3
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "category": "Billing",
    "subcategory": "Refund",
    "confidence": 0.82,
    "probabilities": {
      "Billing": 0.82,
      "Technical": 0.12,
      "Sales": 0.06
    },
    "routing_hints": [
      "finance-queue"
    ],
    "notes": "Explicit refund request with an order number.",
    "justification": "The sender asks to reverse a charge on a paid order. Billing is more specific than Sales because no new purchase is discussed.",
    "needs_review": false,
    "gate_failed": [],
    "raw": null,
    "port": "success"
  },
  "port": "success"
}
```

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

### `success`

El modelo respondió JSON válido con una categoría. `needs_review` indica si una persona debe revisarlo.

```json
{
  "category": "Billing",
  "subcategory": "Refund",
  "confidence": 0.82,
  "probabilities": {
    "Billing": 0.82,
    "Technical": 0.12,
    "Sales": 0.06
  },
  "routing_hints": [
    "finance-queue"
  ],
  "notes": "Explicit refund request with an order number.",
  "justification": "The sender asks to reverse a charge on a paid order. Billing is more specific than Sales because no new purchase is discussed.",
  "needs_review": false,
  "gate_failed": [],
  "raw": null,
  "port": "success"
}
```

### `error`

Falta la entrada o la taxonomía, la llamada al modelo falló tras sus reintentos o la respuesta no era JSON utilizable.

```json
{
  "error": "Model did not return valid JSON output"
}
```

## Comportamiento en el código

- `llm_retry_max_attempts`: Intentos totales, con tope fijo de 5. Si no se define: 1 si `execution.retryOnFail` es `false`; si no, `execution.maxTries`; si no, 3.
- `llm_retry_backoff_ms`: Espera base, que se duplica en cada reintento más hasta 250 ms aleatorios. Si no se define, usa `execution.waitBetweenTries` y, si no, 1500.
- `llm_retry_max_wait_ms`: Tope de una sola espera, por defecto 20000, con tope fijo de 30000.
- `execution`: A diferencia de otros nodos, aquí `retryOnFail`, `maxTries` y `waitBetweenTries` se usan como política de reintentos de respaldo para la llamada al modelo.
- `taxonomy`: No declarado. Taxonomía en línea heredada `{ categories: [...] }`, usada solo cuando `knowledge_resource_id` está vacío.
- `text, subject, body, sender, channel`: No están en el esquema de configuración, pero se leen primero de la configuración y luego del payload anterior.
- `confidence_threshold`: Solo se usa cuando el modelo no envía `needs_review`: entonces `needs_review` es `confidence < confidence_threshold`. Un `needs_review` del modelo tiene prioridad, salvo que una compuerta fallida siempre fuerza `true`.
- `timeout_ms`: Solo en modo stream: timeout de inactividad entre fragmentos, por defecto 600000. En modo sync no se aplica a la petición.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing input content (text/subject/body)` | `error` | Ninguno de `text`, `channel`, `sender`, `subject` o `body` tiene contenido. |
| `No categories found for triage classification. Ensure the linked knowledge resource contains at least one category.` | `error` | El recurso de taxonomía no tiene `structured_data.categories`. |
| `Model did not return valid JSON output` | `error` | La respuesta no se pudo interpretar como objeto JSON. `Missing 'category' in output` significa que el JSON no traía categoría. |
| `Knowledge resource not found: <knowledge_resource_id>` | `error` | El id no corresponde a ningún recurso de conocimiento. Un recurso eliminado falla con `Knowledge resource "<name>" has been deleted. Update the node config to reference an active resource.` |
| `[TriageClassifier] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). The legacy 'model_id' alias is no longer supported — update the node config to use 'llm_provider_id'.` | `error` | `llm_provider_id` está vacío o no es un texto. Elige un registro de proveedor LLM con capacidad de chat. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada: registro de proveedor inexistente o inactivo, error del proveedor, cuota o filtro de contenido. Revisa el registro de proveedor y los logs del backend. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Modo sync: falló la llamada HTTP al backend (error de red, estado distinto de 2xx o timeout). Los prompts largos suelen agotar el timeout de la petición; cambia a `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Modo stream: no llegó ningún fragmento dentro de `timeout_ms`. Si la petición de stream falla, el mensaje es `RemoteApiService.stream: HTTP <status> — <body>`. |

## Notas y límites

- La falta de `llm_provider_id` y otros errores sin estado HTTP también se reintentan, así que un error de configuración consume todos los intentos y sus esperas antes de fallar.
- Las entradas de `gate_failed` son `{ level, name, reason }`; `reason` es un texto fijo en español, como `requires_any_regex: ninguno coincidió` o `forbids_any_regex coincidió: <pattern>`. Los patrones regex inválidos se ignoran.
- `language` (por defecto `es`) solo fija la línea de idioma del prompt.
- El worker devuelve sus campos en el primer nivel en lugar de dentro de `data`, así que el motor guarda todo el valor devuelto como salida del nodo: `port` y `raw` aparecen en `$json` junto a los campos del resultado.
- La llamada al modelo pasa por el backend de Sommatic AI, que resuelve el registro de proveedor indicado en `llm_provider_id` (endpoint, credenciales, despliegue); el orquestador nunca guarda llaves del proveedor. `invocation_mode: "sync"` (por defecto) espera la respuesta completa; `"stream"` la lee como eventos SSE y une los fragmentos.
- `timeout_ms` solo tiene efecto en modo stream, como tiempo máximo de inactividad entre fragmentos (por defecto 600000). En modo sync el valor se registra en el log, pero no se aplica a la petición HTTP, así que rige el timeout por defecto de la plataforma.
- En modo stream el endpoint del backend no aplica los parámetros de muestreo, así que la `temperature: 0` fija solo tiene efecto en modo sync.
- El recurso de conocimiento se lee del backend en cada ejecución (timeout de 10 s). Un recurso cuyo estado no es `active` se usa igual, con una advertencia en el log.


## Contratos (JSON Schema)

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

```json
{
  "slug": "ai.classify.triage",
  "name": "Triage Classifier",
  "category": "ai",
  "version": "1.0.0",
  "description": "Performs hierarchical intake triage with policy-driven decision rules.\n\nThis operator classifies text into a **category + subcategory** taxonomy, produces **confidence** and a full **probability distribution** across categories, generates **routing hints**, and returns both **notes** and a longer **justification** suitable for audits and human review.\n\n**Typical use cases**\n- Government / legal intake triage (PQRS, tutela, hábeas corpus, etc.)\n- Enterprise incident routing with policy rules\n- Multi-level taxonomy classification with traceable rationale",
  "capabilities": [
    "ai",
    "classification",
    "nlp",
    "taxonomy",
    "triage",
    "routing",
    "explainability"
  ],
  "knowledge_binding": {
    "enabled": true,
    "resource_types": [
      "taxonomy"
    ],
    "field": "knowledge_resource_id",
    "label": "Classification Taxonomy"
  },
  "config_schema": {
    "type": "object",
    "required": [
      "knowledge_resource_id"
    ],
    "properties": {
      "knowledge_resource_id": {
        "type": "string",
        "title": "Classification Taxonomy",
        "description": "Knowledge resource (type: taxonomy) containing the categories and subcategories for triage.",
        "x-ui-widget": "knowledge-resource-picker",
        "x-knowledge-resource-types": [
          "taxonomy"
        ]
      },
      "general_considerations": {
        "type": "array",
        "title": "General Considerations",
        "description": "High-level rules that should always be considered during triage.",
        "items": {
          "type": "string"
        },
        "default": []
      },
      "decision_rules": {
        "type": "array",
        "title": "Decision Rules",
        "description": "Explicit decision/routing rules (specificity, precedence, exceptions).",
        "items": {
          "type": "string"
        },
        "default": []
      },
      "routing_hints_catalog": {
        "type": "array",
        "title": "Routing Hints Catalog",
        "description": "Allowed routing hints that the model may suggest (optional).",
        "items": {
          "type": "string"
        },
        "default": []
      },
      "confidence_threshold": {
        "type": "number",
        "title": "Confidence Threshold",
        "description": "If confidence is below this threshold, the output will be flagged as needs_review.",
        "default": 0.7,
        "minimum": 0,
        "maximum": 1
      },
      "language": {
        "type": "string",
        "title": "Language",
        "description": "Language used for notes/justification and interpretation. Example: \"es\", \"en\".",
        "default": "es"
      },
      "llm_provider_id": {
        "type": "string",
        "title": "LLM Provider",
        "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter (Azure OpenAI, Azure Foundry, OpenAI, AWS Bedrock, Google Vertex, Link Loom Cloud, Generic). Managed in the webapp at `/cognitive-assets/llm-provider/*`.",
        "x-ui-widget": "llm-provider-picker",
        "x-llm-provider-capabilities": [
          "chat"
        ]
      },
      "invocation_mode": {
        "type": "string",
        "title": "Invocation Mode",
        "description": "Transport for the LLM call. `sync` opens a short HTTP request and blocks until the full response arrives (ideal for fast inferences: classification, short generation). `stream` consumes tokens via SSE as they arrive (required for long generations or outputs that would exceed the HTTP timeout). Default `sync`.",
        "enum": [
          "sync",
          "stream"
        ],
        "default": "sync"
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait for the invocation to complete (or, in stream mode, the idle timeout between chunks). Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "llm_retry_max_attempts": {
        "type": "integer",
        "title": "LLM Retry — Max Attempts",
        "description": "Total attempts for the LLM call on transient failures (HTTP 5xx, 429, network/timeout). 1 disables retry. Falls back to execution.maxTries, then 3. Hard-capped at 5.",
        "minimum": 1,
        "maximum": 5,
        "default": 3
      },
      "llm_retry_backoff_ms": {
        "type": "integer",
        "title": "LLM Retry — Base Backoff (ms)",
        "description": "Base delay for exponential backoff between LLM retries (wait = base * 2^(attempt-1) + jitter, capped by llm_retry_max_wait_ms). Falls back to execution.waitBetweenTries, then 1500.",
        "minimum": 0,
        "default": 1500
      },
      "llm_retry_max_wait_ms": {
        "type": "integer",
        "title": "LLM Retry — Max Wait (ms)",
        "description": "Ceiling for a single backoff wait between LLM retries. Hard-capped at 30000.",
        "minimum": 0,
        "default": 20000
      },
      "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": "Incoming content and optional metadata used for intake triage.",
    "properties": {
      "text": {
        "type": "string",
        "description": "Primary text content to classify."
      },
      "subject": {
        "type": "string",
        "description": "Optional subject line (email/form)."
      },
      "body": {
        "type": "string",
        "description": "Optional body content."
      },
      "sender": {
        "type": "string",
        "description": "Optional sender (email/domain/identifier)."
      },
      "channel": {
        "type": "string",
        "description": "Optional channel identifier (email, form, api, etc.)."
      },
      "metadata": {
        "type": "object",
        "description": "Optional arbitrary metadata (headers, tags, etc.).",
        "additionalProperties": true
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "category": {
        "type": "string",
        "description": "Selected primary category."
      },
      "subcategory": {
        "type": [
          "string",
          "null"
        ],
        "description": "Selected subcategory when applicable, else null."
      },
      "confidence": {
        "type": "number",
        "description": "Confidence score (0-1) for the selected category."
      },
      "probabilities": {
        "type": "object",
        "description": "Probability distribution across categories. Values should sum approximately to 1.",
        "additionalProperties": {
          "type": "number"
        }
      },
      "routing_hints": {
        "type": "array",
        "description": "Suggested routing targets / hints to guide downstream workflows.",
        "items": {
          "type": "string"
        }
      },
      "notes": {
        "type": "string",
        "description": "Concise 1-2 line explanation referencing key signals and rules."
      },
      "justification": {
        "type": "string",
        "description": "Longer justification explaining reasoning and rule precedence."
      },
      "needs_review": {
        "type": "boolean",
        "description": "True when confidence is below confidence_threshold, output validation is weak, or a taxonomy hierarchy gate failed."
      },
      "gate_failed": {
        "type": "array",
        "description": "Hierarchy gates that the input did NOT satisfy. A category or subcategory in the taxonomy may declare a `gate` ({ requires_any_regex, forbids_any_regex, on_fail }); when the input text does not satisfy it, the chosen subcategory is nulled and needs_review is forced. Empty array when no gate failed.",
        "items": {
          "type": "object",
          "properties": {
            "level": {
              "type": "string",
              "description": "'category' | 'subcategory'"
            },
            "name": {
              "type": "string"
            },
            "reason": {
              "type": "string"
            }
          }
        }
      },
      "raw": {
        "type": "object",
        "description": "Raw provider response for audit/debug (optional).",
        "additionalProperties": true
      }
    },
    "required": [
      "category",
      "subcategory",
      "confidence",
      "probabilities"
    ]
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Classified",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "classifier",
    "triage",
    "taxonomy",
    "routing"
  ],
  "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": [
    "knowledge_resource_id"
  ],
  "properties": {
    "knowledge_resource_id": {
      "type": "string",
      "title": "Classification Taxonomy",
      "description": "Knowledge resource (type: taxonomy) containing the categories and subcategories for triage.",
      "x-ui-widget": "knowledge-resource-picker",
      "x-knowledge-resource-types": [
        "taxonomy"
      ]
    },
    "general_considerations": {
      "type": "array",
      "title": "General Considerations",
      "description": "High-level rules that should always be considered during triage.",
      "items": {
        "type": "string"
      },
      "default": []
    },
    "decision_rules": {
      "type": "array",
      "title": "Decision Rules",
      "description": "Explicit decision/routing rules (specificity, precedence, exceptions).",
      "items": {
        "type": "string"
      },
      "default": []
    },
    "routing_hints_catalog": {
      "type": "array",
      "title": "Routing Hints Catalog",
      "description": "Allowed routing hints that the model may suggest (optional).",
      "items": {
        "type": "string"
      },
      "default": []
    },
    "confidence_threshold": {
      "type": "number",
      "title": "Confidence Threshold",
      "description": "If confidence is below this threshold, the output will be flagged as needs_review.",
      "default": 0.7,
      "minimum": 0,
      "maximum": 1
    },
    "language": {
      "type": "string",
      "title": "Language",
      "description": "Language used for notes/justification and interpretation. Example: \"es\", \"en\".",
      "default": "es"
    },
    "llm_provider_id": {
      "type": "string",
      "title": "LLM Provider",
      "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter (Azure OpenAI, Azure Foundry, OpenAI, AWS Bedrock, Google Vertex, Link Loom Cloud, Generic). Managed in the webapp at `/cognitive-assets/llm-provider/*`.",
      "x-ui-widget": "llm-provider-picker",
      "x-llm-provider-capabilities": [
        "chat"
      ]
    },
    "invocation_mode": {
      "type": "string",
      "title": "Invocation Mode",
      "description": "Transport for the LLM call. `sync` opens a short HTTP request and blocks until the full response arrives (ideal for fast inferences: classification, short generation). `stream` consumes tokens via SSE as they arrive (required for long generations or outputs that would exceed the HTTP timeout). Default `sync`.",
      "enum": [
        "sync",
        "stream"
      ],
      "default": "sync"
    },
    "timeout_ms": {
      "type": "integer",
      "title": "Timeout (ms)",
      "description": "Maximum time to wait for the invocation to complete (or, in stream mode, the idle timeout between chunks). Default 30000 for sync, 600000 for stream.",
      "minimum": 1000
    },
    "llm_retry_max_attempts": {
      "type": "integer",
      "title": "LLM Retry — Max Attempts",
      "description": "Total attempts for the LLM call on transient failures (HTTP 5xx, 429, network/timeout). 1 disables retry. Falls back to execution.maxTries, then 3. Hard-capped at 5.",
      "minimum": 1,
      "maximum": 5,
      "default": 3
    },
    "llm_retry_backoff_ms": {
      "type": "integer",
      "title": "LLM Retry — Base Backoff (ms)",
      "description": "Base delay for exponential backoff between LLM retries (wait = base * 2^(attempt-1) + jitter, capped by llm_retry_max_wait_ms). Falls back to execution.waitBetweenTries, then 1500.",
      "minimum": 0,
      "default": 1500
    },
    "llm_retry_max_wait_ms": {
      "type": "integer",
      "title": "LLM Retry — Max Wait (ms)",
      "description": "Ceiling for a single backoff wait between LLM retries. Hard-capped at 30000.",
      "minimum": 0,
      "default": 20000
    },
    "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": "Incoming content and optional metadata used for intake triage.",
  "properties": {
    "text": {
      "type": "string",
      "description": "Primary text content to classify."
    },
    "subject": {
      "type": "string",
      "description": "Optional subject line (email/form)."
    },
    "body": {
      "type": "string",
      "description": "Optional body content."
    },
    "sender": {
      "type": "string",
      "description": "Optional sender (email/domain/identifier)."
    },
    "channel": {
      "type": "string",
      "description": "Optional channel identifier (email, form, api, etc.)."
    },
    "metadata": {
      "type": "object",
      "description": "Optional arbitrary metadata (headers, tags, etc.).",
      "additionalProperties": true
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "category": {
      "type": "string",
      "description": "Selected primary category."
    },
    "subcategory": {
      "type": [
        "string",
        "null"
      ],
      "description": "Selected subcategory when applicable, else null."
    },
    "confidence": {
      "type": "number",
      "description": "Confidence score (0-1) for the selected category."
    },
    "probabilities": {
      "type": "object",
      "description": "Probability distribution across categories. Values should sum approximately to 1.",
      "additionalProperties": {
        "type": "number"
      }
    },
    "routing_hints": {
      "type": "array",
      "description": "Suggested routing targets / hints to guide downstream workflows.",
      "items": {
        "type": "string"
      }
    },
    "notes": {
      "type": "string",
      "description": "Concise 1-2 line explanation referencing key signals and rules."
    },
    "justification": {
      "type": "string",
      "description": "Longer justification explaining reasoning and rule precedence."
    },
    "needs_review": {
      "type": "boolean",
      "description": "True when confidence is below confidence_threshold, output validation is weak, or a taxonomy hierarchy gate failed."
    },
    "gate_failed": {
      "type": "array",
      "description": "Hierarchy gates that the input did NOT satisfy. A category or subcategory in the taxonomy may declare a `gate` ({ requires_any_regex, forbids_any_regex, on_fail }); when the input text does not satisfy it, the chosen subcategory is nulled and needs_review is forced. Empty array when no gate failed.",
      "items": {
        "type": "object",
        "properties": {
          "level": {
            "type": "string",
            "description": "'category' | 'subcategory'"
          },
          "name": {
            "type": "string"
          },
          "reason": {
            "type": "string"
          }
        }
      }
    },
    "raw": {
      "type": "object",
      "description": "Raw provider response for audit/debug (optional).",
      "additionalProperties": true
    }
  },
  "required": [
    "category",
    "subcategory",
    "confidence",
    "probabilities"
  ]
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Classified",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
