---
title: Contextualized Defense Instructing (CDI)
url: https://www.emergentmind.com/topics/contextualized-defense-instructing-cdi
type: topic
---

# Contextualized Defense Instructing (CDI)

Searching arXiv for the cited papers to ground the article in the current record.
Contextualized Defense Instructing (CDI) is a defense paradigm for LLM- and VLM-based agents in which defense is inserted into the agent’s working context as task-specific, state-dependent guidance, so that the next action is shaped proactively rather than merely constrained or vetoed after planning. In current arXiv literature, the idea appears in two closely related forms: exemplar-based in-context defense for computer-use agents facing context deception attacks, and instructor-model-based privacy guidance for tool-using LLM agents in multi-step execution [2503.09241; 2603.02983]. Across these formulations, CDI treats defense as a contextual policy encoded in the prompt-time or run-time context of the agent, with the explicit aim of preserving task performance while reducing deception or privacy failures.

## 1. Definition and conceptual scope

The term *Contextualized Defense Instructing* is used explicitly as a privacy defense paradigm in "Contextualized Privacy Defense for LLM Agents" [2603.02983]. In work on computer-use agents, the closely related mechanism called *in-context defense* is presented as a concrete instantiation of CDI: curated exemplars are embedded into the agent’s context so that the agent performs explicit defensive reasoning before action planning [2503.09241]. A third paper uses the acronym *CDI* differently, to denote *coherence-driven inference* in cybersecurity; that usage is terminologically distinct, although the supplied description presents it as relevant to explainable, context-sensitive acceptance or rejection of hypotheses and actions [2509.18520].

| Paper | CDI role | Agent setting |
|---|---|---|
| [2503.09241] | In-context defense as a concrete instantiation of CDI | VLM-powered computer agents under context deception attacks |
| [2603.02983] | Explicit CDI privacy defense paradigm | Tool-using LLM agents in multi-step communication tasks |
| [2509.18520] | CDI means coherence-driven inference | Cybersecurity inference over weighted coherence graphs |

In both primary CDI formulations, the central move is to replace generic safety instructions with contextualized guidance. In the computer-agent setting, this guidance is delivered through few-shot exemplars that encode a defensive procedure. In the privacy setting, it is delivered by a separate instructor model that observes the evolving trajectory and emits step-specific guidance. This shared structure distinguishes CDI from static prompting and from post-hoc blocking.

## 2. Formalization and intervention points in agent execution

The formalization in the computer-agent setting starts from a VLM that models a conditional distribution over actions given context. The input is denoted by \(Q\), the output action sequence or next action by \(A\), and the model by \(\Pr(A \mid Q)\). Under benign conditions, the objective is to choose an action \(A\) that aligns with the user’s intended task \(A_{\text{gold}}\). Under attack, the attacker modifies the original input \(Q\) into a deceptive input \(Q_{\text{malicious}}\), for example by adding a fake pop-up overlay or extra DOM nodes. The attack and defense objectives are given as [2503.09241]:
\[
\begin{aligned}
&\text{Untargeted Attack:} &&\min_{Q_{\text{malicious}}} \Pr(A_{\text{gold}} \mid Q_{\text{malicious}}) \\
&\text{Targeted Attack:} &&\max_{Q_{\text{malicious}}} \Pr(A_{\text{wrong}} \mid Q_{\text{malicious}})
\end{aligned}
\]
and, for the defender controlling in-context examples \(H\),
\[
\begin{aligned}
&\text{Defending Both:} &&\max_{H} \Pr(A_{\text{gold}} \mid Q_{\text{malicious}}, H) \\
&\text{Defending Targeted:} &&\min_{H} \Pr(A_{\text{wrong}} \mid Q_{\text{malicious}}, H).
\end{aligned}
\]

The privacy paper formulates the same general problem through a canonical agent loop. The sender agent maintains an accumulating context buffer
\[
C_{<t} = \{ p_0, u_1, (a_1, o_1), \dots, (a_t, o_t) \},
\]
where \(p_0\) is the system prompt, \(u_i\) are user messages, and \((a_i,o_i)\) are tool calls and their results. The next action is chosen as
\[
a_{t+1} = A(C_{<t}) = LM_A(p_0, \dots, u_t).
\]
Within this loop, the paper identifies three distinct intervention points [2603.02983]. Prompting modifies initialization,
\[
p_0 := p_0 + p_{\text{privacy}}.
\]
Guarding intervenes after planning but before execution,
\[
f_t = LM_G(C_{<t}, a_t) \in \{\text{ALLOW}, \text{BLOCK}\}.
\]
CDI intervenes after observation and before the next action. If the latest tool result is non-empty, the instructor model emits guidance
\[
h_t = LM_I(C_{<t}),
\]
which is appended to the context,
\[
\tilde{C}_{<t} = C_{<t} \cup \{h_t\},
\]
and the next action is drawn from the main agent model conditioned on this augmented context,
\[
a_{t+1} = LM_A(\tilde{C}_{<t}).
\]

