# `Nous.Plugins.DecisionGuard`
[🔗](https://github.com/nyo16/nous/blob/v0.21.1/lib/nous/plugins/decision_guard.ex#L1)

Security guard backed by a `Nous.DecisionModel`: per-surface question packs
classify user input, tool calls, tool results and model output, and
probability bands turn the answers into allow / escalate / deny.

    agent = Nous.new("openai:gpt-4.1", plugins: [Nous.Plugins.DecisionGuard])

    Nous.run(agent, prompt,
      deps: %{
        decision_guard_config: %{
          model: "workers_ai:clef-flash",
          surfaces: [:user_input, :tool_call]
        }
      }
    )

## Surfaces

| Surface | Runs in | Pack | Deny means |
|---|---|---|---|
| `:user_input` (default) | plugin `before_request/3` | `Packs.UserInput` | the refused messages are redacted in place (`"[user message blocked by DecisionGuard]"`; the originals stay in the session log), an assistant refusal is added and no chat request is sent |
| `:tool_call` | `:pre_tool_use` hook | `Packs.ToolCall` | the tool never runs; the model is told the call was denied |
| `:tool_result` | `:post_tool_use` hook | `Packs.ToolResult` | the result is withheld from the model, history and callbacks |
| `:model_output` | `:post_response` hook (blocking) | `Packs.ModelOutput` | the run returns `{:error, %Nous.Errors.ResponseDenied{}}` |

The user-input surface runs `Nous.Plugins.InputGuard.Strategies.DecisionModel`
and (with `:pattern_ensemble`) `Nous.Plugins.InputGuard.Strategies.Pattern`
through `Nous.Plugins.InputGuard.Engine` under `:any`: a Pattern hit blocks
even when the model says safe. It checks every user message added since its
last check once, oldest first, including the initial prompt of
`Nous.run/3`. A step boundary can add several at once (an inbox batch);
the worst verdict wins, so one denied message refuses the whole batch.

"Since its last check" is tracked by session-log position (`Nous.Session.Log`
seqs), not by place in `ctx.messages`, so compaction cannot hide a message.
The marker lives in `ctx.deps` and carries over to the next run on the same
context (each `Nous.AgentServer` turn checks only its own input); on any
other context it does not apply and everything is checked again. If a
plugin wrote `ctx.messages` directly, so the list is not exactly the log's
projection, every user message in it is checked. A message is classified
on the text a provider will send: for a multimodal message, its
`metadata.content_parts` (see `Nous.Plugins.InputGuard.Engine.message_text/1`).
A refused batch is replaced by fresh messages (parts dropped), so it reaches
the model on no later turn either.

### Plugin order

Only user messages that exist when this plugin's `before_request/3` runs are
checked before the request:

  * list it **after** plugins that add user messages in `before_request/3`
    (`Nous.Plugins.LoopGuard`'s advisories), so their messages are checked
    too. LoopGuard's text is framework-written, so this is not enforced; a
    third-party plugin that adds user-role content needs the same placement;
  * list it **before** `Nous.Plugins.Summarization` (or any plugin that
    rewrites the transcript there): run the other way round, unchecked
    messages would be summarised first. With Summarization first, the run
    raises `ArgumentError`.

For example `plugins: [Nous.Plugins.LoopGuard, Nous.Plugins.DecisionGuard,
Nous.Plugins.Summarization]`.

The other surfaces are `:decision` hooks (`Nous.Hook.Decision`) contributed
through `c:Nous.Plugin.hooks/2` at priority **900** with `fail_closed:
true`, so they classify what earlier (lower-priority) hooks produced.

Only `:user_input` is on by default: on a laptop-local model every check
costs ~0.5–1 s, and tool results routinely need several chunks.

## Configuration (`deps[:decision_guard_config]`, map or keyword list)

  * `:model` — **required**. A `%Nous.DecisionModel{}` or a
    `Nous.DecisionModel.parse/2` string.
  * `:model_family` — inferred as `"clef"` when the model name contains
    "clef". Packs refuse default bands for any other family; pass
    per-surface `:bands` for every question then.
  * `:surfaces` — default `[:user_input]`. A list of surfaces, or a keyword
    list / map of `surface => opts` with per-surface overrides:
    `:questions` (`{:replace, qs}` or `{:extend, qs}`), `:bands`
    (`%{id => band}`), `:include`, `:preset`, `:on_escalate`, `:on_error`,
    `:oversize`, `:max_chunks`, `:timeout`, `:canary` and (tool surfaces)
    `:matcher`.
  * `:preset` — user-input band preset: `:balanced` (default) or `:strict`.
  * `:pattern_ensemble` — default `true`: run Pattern beside the model on
    user input.
  * `:canary` — default `false`. A separate canary call per check and
    chunk; a wrong answer floors the verdict at escalate. Weak evidence.
  * `:on_escalate` — what an escalation means:
    * user input: `(info -> :allow | :deny | {:edit, %{content: text}})`
      with `info = %{surface: :user_input, content, reason,
      probabilities}`; `{:edit, ...}` replaces the user message. Without a
      handler, an escalation blocks.
    * hook surfaces: as `Nous.Hook.Decision` (`info.event` names the
      event). Without a handler, `:tool_call` asks the run's approval
      handler (`Nous.Permissions.consult_handler/2`; none rejects) and the
      other surfaces deny.
  * `:on_error` — `:deny` (default), `:escalate` or `:allow`: what a
    decision-model error or timeout means, including a user-input strategy
    that exits (e.g. a llama.cpp process that is down) or is killed at its
    timeout.
  * `:oversize` — `:chunk` (default), `:suspicious` or `:head_tail`.
    **`:head_tail` never classifies the middle of the content**, so an
    injection placed mid-content is missed and nothing floors the verdict.
    It trades coverage for cost; do not use it where the middle matters.
  * `:max_chunks` — default 8.
  * `:timeout` — per decision-model call, in ms. Default `10_000`; size it
    for your backend (seconds for a laptop-local model).
  * `:skip_empty` — default `true`: blank user messages are not checked.

## Sub-agents

`:decision_guard_config` is confinement: `Nous.Plugins.SubAgent` always
forwards it (whatever `:sub_agent_shared_deps` says) and re-adds this plugin
to every sub-agent. A sub-agent template cannot loosen it; it can only add
hooks of its own, and those do not reach grandchildren.

## Limits

  * A guard verdict is a classifier's opinion, not a trust signal: an
    allowed input is not "trusted". Keep permissions, the sandbox and
    approvals in place.
  * It is a **text** classifier. Images, PDFs and other non-text binary
    attachments are **not** classified (visual or document prompt
    injection is out of scope); only their placeholder text is. An inline
    `text/*` attachment (an `:image` part with a `text/*` `media_type`, or
    a base64 `data:text/...` URL, which Gemini / Vertex AI send as a
    document) is decoded and classified. One larger than the model's window
    times `:max_chunks` (one byte per token), or that is not base64 or not
    UTF-8, is not decoded: the message is then at least `:on_error`.
  * `run_stream/3` does not invoke `before_request/3`, so the user-input
    surface does not apply there, and under `stream: true` a denied
    response's tokens were already streamed.
  * `Nous.Workflow` nodes are not covered: guard each `:agent_step` agent
    explicitly.

## Telemetry

  * `[:nous, :decision_guard, :verdict]` — every classified check.
    * Measurements: `%{duration: native_time, chunk_count: integer}`
    * Metadata: `%{surface, agent_name, tool_call_id, verdict, result,
      probabilities, canary_failed, error}`, with `verdict` one of `:allow`,
      `:escalate`, `:deny` and `result` one of `:allow`, `:deny`, `:modify`
      (after escalation). `tool_call_id` is the guarded call on the
      `:tool_call` / `:tool_result` surfaces and nil on `:user_input`.
  * `[:nous, :decision_guard, :canary_failed]` — a canary was answered
    wrongly. Measurements `%{count: integer}`, metadata `%{surface}`.
  * `[:nous, :decision_guard, :strategy_verdict]` — one user-input
    strategy's verdict (see `Nous.Plugins.InputGuard.Engine`).
  * `[:nous, :decision_guard, :strategy_dropped]` — a user-input strategy
    produced no verdict (see `Nous.Plugins.InputGuard.Engine`).

Every event also carries the run correlation keys (`trace_id`,
`agent_run_id`, `parent_agent_run_id`; see `Nous.Telemetry`). On hook
surfaces each check also emits `[:nous, :hook, :decision]` (hook name
`"decision_guard:<surface>"`); count verdicts on one of the two.

# `decision`

```elixir
@spec decision(
  map() | keyword(),
  :user_input | :tool_call | :tool_result | :model_output
) ::
  Nous.Hook.Decision.t()
```

The `Nous.Hook.Decision` this guard classifies `surface` with, built from a
`:decision_guard_config` (map or keyword list, as in `deps`) by the same
code the plugin runs: the guard as configured, not a re-derivation.

A surface the config does not list gets its default options. On
`:user_input` the decision is what `Strategies.DecisionModel` builds (with
the surface's `:on_error`); the plugin also runs `Strategies.Pattern` beside
it when `:pattern_ensemble` is on. Raises `ArgumentError` on an invalid
config, as the plugin does.

`Nous.Eval.Guard` records the guard's answers with
`Nous.Hook.Decision.verdict/3` (`record: :all_chunks`) and replays them
under candidate bands with `Nous.Hook.Decision.replay/2`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
