# Content Safety Scan

> Escáner de seguridad multimodal integral (texto e imagen).

Source: https://docs.sommatic.ai/es/nodes/ai.safety.scan/

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

Escáner de seguridad multimodal integral (texto e imagen).

Es una versión más amplia de Safety Filter, diseñada para analizar payloads multimodales y cumplir los requisitos de seguridad en producción.

**Revisiones:**
- Detección de PII (básica).
- Toxicidad y discurso de odio.
- Detección de inyección de prompts.

## Configuración

- `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.
- `invocation_mode` (string, opcional): Transporte de la llamada al LLM. `sync` se bloquea hasta recibir la respuesta completa. `stream` consume los tokens mediante SSE (necesario para generaciones largas). 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 tiempo máximo de inactividad entre fragmentos en modo stream). Predeterminado: 30000 en sync, 600000 en stream.
- `check_toxicity` (boolean, opcional): Detecta odio, acoso y violencia. Por defecto: `true`.
- `check_pii` (boolean, opcional): Detecta información de identificación personal. Por defecto: `false`.
- `check_injection` (boolean, opcional): Detecta intentos de eludir las restricciones. Por defecto: `true`.
- `check_sexual` (boolean, opcional): Detecta contenido explícito o sugerente. Por defecto: `false`.

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

- `pass` (por defecto): Pass
- `fail`: Fail
- `error`: Error

## Contrato de entrada

- `content` (string, obligatorio): Contenido que se analiza.

## Contrato de salida

- `passed` (boolean, opcional)
- `report` (object, opcional)

## En expresiones

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

- `$("Content Safety Scan").item.json.passed` (boolean) = `true`
- `$("Content Safety Scan").item.json.report` (object) = `{…}`
- `$("Content Safety Scan").item.json.report.flagged_categories` (array) = `[…] (0)` (El editor no la sugiere)
- `$("Content Safety Scan").item.json.report.confidence` (number) = `0.97` (El editor no la sugiere)
- `$("Content Safety Scan").item.json.report.active_checks` (array) = `[…] (2)` (El editor no la sugiere)
- `$("Content Safety Scan").item.json.report.modality` (string) = `"text"` (El editor no la sugiere)
- `$("Content Safety Scan").item.json.report.raw` (object) = `{…}` (El editor no la sugiere)


## Cómo funciona

Clasifica un texto y/o una imagen con el LLM según los controles de seguridad activos (toxicidad, inyección de prompt, contenido sexual, datos personales) y enruta a `pass` o `fail`. Una petición bloqueada por el filtro de contenido del propio proveedor también cuenta como `fail`.

1. Resuelve la configuración del nodo: las expresiones de las claves de configuración se evalúan contra la ejecución; el ítem entrante se usa tal cual.
2. Lee el texto del ítem entrante: `content`; si no, `input`; si no, el propio ítem cuando es un texto. Lee una `image` opcional del ítem. Si no hay ninguno de los dos, devuelve `error`.
3. Construye los controles activos: `check_toxicity` (odio, acoso, violencia) y `check_injection` (inyección de prompt) están activos salvo que valgan `false`; `check_sexual` y `check_pii` solo cuando valen `true`.
4. Prepara la imagen: un URI `data:` se usa tal cual, una URL `http(s)` se descarga (tiempo límite de 10 s) y se incrusta en base64, y cualquier otro texto se trata como JPEG en base64.
5. Llama al LLM a través del backend con el registro `llm_provider_id`. `invocation_mode: "sync"` (predeterminado) espera la respuesta completa; `"stream"` la lee por SSE y une los fragmentos.
6. Toma el primer bloque `{…}` de la respuesta (temperatura 0) y solo marca el resultado por categorías que pertenezcan a los controles activos. Cualquiera de ellas → `fail`; ninguna → `pass`.
7. Si la llamada al LLM falla con un mensaje que coincide con `filtered`, `content management` o `content polic…`, devuelve `fail` con todas las categorías activas y `_filter_source: "provider_content_policy"`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-safety-scan",
  "label": "Scan user message",
  "operator_slug": "ai.safety.scan",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "check_toxicity": true,
    "check_injection": true,
    "check_sexual": false,
    "check_pii": false
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "pass",
  "data": {
    "passed": true,
    "report": {
      "flagged_categories": [],
      "confidence": 0.97,
      "active_checks": [
        "toxicity",
        "injection"
      ],
      "modality": "text",
      "raw": {
        "flagged": false,
        "confidence": 0.97,
        "categories": {
          "hate": false,
          "harassment": false,
          "violence": false,
          "prompt-injection": false,
          "sexual": false,
          "pii": false
        }
      }
    }
  }
}
```

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

### `pass`

No se marcó ninguna categoría activa.

```json
{
  "passed": true,
  "report": {
    "flagged_categories": [],
    "confidence": 0.97,
    "active_checks": [
      "toxicity",
      "injection"
    ],
    "modality": "text",
    "raw": {
      "flagged": false,
      "confidence": 0.97,
      "categories": {
        "hate": false,
        "harassment": false,
        "violence": false,
        "prompt-injection": false,
        "sexual": false,
        "pii": false
      }
    }
  }
}
```

### `fail`

Se marcó una categoría activa, o el filtro de contenido del proveedor bloqueó la petición. En el segundo caso `report` incluye `_filter_source` y no tiene `raw`.

