# Outlook - Message Category

> Aplica categorías (etiquetas) de Outlook a los mensajes mediante Microsoft Graph API.

Source: https://docs.sommatic.ai/es/nodes/connectors.microsoft.outlook.message.category/

- Slug: `connectors.microsoft.outlook.message.category`
- Familia: Conectores
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Aplica categorías (etiquetas) de Outlook a los mensajes mediante Microsoft Graph API.

Las categorías viven en la lista maestra del usuario y se aplican a los mensajes con un PATCH que combina de forma segura y conserva las categorías que ya pusieron personas u otras automatizaciones.

**Operaciones:**
- **apply:** Aplica una o varias categorías a un mensaje existente. Las combina con las categorías existentes (no las sobrescribe).
- **ensure_master_category:** Crea una o varias categorías en la lista maestra del usuario. Es idempotente: devuelve éxito si la categoría ya existe.
- **apply_with_ensure:** Combina las dos anteriores. Recomendada para workflows que deben crear sus propias categorías.

## Configuración

- `connection_id` (string, obligatorio): Credencial de acceso a Microsoft Graph API. Requiere `Mail.ReadWrite` (para PATCH /messages/{id}) y `MailboxSettings.ReadWrite` (para POST /outlook/masterCategories). Acepta credenciales de tipo `oauth2` (token de acceso + token de actualización), `service-account` (tenant id + client id + client secret) u `object` (configuración avanzada de Graph).
- `mailbox_mode` (string, opcional): Token owner: usa el buzón de la cuenta que generó la credencial. Other mailbox: indica una dirección de correo (requiere permisos de aplicación en Azure AD). Por defecto: `token_owner`. Valores permitidos: `token_owner`, `other`.
- `mailbox_email` (any, opcional, acepta expresiones): Un correo o un arreglo / lista separada por comas de buzones sobre los que se opera. Si se indica más de uno, el worker se distribuye y aplica las categorías en cada buzón que contenga el mismo mensaje (identificado por internetMessageId). Se muestra cuando: mailbox_mode = `other`.
- `internet_message_id` (string, opcional, acepta expresiones): Internet Message ID RFC-5322 del correo (p. ej., <BL0PR16MB...@outlook.com>). Obligatorio en el modo de varios buzones: el worker lo usa para encontrar el id local del mensaje en cada buzón mediante $filter=internetMessageId eq. Si se omite y se indica un solo buzón, el worker vuelve al flujo heredado de un solo buzón y usa `message_id` directamente. Se muestra cuando: operation = `apply` | `apply_with_ensure`.
- `operation` (string, obligatorio): apply: aplica categorías a un mensaje existente (combinación segura). ensure_master_category: crea categorías en la lista maestra del usuario (idempotente). apply_with_ensure: ensure + apply en una sola llamada (recomendado). Por defecto: `apply_with_ensure`. Valores permitidos: `apply`, `ensure_master_category`, `apply_with_ensure`.
- `message_id` (string, opcional, acepta expresiones): ID de Graph del mensaje que se categoriza. Se muestra cuando: operation = `apply` | `apply_with_ensure`.
- `categories` (array<string | object>, opcional, acepta expresiones): Categorías que se aplican o se aseguran. Acepta: un arreglo de cadenas con el nombre visible, una cadena separada por comas O un arreglo de objetos { name, color } para fijar un color distinto por categoría (p. ej. [{name:"Recibido por IA - Sommatic",color:"preset8"},{name:"Asignado DAUITA",color:"preset4"}]). Cuando un elemento no tiene color, se usa el category_color del nodo.
- `category_color` (string, opcional): Color predefinido de la categoría de Outlook. Obligatorio para ensure_master_category y apply_with_ensure (apply lo ignora). Valores comunes: preset0 (rojo), preset8 (morado), preset23 (morado oscuro, el más cercano al corporativo de Sommatic AI #2A213B). Usa "none" para no asignar color. Valores permitidos: `preset0`, `preset1`, `preset2`, `preset3`, `preset4`, `preset5`, `preset6`, `preset7`, `preset8`, `preset9`, `preset10`, `preset11`, `preset12`, `preset13`, `preset14`, `preset15`, `preset16`, `preset17`, `preset18`, `preset19`, `preset20`, `preset21`, `preset22`, `preset23`, `preset24`, `none`. Se muestra cuando: operation = `ensure_master_category` | `apply_with_ensure`.
- `match_scope` (string, opcional): conversation (predeterminado): se busca un internet_message_id y se extiende a TODO el hilo (etiqueta el original y sus respuestas/reenvíos). message: resuelve SOLO las coincidencias exactas del internet_message_id (la copia de la respuesta o del reenvío), sin extenderse nunca a la conversación. Usa "message" para etiquetar o marcar como leída una copia concreta generada por la IA sin tocar el original del ciudadano. Por defecto: `conversation`. Valores permitidos: `conversation`, `message`. Se muestra cuando: operation = `apply` | `apply_with_ensure`.
- `mark_read` (boolean, opcional): Después de etiquetar, aplica PATCH { isRead:true } a cada mensaje resuelto. Limítalo solo a las copias generadas por la IA (con match_scope:"message" o apuntando al buzón de forward_recipient); nunca dirijas un nodo con mark_read al original del ciudadano, que debe quedar sin leer. Por defecto: `false`. Se muestra cuando: operation = `apply` | `apply_with_ensure`.
- `resolve_max_attempts` (number, opcional): Reintentos acotados de la consulta de resolución del mensaje. Absorbe la latencia de indexación de Graph para una copia de respuesta o reenvío recién enviada (un "éxito que resolvió 0 mensajes" no vuelve a disparar el reintento del nodo). Usa, por ejemplo, 6 en los nodos de copias de la IA; deja 1 en las llamadas heredadas. Por defecto: `1`. Se muestra cuando: operation = `apply` | `apply_with_ensure`.
- `resolve_wait_ms` (number, opcional): Espera entre intentos de resolución, en milisegundos (p. ej. 1500). Solo aplica cuando resolve_max_attempts > 1. Por defecto: `0`. Se muestra cuando: operation = `apply` | `apply_with_ensure`.
- `require_apply` (boolean, opcional): Si es true, emite port:"error" cuando no se etiquetó nada después de todos los reintentos (en lugar de un éxito silencioso). Permite que quien llama active una rama de respaldo (p. ej., un aviso + una tarea humana). Por defecto: `false`. Se muestra cuando: operation = `apply` | `apply_with_ensure`.

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 operación de categorías terminó correctamente.
- `error`: La operación falló (error de autenticación, ID de mensaje no válido, error de la API).

## Contrato de entrada

- `connection_id` (string, obligatorio)
- `operation` (string, obligatorio)
- `message_id` (string, opcional)
- `internet_message_id` (string, opcional)
- `conversation_id` (string, opcional)
- `categories` (array<string>, opcional)
- `category_color` (string, opcional)
- `match_scope` (string, opcional): Valores permitidos: `conversation`, `message`.
- `mark_read` (boolean, opcional)
- `resolve_max_attempts` (number, opcional)
- `resolve_wait_ms` (number, opcional)
- `require_apply` (boolean, opcional)

## Contrato de salida

- `result` (object, opcional)
  - `operation` (string, opcional)
  - `message_id` (string, opcional)
  - `applied` (array<string>, opcional): Categorías nuevas agregadas al mensaje.
  - `preserved` (array<string>, opcional): Categorías que ya tenía el mensaje y que se conservaron.
  - `final_categories` (array<string>, opcional): Categorías finales del mensaje tras la operación.
  - `ensured` (array<string>, opcional): Categorías creadas en la lista maestra.
  - `already_existed` (array<string>, opcional): Categorías que ya existían en la lista maestra.
  - `master_category_ensured` (boolean, opcional)
  - `conversation_id_resolved` (string, opcional): Id del hilo usado para resolver los mensajes (modo de varios buzones).
  - `messages_per_mailbox` (object, opcional): Número de mensajes etiquetados por buzón.
  - `messages_read_by_mailbox` (object, opcional): Número de mensajes marcados como leídos (isRead:true) por buzón, cuando mark_read está activado.

## En expresiones

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

- `$("Outlook - Message Category").item.json.result` (object) = `{…}`
- `$("Outlook - Message Category").item.json.result.operation` (string) = `"apply_with_ensure"`
- `$("Outlook - Message Category").item.json.result.message_id` (string) = `"AAkALgAAAAAAHYQDEapmEc2byACqAC-EWg0A"`
- `$("Outlook - Message Category").item.json.result.applied` (array) = `[…] (1)`: Categorías nuevas agregadas al mensaje.
- `$("Outlook - Message Category").item.json.result.preserved` (array) = `[…] (1)`: Categorías que ya tenía el mensaje y que se conservaron.
- `$("Outlook - Message Category").item.json.result.final_categories` (array) = `[…] (2)`: Categorías finales del mensaje tras la operación.
- `$("Outlook - Message Category").item.json.result.ensured` (array) = `[…] (0)`: Categorías creadas en la lista maestra.
- `$("Outlook - Message Category").item.json.result.already_existed` (array) = `[…] (1)`: Categorías que ya existían en la lista maestra.
- `$("Outlook - Message Category").item.json.result.master_category_ensured` (boolean) = `true`
- `$("Outlook - Message Category").item.json.result.conversation_id_resolved` (string): Id del hilo usado para resolver los mensajes (modo de varios buzones). **El worker no la devuelve: se lee como undefined.**
- `$("Outlook - Message Category").item.json.result.messages_per_mailbox` (object): Número de mensajes etiquetados por buzón. **El worker no la devuelve: se lee como undefined.**
- `$("Outlook - Message Category").item.json.result.messages_read_by_mailbox` (object): Número de mensajes marcados como leídos (isRead:true) por buzón, cuando mark_read está activado. **El worker no la devuelve: se lee como undefined.**
- `$("Outlook - Message Category").item.json.result.permission_denied` (array) = `[…] (0)` (El editor no la sugiere)


## Cómo funciona

Aplica categorías (etiquetas) de Outlook a un mensaje sin quitar las que ya tiene, y puede crearlas con color en la lista maestra de categorías del buzón. Funciona en un buzón por id de mensaje, o se distribuye entre varios buzones por Internet Message ID o por conversación.

1. Resuelve la configuración del nodo, exige `connection_id` y obtiene un token de Graph (de aplicación con `client_id`, `client_secret`, `tenant_id`, o el `token` / `access_token` guardado). Cada solicitud pide ids inmutables (`Prefer: IdType="ImmutableId"`).
2. Normaliza `categories` a partir de un texto separado por comas, un arreglo de nombres o un arreglo de `{ name, color }`; los elementos sin color usan `category_color`.
3. El modo de un solo buzón aplica cuando hay un buzón (o `mailbox_mode` es `token_owner`) y no se definen `internet_message_id` ni `conversation_id`: trabaja directamente sobre `message_id`.
4. En otro caso se distribuye sobre `mailbox_email` (arreglo o lista separada por comas). Con `internet_message_id` y `match_scope: conversation`, primero busca en los buzones el id de conversación; luego, en paralelo por buzón, resuelve los mensajes locales (los de la conversación, hasta 50, o con `match_scope: message` solo las copias exactas del Internet Message ID, hasta 10), reintentando `resolve_max_attempts` veces con `resolve_wait_ms` entre intentos.
5. `ensure_master_category` crea cada categoría en la lista maestra; si ya existe se acepta y se corrige su color cuando difiere. `apply` lee las categorías del mensaje, agrega las nuevas sin duplicados y hace PATCH, reintentando 412 (change key), 429 (respetando `Retry-After`) y 404 hasta `patch_max_attempts`. `apply_with_ensure` ejecuta ambas.
6. Con `mark_read`, marca como leídos los mensajes resueltos (en la medida de lo posible). Elige `error` cuando fallaron todos los buzones, o cuando `require_apply` está activo y no se etiquetó nada; si no, `out`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-label-processed",
  "label": "Label as processed",
  "operator_slug": "connectors.microsoft.outlook.message.category",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "mailbox_mode": "other",
    "mailbox_email": "support@example.com",
    "operation": "apply_with_ensure",
    "message_id": "{{ $json.id }}",
    "categories": [
      {
        "name": "Processed",
        "color": "preset4"
      }
    ],
    "category_color": "preset8"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": {
      "operation": "apply_with_ensure",
      "message_id": "AAkALgAAAAAAHYQDEapmEc2byACqAC-EWg0A",
      "applied": [
        "Processed"
      ],
      "preserved": [
        "Customer"
      ],
      "final_categories": [
        "Customer",
        "Processed"
      ],
      "master_category_ensured": true,
      "ensured": [],
      "already_existed": [
        "Processed"
      ],
      "permission_denied": []
    }
  },
  "port": "out"
}
```

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

### `out`

Modo de un buzón: las categorías se aplicaron o ya estaban. Modo multibuzón: al menos un buzón no falló; la salida es entonces `{ result: { operation, mode: "multi_mailbox", conversation_id_resolved, mailboxes_total, applied_in, messages_per_mailbox, messages_read_by_mailbox, not_found_in, permission_denied_in, errored_in, conflict_in, any_applied, any_conflict } }`.

```json
{
  "result": {
    "operation": "apply_with_ensure",
    "message_id": "AAkALgAAAAAAHYQDEapmEc2byACqAC-EWg0A",
    "applied": [
      "Processed"
    ],
    "preserved": [
      "Customer"
    ],
    "final_categories": [
      "Customer",
      "Processed"
    ],
    "master_category_ensured": true,
    "ensured": [],
    "already_existed": [
      "Processed"
    ],
    "permission_denied": []
  }
}
```

### `error`

Falló una validación (la salida es el sobre `{ ok, errors, port }`), falló una llamada a Graph en modo de un buzón (`{ error, response }`), o en modo multibuzón fallaron todos los buzones o `require_apply` no encontró nada etiquetado (el `result` multibuzón).

```json
{
  "ok": false,
  "errors": [
    "At least one category is required for apply operation"
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `patch_max_attempts`: No declarado. Intentos de cada PATCH de categorías (por defecto 4, mínimo 1). `patch_wait_ms` (no declarado, por defecto 500) se multiplica por el número de intento entre reintentos, salvo que Graph envíe `Retry-After`.
- `conversation_id`: No está declarado en el esquema de configuración (solo en el contrato de entrada). Si se define, se usa directamente como el hilo a etiquetar y se omite la búsqueda por Internet Message ID; también activa el modo multibuzón.
- `mailbox_email`: Solo se lee cuando `mailbox_mode` es `other`. Acepta una dirección, un arreglo o una lista separada por comas; más de una dirección activa el modo multibuzón.
- `category_color`: Preajuste de Outlook (`preset0`…`preset24`) o `none`. `apply` lo ignora. El `color` de cada elemento en `categories` tiene prioridad.
- `mark_read`: En modo de un buzón marca `message_id` como leído; en modo multibuzón, todos los mensajes resueltos. Con `match_scope: conversation` eso incluye todo el hilo, así que usa `match_scope: message` para marcar solo una copia.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Microsoft 365 credential is required` | `error` | `connection_id` está vacío. |
| `Failed to resolve Microsoft 365 access token` | `error` | No se pudo resolver la credencial o falló la solicitud del token. |
| `Message ID is required for apply operation` | `error` | Modo de un buzón sin `message_id`. |
| `At least one category is required for apply operation` | `error` | `categories` está vacío. En `ensure_master_category` el mensaje es `At least one category displayName is required`. |
| `Failed to ensure master category '<name>': <Graph message>` | `error` | La creación de la categoría falló por un motivo distinto de "ya existe" o de un error de permisos. |
| `Unknown operation: <operation>` | `error` | `operation` no es apply, ensure_master_category ni apply_with_ensure (modo de un buzón). |
| `No messages could be labeled in this mailbox: <reason>` | `error` | Modo multibuzón: se informa por buzón dentro de `errored_in` (o de `conflict_in` para conflictos de change key que persistieron tras los reintentos). |

## Notas y límites

- Aplicar es seguro e idempotente: se conservan las categorías existentes y una categoría que ya estaba devuelve `reason: "already_present"` con `skipped`.
- Sin `MailboxSettings.ReadWrite`, `apply_with_ensure` igual etiqueta el mensaje y devuelve `master_category_ensured: false` con un `warning`; la categoría puede verse sin color.
- En modo multibuzón, un 401/403 en un buzón se cuenta en `permission_denied_in`, no como error. Los ids de conversación cambian según el buzón, así que cuando la búsqueda del hilo no devuelve nada el worker vuelve a derivar el hilo local a partir de `internet_message_id`.
- El modo multibuzón escribe en los logs una línea de resumen `[label-trace]` por ejecución, más una línea por cada buzón donde no quedó la etiqueta.


## Contratos (JSON Schema)

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

```json
{
  "slug": "connectors.microsoft.outlook.message.category",
  "name": "Outlook - Message Category",
  "category": "integrations",
  "version": "1.0.0",
  "description": "Apply Outlook categories (labels) to messages via the Microsoft Graph API.\n\n  Categories live in the user master list and can be applied to messages with a merge-safe PATCH that preserves categories already set by humans or other automations.\n\n  **Operations:**\n  - **apply:** Apply one or more categories to an existing message. Merges with existing categories (does not overwrite).\n  - **ensure_master_category:** Create one or more categories in the user master list. Idempotent: returns success if the category already exists.\n  - **apply_with_ensure:** Combination of the two. Recommended for workflows that should self-bootstrap their categories.",
  "capabilities": [
    "email",
    "microsoft",
    "outlook",
    "office365",
    "graph-api",
    "category",
    "label"
  ],
  "group": [
    {
      "key": "microsoft",
      "name": "Microsoft",
      "icon_url": "/icons/integrations/microsoft/microsoft.svg"
    },
    {
      "key": "microsoft365",
      "name": "Microsoft 365",
      "icon_url": "/icons/integrations/microsoft/microsoft365.svg"
    }
  ],
  "icon_url": "/icons/integrations/microsoft/outlook.svg",
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "Microsoft 365 Credential",
        "description": "Credential for Microsoft Graph API access. Requires `Mail.ReadWrite` (for PATCH /messages/{id}) and `MailboxSettings.ReadWrite` (for POST /outlook/masterCategories). Accepts credentials of type `oauth2` (access + refresh token), `service-account` (tenant id + client id + client secret), or `object` (advanced Graph config).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "oauth2",
            "service-account",
            "object"
          ],
          "types": [
            "outlook",
            "microsoft365",
            "oauth2"
          ]
        }
      },
      "mailbox_mode": {
        "type": "string",
        "title": "Mailbox",
        "enum": [
          "token_owner",
          "other"
        ],
        "default": "token_owner",
        "description": "Token owner: uses the mailbox of the account that generated the credential. Other mailbox: specify an email address (requires Application permissions in Azure AD)."
      },
      "mailbox_email": {
        "title": "Mailbox Email(s)",
        "description": "Single email or array/comma-separated list of mailboxes to operate on. When more than one is provided, the worker fans out and applies the categories in every mailbox that contains the same message (matched by internetMessageId).",
        "format": "expression",
        "displayOptions": {
          "show": {
            "mailbox_mode": [
              "other"
            ]
          }
        }
      },
      "internet_message_id": {
        "type": "string",
        "title": "Internet Message ID",
        "description": "RFC-5322 Internet Message ID of the email (e.g., <BL0PR16MB...@outlook.com>). Required for multi-mailbox mode: the worker uses it to find the local message id in each mailbox via $filter=internetMessageId eq. When omitted and a single mailbox is provided, the worker falls back to the legacy single-mailbox flow using `message_id` directly.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "apply",
              "apply_with_ensure"
            ]
          }
        }
      },
      "operation": {
        "type": "string",
        "title": "Operation",
        "enum": [
          "apply",
          "ensure_master_category",
          "apply_with_ensure"
        ],
        "default": "apply_with_ensure",
        "description": "apply: apply categories to an existing message (merge-safe). ensure_master_category: create categories in the user master list (idempotent). apply_with_ensure: ensure + apply in one call (recommended)."
      },
      "message_id": {
        "type": "string",
        "title": "Message ID",
        "description": "Graph message ID of the email to categorize.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "apply",
              "apply_with_ensure"
            ]
          }
        }
      },
      "categories": {
        "type": "array",
        "title": "Categories",
        "items": {
          "type": [
            "string",
            "object"
          ]
        },
        "description": "Categories to apply or ensure. Accepts: an array of display-name strings, a comma-separated string, OR an array of { name, color } objects to set a distinct color per category (e.g. [{name:\"Recibido por IA - Sommatic\",color:\"preset8\"},{name:\"Asignado DAUITA\",color:\"preset4\"}]). When an item has no color, the node-level category_color is used.",
        "format": "expression"
      },
      "category_color": {
        "type": "string",
        "title": "Category Color",
        "enum": [
          "preset0",
          "preset1",
          "preset2",
          "preset3",
          "preset4",
          "preset5",
          "preset6",
          "preset7",
          "preset8",
          "preset9",
          "preset10",
          "preset11",
          "preset12",
          "preset13",
          "preset14",
          "preset15",
          "preset16",
          "preset17",
          "preset18",
          "preset19",
          "preset20",
          "preset21",
          "preset22",
          "preset23",
          "preset24",
          "none"
        ],
        "description": "Outlook category color preset. Required for ensure_master_category and apply_with_ensure (ignored by apply). Common values: preset0 (Red), preset8 (Purple), preset23 (Dark Purple - closest to Sommatic AI corporate #2A213B). Use \"none\" for no color.",
        "displayOptions": {
          "show": {
            "operation": [
              "ensure_master_category",
              "apply_with_ensure"
            ]
          }
        }
      },
      "match_scope": {
        "type": "string",
        "title": "Match Scope",
        "enum": [
          "conversation",
          "message"
        ],
        "default": "conversation",
        "description": "conversation (default): an internet_message_id is probed and expanded to the WHOLE thread (labels original + replies/forwards). message: resolve ONLY the exact internet_message_id matches (the reply/forward copy) — never expand to the conversation. Use \"message\" to label/mark-read a specific IA-generated copy without touching the citizen original.",
        "displayOptions": {
          "show": {
            "operation": [
              "apply",
              "apply_with_ensure"
            ]
          }
        }
      },
      "mark_read": {
        "type": "boolean",
        "title": "Mark as Read",
        "default": false,
        "description": "After labeling, PATCH { isRead:true } on every resolved message. Scope it to IA-generated copies only (via match_scope:\"message\" or by targeting the forward_recipient mailbox); never point a mark_read node at the citizen original, which must stay unread.",
        "displayOptions": {
          "show": {
            "operation": [
              "apply",
              "apply_with_ensure"
            ]
          }
        }
      },
      "resolve_max_attempts": {
        "type": "number",
        "title": "Resolve Max Attempts",
        "default": 1,
        "description": "Bounded retry on the message-resolution query. Absorbs Graph indexing latency of a just-sent reply/forward copy (a \"success that resolved 0 messages\" does not re-fire the node retry). Use e.g. 6 for IA-copy nodes; leave 1 for legacy calls.",
        "displayOptions": {
          "show": {
            "operation": [
              "apply",
              "apply_with_ensure"
            ]
          }
        }
      },
      "resolve_wait_ms": {
        "type": "number",
        "title": "Resolve Wait (ms)",
        "default": 0,
        "description": "Delay between resolution attempts in milliseconds (e.g. 1500). Only relevant when resolve_max_attempts > 1.",
        "displayOptions": {
          "show": {
            "operation": [
              "apply",
              "apply_with_ensure"
            ]
          }
        }
      },
      "require_apply": {
        "type": "boolean",
        "title": "Require Apply",
        "default": false,
        "description": "When true, emit port:\"error\" if nothing was labeled after all retries (instead of a silent success). Lets the caller drive a fallback branch (e.g. a notice + human task).",
        "displayOptions": {
          "show": {
            "operation": [
              "apply",
              "apply_with_ensure"
            ]
          }
        }
      },
      "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
          }
        }
      }
    },
    "required": [
      "connection_id",
      "operation"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "operation": {
        "type": "string"
      },
      "message_id": {
        "type": "string"
      },
      "internet_message_id": {
        "type": "string"
      },
      "conversation_id": {
        "type": "string"
      },
      "categories": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "category_color": {
        "type": "string"
      },
      "match_scope": {
        "type": "string",
        "enum": [
          "conversation",
          "message"
        ]
      },
      "mark_read": {
        "type": "boolean"
      },
      "resolve_max_attempts": {
        "type": "number"
      },
      "resolve_wait_ms": {
        "type": "number"
      },
      "require_apply": {
        "type": "boolean"
      }
    },
    "required": [
      "connection_id",
      "operation"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "object",
        "properties": {
          "operation": {
            "type": "string"
          },
          "message_id": {
            "type": "string"
          },
          "applied": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Categories newly added to the message."
          },
          "preserved": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Categories that were already on the message and were preserved."
          },
          "final_categories": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Final categories on the message after the operation."
          },
          "ensured": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Categories created in the master list."
          },
          "already_existed": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Categories that already existed in the master list."
          },
          "master_category_ensured": {
            "type": "boolean"
          },
          "conversation_id_resolved": {
            "type": "string",
            "description": "Thread id used to resolve messages (multi-mailbox mode)."
          },
          "messages_per_mailbox": {
            "type": "object",
            "description": "Count of messages labeled per mailbox."
          },
          "messages_read_by_mailbox": {
            "type": "object",
            "description": "Count of messages marked read (isRead:true) per mailbox, when mark_read is set."
          }
        }
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Success",
      "description": "Category operation completed successfully.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Operation failed (auth error, invalid message ID, API error).",
      "is_default": false,
      "supports_condition": true
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "cloud-io"
  ],
  "tags": [
    "email",
    "microsoft",
    "outlook",
    "office365",
    "category",
    "label",
    "connector"
  ],
  "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": {
    "connection_id": {
      "type": "string",
      "title": "Microsoft 365 Credential",
      "description": "Credential for Microsoft Graph API access. Requires `Mail.ReadWrite` (for PATCH /messages/{id}) and `MailboxSettings.ReadWrite` (for POST /outlook/masterCategories). Accepts credentials of type `oauth2` (access + refresh token), `service-account` (tenant id + client id + client secret), or `object` (advanced Graph config).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "oauth2",
          "service-account",
          "object"
        ],
        "types": [
          "outlook",
          "microsoft365",
          "oauth2"
        ]
      }
    },
    "mailbox_mode": {
      "type": "string",
      "title": "Mailbox",
      "enum": [
        "token_owner",
        "other"
      ],
      "default": "token_owner",
      "description": "Token owner: uses the mailbox of the account that generated the credential. Other mailbox: specify an email address (requires Application permissions in Azure AD)."
    },
    "mailbox_email": {
      "title": "Mailbox Email(s)",
      "description": "Single email or array/comma-separated list of mailboxes to operate on. When more than one is provided, the worker fans out and applies the categories in every mailbox that contains the same message (matched by internetMessageId).",
      "format": "expression",
      "displayOptions": {
        "show": {
          "mailbox_mode": [
            "other"
          ]
        }
      }
    },
    "internet_message_id": {
      "type": "string",
      "title": "Internet Message ID",
      "description": "RFC-5322 Internet Message ID of the email (e.g., <BL0PR16MB...@outlook.com>). Required for multi-mailbox mode: the worker uses it to find the local message id in each mailbox via $filter=internetMessageId eq. When omitted and a single mailbox is provided, the worker falls back to the legacy single-mailbox flow using `message_id` directly.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "apply",
            "apply_with_ensure"
          ]
        }
      }
    },
    "operation": {
      "type": "string",
      "title": "Operation",
      "enum": [
        "apply",
        "ensure_master_category",
        "apply_with_ensure"
      ],
      "default": "apply_with_ensure",
      "description": "apply: apply categories to an existing message (merge-safe). ensure_master_category: create categories in the user master list (idempotent). apply_with_ensure: ensure + apply in one call (recommended)."
    },
    "message_id": {
      "type": "string",
      "title": "Message ID",
      "description": "Graph message ID of the email to categorize.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "apply",
            "apply_with_ensure"
          ]
        }
      }
    },
    "categories": {
      "type": "array",
      "title": "Categories",
      "items": {
        "type": [
          "string",
          "object"
        ]
      },
      "description": "Categories to apply or ensure. Accepts: an array of display-name strings, a comma-separated string, OR an array of { name, color } objects to set a distinct color per category (e.g. [{name:\"Recibido por IA - Sommatic\",color:\"preset8\"},{name:\"Asignado DAUITA\",color:\"preset4\"}]). When an item has no color, the node-level category_color is used.",
      "format": "expression"
    },
    "category_color": {
      "type": "string",
      "title": "Category Color",
      "enum": [
        "preset0",
        "preset1",
        "preset2",
        "preset3",
        "preset4",
        "preset5",
        "preset6",
        "preset7",
        "preset8",
        "preset9",
        "preset10",
        "preset11",
        "preset12",
        "preset13",
        "preset14",
        "preset15",
        "preset16",
        "preset17",
        "preset18",
        "preset19",
        "preset20",
        "preset21",
        "preset22",
        "preset23",
        "preset24",
        "none"
      ],
      "description": "Outlook category color preset. Required for ensure_master_category and apply_with_ensure (ignored by apply). Common values: preset0 (Red), preset8 (Purple), preset23 (Dark Purple - closest to Sommatic AI corporate #2A213B). Use \"none\" for no color.",
      "displayOptions": {
        "show": {
          "operation": [
            "ensure_master_category",
            "apply_with_ensure"
          ]
        }
      }
    },
    "match_scope": {
      "type": "string",
      "title": "Match Scope",
      "enum": [
        "conversation",
        "message"
      ],
      "default": "conversation",
      "description": "conversation (default): an internet_message_id is probed and expanded to the WHOLE thread (labels original + replies/forwards). message: resolve ONLY the exact internet_message_id matches (the reply/forward copy) — never expand to the conversation. Use \"message\" to label/mark-read a specific IA-generated copy without touching the citizen original.",
      "displayOptions": {
        "show": {
          "operation": [
            "apply",
            "apply_with_ensure"
          ]
        }
      }
    },
    "mark_read": {
      "type": "boolean",
      "title": "Mark as Read",
      "default": false,
      "description": "After labeling, PATCH { isRead:true } on every resolved message. Scope it to IA-generated copies only (via match_scope:\"message\" or by targeting the forward_recipient mailbox); never point a mark_read node at the citizen original, which must stay unread.",
      "displayOptions": {
        "show": {
          "operation": [
            "apply",
            "apply_with_ensure"
          ]
        }
      }
    },
    "resolve_max_attempts": {
      "type": "number",
      "title": "Resolve Max Attempts",
      "default": 1,
      "description": "Bounded retry on the message-resolution query. Absorbs Graph indexing latency of a just-sent reply/forward copy (a \"success that resolved 0 messages\" does not re-fire the node retry). Use e.g. 6 for IA-copy nodes; leave 1 for legacy calls.",
      "displayOptions": {
        "show": {
          "operation": [
            "apply",
            "apply_with_ensure"
          ]
        }
      }
    },
    "resolve_wait_ms": {
      "type": "number",
      "title": "Resolve Wait (ms)",
      "default": 0,
      "description": "Delay between resolution attempts in milliseconds (e.g. 1500). Only relevant when resolve_max_attempts > 1.",
      "displayOptions": {
        "show": {
          "operation": [
            "apply",
            "apply_with_ensure"
          ]
        }
      }
    },
    "require_apply": {
      "type": "boolean",
      "title": "Require Apply",
      "default": false,
      "description": "When true, emit port:\"error\" if nothing was labeled after all retries (instead of a silent success). Lets the caller drive a fallback branch (e.g. a notice + human task).",
      "displayOptions": {
        "show": {
          "operation": [
            "apply",
            "apply_with_ensure"
          ]
        }
      }
    },
    "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
        }
      }
    }
  },
  "required": [
    "connection_id",
    "operation"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "operation": {
      "type": "string"
    },
    "message_id": {
      "type": "string"
    },
    "internet_message_id": {
      "type": "string"
    },
    "conversation_id": {
      "type": "string"
    },
    "categories": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "category_color": {
      "type": "string"
    },
    "match_scope": {
      "type": "string",
      "enum": [
        "conversation",
        "message"
      ]
    },
    "mark_read": {
      "type": "boolean"
    },
    "resolve_max_attempts": {
      "type": "number"
    },
    "resolve_wait_ms": {
      "type": "number"
    },
    "require_apply": {
      "type": "boolean"
    }
  },
  "required": [
    "connection_id",
    "operation"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "object",
      "properties": {
        "operation": {
          "type": "string"
        },
        "message_id": {
          "type": "string"
        },
        "applied": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Categories newly added to the message."
        },
        "preserved": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Categories that were already on the message and were preserved."
        },
        "final_categories": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Final categories on the message after the operation."
        },
        "ensured": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Categories created in the master list."
        },
        "already_existed": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Categories that already existed in the master list."
        },
        "master_category_ensured": {
          "type": "boolean"
        },
        "conversation_id_resolved": {
          "type": "string",
          "description": "Thread id used to resolve messages (multi-mailbox mode)."
        },
        "messages_per_mailbox": {
          "type": "object",
          "description": "Count of messages labeled per mailbox."
        },
        "messages_read_by_mailbox": {
          "type": "object",
          "description": "Count of messages marked read (isRead:true) per mailbox, when mark_read is set."
        }
      }
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Success",
    "description": "Category operation completed successfully.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Operation failed (auth error, invalid message ID, API error).",
    "is_default": false,
    "supports_condition": true
  }
]
```