This decomposition clarifies the distinctive claim of CDI. Prompting is global and static. Guarding is reactive and veto-oriented. CDI is post-observation and pre-action, so it can shape the next action as a safe alternative rather than merely blocking an unsafe one.

## 3. Exemplar-based CDI for computer-use agents

In the computer-agent literature, CDI is instantiated as *in-context defense* for computer-use agents powered by VLMs. These agents take screenshots, optional structured annotations such as SoM labels or HTML elements, and a user-specified task in natural language, and then produce actions such as clicking, typing, or selecting “None” in some setups [2503.09241]. The threat model is *context deception attacks*, defined as attacks that “introduce human-perceptible deceptive elements into the environment perceived by an agent to distract or manipulate its behavior.” The paper studies three categories: pop-up window attacks, Environment Injection Attacks (EIA), and Environmental Distraction Attacks (EDA).

The core mechanism is the addition of a small set of exemplars
\[
H = \{h_1, h_2, \ldots\} = \{(Q_1, A_1), (Q_2, A_2), \ldots\},
\]
including both defensive and benign cases. Each exemplar output is structured as
\[
A = \{ r_{\text{defense}}, r_{\text{action}}, a_{\text{gold}} \},
\]
where \(r_{\text{defense}}\) is explicit defensive chain-of-thought, \(r_{\text{action}}\) is optional action-planning chain-of-thought, and \(a_{\text{gold}}\) is the concrete action. The prompt structure described in the paper includes an input block with screenshot, annotations, and task, followed by an output block with a top-level `"Risk/Distraction Analysis:"` section, then a `"Plan"` or `"Action Plan"` section, and finally an `"Action"` command.

This structure is not incidental. The method enforces a two-stage process: first identify deceptive or distracting elements, then perform action planning conditioned on that analysis. The functional decomposition is stated schematically as
\[
r_{\text{defense}} = f_{\text{defense}}(Q_{\text{malicious}}, H),
\qquad
a_{\text{gold}} = f_{\text{plan}}(Q_{\text{malicious}}, H, r_{\text{defense}}).
\]
For pop-up attacks, the defensive reasoning explicitly marks overlay elements and their SoM IDs as suspicious and to be ignored. For EIA, the reasoning identifies ambiguous mappings between screenshot content and injected HTML options, and in the ambiguous case chooses the special safe action `“None of the other options match the correct element.”` For EDA, the reasoning identifies advertisements or recommendations as irrelevant relative to the user’s goal.

The paper reports nine defensive exemplar pairs total across attack types. VisualWebArena uses 3 defensive exemplars plus 3 benign exemplars; SeeAct uses 3 defensive plus 1 benign exemplar; the custom ads agent uses 3 defensive exemplars and no benign exemplar because the dataset lacked attack-free content. The quantity ablation shows that fewer than three exemplars are sufficient to induce defensive behavior. With 1 defensive exemplar plus 3 benign exemplars, ASR shrinks from 0.583 to 0.022; with 2 defensive exemplars, ASR is 0.047; with 3 defensive exemplars, ASR is 0.003 and SR improves to 0.458 [2503.09241].

## 4. Instructor-based CDI for privacy-preserving LLM agents

The privacy formulation generalizes CDI from exemplar-conditioned behavior to a distinct architectural component: a separate, lightweight instructor model \(LM_I\) that generates step-specific, context-aware privacy guidance during execution [2603.02983]. The setting is a multi-agent privacy simulator over communication applications such as Gmail, Messenger, and Facebook. Each privacy scenario contains a data subject, a data sender, and a data recipient. The subject’s personal information is partitioned into shareable items \(S\) and unshareable items \(U\), and the recipient’s task is explicitly to obtain both \(S\) and \(U\) from the sender.