```json
{
  "passed": false,
  "report": {
    "flagged_categories": [
      "prompt-injection"
    ],
    "confidence": 0.9,
    "active_checks": [
      "toxicity",
      "injection"
    ],
    "modality": "text",
    "raw": {
      "flagged": true,
      "confidence": 0.9,
      "categories": {
        "hate": false,
        "harassment": false,
        "violence": false,
        "prompt-injection": true,
        "sexual": false,
        "pii": false
      }
    }
  }
}
```

### `error`

Falló la validación, la llamada al LLM o la interpretación. `data` es `{ error }` (más `response` cuando el backend devolvió un cuerpo).

```json
{
  "error": "Missing input: provide 'content', 'input', or 'image'"
}
```

## Comportamiento en el código

- `llm_provider_id`: Es obligatorio en ejecución aunque el esquema no lo marque como requerido. Es el id de un registro de proveedor LLM; el backend resuelve a partir de él el endpoint, el despliegue y las credenciales.
- `check_toxicity / check_injection / check_sexual / check_pii`: Con los cuatro desactivados, se usa el arreglo antiguo `checks` (p. ej. `["pii"]`) si existe; si no, se evalúan todas las categorías y `active_checks` vale `"all"`. Por tanto, desactivarlo todo analiza todo.
- `timeout_ms`: `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing input: provide 'content', 'input', or 'image'` | `error` | El ítem entrante no tiene `content`, `input` ni `image`, y no es un texto. Estas claves solo se leen del ítem entrante, no de la configuración del nodo. |
| `Safety scan response could not be parsed` | `error` | La respuesta no tenía ningún bloque `{…}`. |
| `<JSON.parse error>` | `error` | El bloque `{…}` de la respuesta no es JSON válido. |
| `<image download error>` | `error` | La URL de la imagen no se pudo descargar en 10 s. |
| `[AiSafetyScan] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | El nodo no tiene `llm_provider_id`. Elige un proveedor LLM en la configuración del nodo; la clave antigua `model_id` no se acepta. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada (registro de proveedor desconocido o inactivo, error del proveedor, credenciales). Revisa el registro del proveedor. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | No se pudo contactar con el backend o no devolvió nada en modo `sync`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | En modo `stream` no llegó ningún fragmento dentro de `timeout_ms`. |

## Notas y límites

- Para imágenes el modelo debe aceptar entrada multimodal; el mensaje de usuario se envía como una parte de texto más una parte `image_url`.
- Las URL de imagen se descargan desde el host del orquestador, así que deben ser accesibles desde él.
- `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.
- En modo `stream` la temperatura que fija este nodo no se envía al proveedor, y `raw` es `null`.
- El motor no aplica `execution.retryOnFail`, `maxTries`, `waitBetweenTries` ni `continueOnFail` a este nodo. Gestiona los fallos conectando el puerto `error`.


## Contratos (JSON Schema)

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

```json
{
  "slug": "ai.safety.scan",
  "name": "Content Safety Scan",
  "category": "ai",
  "version": "1.0.0",
  "description": "Comprehensive multi-modal safety scanner (Text/Image).\n\n  This is a broader version of the Safety Filter, designed for analyzing multimodal payloads for production safety compliance.\n\n  **Checks:**\n  - PII Detection (Basic).\n  - Toxicity/Hate Speech.\n  - Prompt Injection Detection.",
  "capabilities": [
    "safety",
    "security",
    "scan"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "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.",
        "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` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). 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 idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "check_toxicity": {
        "type": "boolean",
        "title": "Toxicity/Hate Speech",
        "description": "Detect hate, harassment, and violence.",
        "default": true
      },
      "check_pii": {
        "type": "boolean",
        "title": "PII Detection",
        "description": "Detect personally identifiable information.",
        "default": false
      },
      "check_injection": {
        "type": "boolean",
        "title": "Prompt Injection",
        "description": "Detect attempts to bypass constraints.",
        "default": true
      },
      "check_sexual": {
        "type": "boolean",
        "title": "Sexual Content",
        "description": "Detect explicit or suggestive content.",
        "default": false
      },
      "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",
    "properties": {
      "content": {
        "type": "string",
        "description": "Content to scan."
      }
    },
    "required": [
      "content"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "passed": {
        "type": "boolean"
      },
      "report": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "pass",
      "label": "Pass",
      "is_default": true
    },
    {
      "port_id": "fail",
      "label": "Fail"
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "safety",
    "scan",
    "security"
  ],
  "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": {
    "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.",
      "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` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). 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 idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
      "minimum": 1000
    },
    "check_toxicity": {
      "type": "boolean",
      "title": "Toxicity/Hate Speech",
      "description": "Detect hate, harassment, and violence.",
      "default": true
    },
    "check_pii": {
      "type": "boolean",
      "title": "PII Detection",
      "description": "Detect personally identifiable information.",
      "default": false
    },
    "check_injection": {
      "type": "boolean",
      "title": "Prompt Injection",
      "description": "Detect attempts to bypass constraints.",
      "default": true
    },
    "check_sexual": {
      "type": "boolean",
      "title": "Sexual Content",
      "description": "Detect explicit or suggestive content.",
      "default": false
    },
    "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",
  "properties": {
    "content": {
      "type": "string",
      "description": "Content to scan."
    }
  },
  "required": [
    "content"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "passed": {
      "type": "boolean"
    },
    "report": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "pass",
    "label": "Pass",
    "is_default": true
  },
  {
    "port_id": "fail",
    "label": "Fail"
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