The instructor observes the sender’s memory and dialogue history and outputs guidance in a structured JSON-like format:
```json
{
  "analysis": {
    "privacy_risk_analysis": "Your analysis of potential privacy risks here",
    "information_could_be_shared": "Your suggested information that could be shared here"
  },
  "instruction": "Your generated instruction here"
}
```
Only the `"instruction"` field is appended as the user message \(h_t\) to the sender’s context; the `"analysis"` is internal chain-of-thought. The intended behavioral effect is supervisory steering. Rather than telling the sender only that a proposed action is blocked, CDI can tell it what to share, what not to share, and how to formulate a selective disclosure response.

The paper’s qualitative cases emphasize mixed requests that combine shareable and unshareable information. In one example, the instructor says: “Share meeting time. Refuse to tell anything beyond coordination, like Emily’s ID number.” The sender then produces a mixed response that shares the meeting time and refuses the ID number, yielding \(PP = 1.0\), \(HS = 1.0\), and \(AD = 1.0\). In another case, after optimization, the instructor explicitly re-checks the social context and privacy norms and generates the instruction: “Decline the request to share Emily's credit score and home address. Only confirm QA time slots, event logistics.” The significance of CDI here is that the safe alternative is constructed before the next tool call is formed.

To optimize this instructor, the paper introduces an experience-driven RL framework. Failure trajectories with privacy violations are collected through adversarial prompt search. For CDI, the first guidance \(h_{t-1}\) that fails to prevent leakage in the next sender action is identified, the trajectory is truncated before that guidance, and the resulting context \(C_{<t-1}\) becomes an RL environment. The instructor samples a new guidance string
\[
h = LM_I(C_{<t-1}),
\]
the sender executes up to one action, and the reward is computed as Appropriate Disclosure:
\[
R_I(h) = AD(C_{<t-1}, h, (a,o)).
\]
The optimization objective is
\[
J(\theta) = \mathbb{E}_{C \sim \mathcal{D},\, h \sim \pi_\theta^{\text{ins}}(\cdot \mid C)}[R_I(h)].
\]

The reward design is based on three metrics. Let \(N_s\) be the total number of shareable items, \(N_u\) the total number of unshareable items, \(n_s\) the number of shareable items actually shared, and \(n_u\) the number of unshareable items actually shared. Then
\[
PP = 1 - \frac{n_u}{N_u}, \qquad
HS = \frac{n_s}{N_s}, \qquad
AD = \frac{2 \cdot n_s}{n_s + n_u + N_s}.
\]
The staged training schedule uses 400 steps with reward \(PP\) and 200 steps with reward \(AD\), implemented with GRPO and LoRA fine-tuning of Qwen3‑4B at rank \(32\), learning rate \(2 \times 10^{-5}\), batch size \(4\), gradient accumulation \(4\), max context length 5200 tokens, and max generation 2048 tokens [2603.02983].

## 5. Empirical findings, baselines, and design regularities

The empirical claims across the two primary papers are consistent on the central comparison: CDI performs better than static prompting and avoids the characteristic pathologies of reactive guarding. In the computer-agent study, prompting-only defense is reported as inconsistent and often harmful. For pop-up attacks, ASR goes from 0.583 to 0.538 with prompting-only defense and SR stays at 0.417. For EIA, prompting-only defense increases ASR in all three variants: EI (text) 0.415 to 0.433, EI (aria) 0.427 to 0.456, and MI 0.427 to 0.526, while SR decreases notably for EIA-MI from 0.462 to 0.386. By contrast, in-context defense reduces pop-up ASR from 0.583 to 0.051, reduces EIA ASR to 0.117, 0.170, and 0.035 across EI (text), EI (aria), and MI, and achieves 100% successful defenses against distracting advertisements, with AD1, AD2, and AD3 ASR all reduced to 0.000 [2503.09241].

The same paper also isolates two design regularities. First, defensive reasoning must precede action planning. The reasoning-order ablation shows planning-first yields ASR 0.057, whereas defense-first yields ASR 0.003. Second, defensive exemplars, not merely chain-of-thought prompting, are critical. Without defensive exemplars, pop-up ASR only drops from 0.583 to 0.553, and EIA ASR increases in some settings. The backbone ablation further indicates that the defense is backbone-agnostic in the reported experiments: pop-up ASR with defense is 0.051 for GPT-4o, 0.052 for Gemini 1.5 Pro, and 0.071 for Claude 3.5 Sonnet. In-distribution exemplars remain stronger than out-of-distribution ones: ASR 0.003 for IND versus 0.064 for OOD exemplars.

In the privacy study, the baseline no-defense sender is characterized by low privacy preservation and high helpfulness: \(PP = 35.5\%\), \(HS = 81.2\%\), \(AD = 66.1\%\). Unoptimized prompting reaches \(PP=48.1\), \(HS=73.1\), \(AD=65.0\) before attack, but after strategic attack \(PP\) collapses to \(11.8\) while \(HS\) rises to \(94.1\). Unoptimized guarding averages \(PP=47.0\), \(HS=82.0\), \(AD=70.0\) before attack and \(PP=19.6\), \(HS=89.8\), \(AD=66.5\) after attack. Unoptimized CDI averages \(PP=75.9\), \(HS=86.9\), \(AD=82.8\) before attack and remains best after attack at \(PP=38.1\), \(HS=89.8\), \(AD=71.4\) [2603.02983].

After optimization, the privacy results sharpen. On unseen test configurations, optimized prompting achieves \(PP = 85.1\%\), \(HS = 82.7\%\), \(AD = 83.8\%\); optimized guarding achieves \(PP = 83.6\%\), \(HS = 69.0\%\), \(AD = 74.8\%\); optimized CDI achieves \(PP = 94.2\%\), \(HS = 80.6\%\), \(AD = 86.5\%\). Under adversarial retraining scenarios, optimized CDI reports \(PP = 79.5\%\), \(HS = 84.5\%\), \(AD = 82.4\%\). Cross-backbone evaluation shows particularly strong gains for weaker agents: on gpt‑4.1‑nano, AD is 59.3 with no defense, 64.9 with prompting, 56.8 with guarding, and 90.4 with CDI. The paper’s interpretation is that CDI is agent-agnostic guidance that offloads complex privacy reasoning to the instructor.

A plausible unifying implication is that CDI works best when the defense module specifies a *selective alternative* rather than a blanket refusal. In the computer-agent setting, this takes the form “ignore the pop-up; click the task-relevant target.” In the privacy setting, it takes the form “share coordination-oriented information; refuse the sensitive fields.” That pattern is directly opposed to the failure mode of guarding, which often produces block–resend loops and over-blocking.

## 6. Terminological boundaries, limitations, and open directions

A recurrent source of confusion is the acronym *CDI* itself. In "Coherence-driven inference for cybersecurity," CDI denotes a Thagard-style coherence model in which propositions are vertices of a weighted graph, edge weights lie in \([-1,1]\), and the acceptance or rejection of propositions is formulated as a MAX-CUT problem maximizing
\[
C(U) = -\sum_{u \in U,\ v \notin U} A_{uv}.
\]
That paper explicitly does not use *Contextualized Defense Instructing* as its term. Its relation to CDI in the defense-instructing sense is therefore adjacent rather than identical [2509.18520]. A plausible implication is that coherence-driven inference could serve as an upstream reasoning layer for selecting accepted hypotheses and candidate actions before a separate instruction generator produces contextualized defensive guidance.

The primary limitations of CDI as currently studied are practical and distributional rather than conceptual. In the computer-agent setting, multiple exemplars increase prompt size and first-round inference cost; output format adherence can be imperfect; residual failures remain under OOD attacks or when reasoning order is wrong; and novel UI patterns or attack types may require dynamic exemplar selection or regular exemplar updates [2503.09241]. In the privacy setting, optimization depends on a curated set of attack-induced failure trajectories; evaluation is centered on communication apps and social, health, and finance scenarios; a separate instructor model and RL training increase complexity relative to static prompts; and only the instructor or guard is trained, while the main agent remains frozen [2603.02983].

The open directions proposed in the literature follow from these limitations. For computer agents, the supplied description points to dynamic exemplar selection, integration with external detectors such as UI anomaly detectors or HTML parsers, better UI grounding, prompt caching, and stronger output schemas. For privacy agents, the paper highlights more nuanced privacy–utility tradeoffs, extension to other safety domains such as security, fairness, and hallucination control, and broader simulation environments such as collaborative document editing, web browsing, and multi-agent collaboration. Taken together, these directions suggest that CDI is best understood not as a single prompt template but as an intervention family for context-sensitive control of agent behavior under adversarial or norm-sensitive conditions [2503.09241; 2603.02983].

Source: https://www.emergentmind.com/topics/contextualized-defense-instructing-cdi