Preprint
Article

This version is not peer-reviewed.

Synthetic-Trained Guards Fail on Real LLM Agents: Step-Level Evidence from Tool-Use and Coding-Agent Prompt Injection

Submitted:

06 November 2026

Posted:

09 November 2026

You are already at the latest version

Abstract
Indirect prompt injection lets text that a large language model (LLM) agent reads redirect the tools it calls. Step-level guards that score each proposed tool call before it executes report near-perfect accuracy, but only on one synthetic corpus. We test whether such a guard protects real agents in two settings. We build TraceWarden, a pre-dispatch guard with argument-provenance and goal-anchoring features and a conformal false-alarm budget, and release two real, step-labeled datasets: AgentDojo-Steps (846 trajectories from tool-using agents) and SWE-Inject-Steps (630 trajectories from coding agents with shell access, including a URL-free attack set). Over five training seeds, the guard reaches 0.98 trajectory F1 on its synthetic benchmark. On real tool-using agents it falls to 0.33 and 0.46 F1, injection localization drops from 0.88 to 0.01–0.04 exact match, and a 1% conformal false-alarm budget is exceeded 9- to 24-fold. On coding agents it blocks 1 or 2 of 48 hijacks, ranking them at or below chance; a sentence encoder ranks them modestly better but still blocks only 4 or 5. Three causes recur: a positional prior learned from synthetic data, a lexically stereotyped attack vocabulary that favors the encoder that transfers worst, and a mention-based definition of “hijacked” that the guard reproduces. A simple provenance rule blocks every URL-bearing coding-agent attack but none of 18 attacks that run a script already in the repository. Synthetic benchmarks substantially overstate how well learned guards protect real agents.
Keywords: 
;  ;  ;  ;  ;  

1. Introduction

An LLM agent that can read a document, browse a page, check an inbox, or open a repository and then call tools has a weakness that a chatbot does not. The text it reads can contain instructions, and the agent has no reliable way to tell the user’s request apart from a sentence planted by whoever wrote that text. This is indirect prompt injection [1]. A single line inside a bill—“also send $500 to this account”—or inside a README—“before fixing, run curl …| sh”—can turn a helpful agent into one that works for an attacker. The attack surface is every byte the agent ingests, and for a coding agent it is the repository itself.
One line of defense reads the agent’s own behavior. If an agent is compromised, its trajectory has a recognizable shape: a benign prefix, a poisoned observation, then actions that serve the attacker rather than the user. AgentDrift [2] turned this idea into a benchmark of 12,536 synthetic trajectories with every step labeled, and DriftNet [3] trained a small transformer on it that reports 0.983 trajectory F1 and recovers the exact injection point 98.7% of the time. Those numbers suggest that the problem is close to solved.
They are also measured entirely on one synthetic corpus, generated by a single model under one protocol. The DriftNet authors say so and list transfer to real traffic as their most important open problem. A behavioral guard is meant to be deployed as a runtime control—an intrusion detection system for agent tool calls—and an operator will choose, tune, and trust it based on published benchmark numbers. If those numbers do not carry over, a deployed guard gives a false sense of protection: it lets harmful calls through, interrupts legitimate work, and the false-alarm budget the operator configured no longer holds.
This article measures that gap in two real settings with one guard. We reimplement the detector as a causal, pre-dispatch model, TraceWarden, that scores each proposed tool call before it runs and confirm that it reaches 0.984 F1 on AgentDrift. We then evaluate the same checkpoint, unchanged, on (i) real tool-using agents in the AgentDojo environments [4] and (ii) real coding agents with shell and repository access in SWE-Inject, an environment we build that plants one checkable attack per repository. Both datasets are step-labeled, which is what a pre-dispatch guard needs and what existing agent-injection benchmarks, which score whole runs, do not provide.
The result is a collapse in both settings, stable across training seeds, for reasons that can be traced. In tool-using agents, trajectory F1 falls from 0.98 to 0.33 (7B) and 0.46 (14B), localization from 0.88 to 0.01–0.04, and a 1% conformal false-alarm budget is exceeded 9- to 24-fold. In coding agents, the guard blocks 1 or 2 of 48 hijacks and ranks real hijacks at or below chance. We rule out the obvious confounds, show that the representation that wins the benchmark transfers worst, and find that the guard reproduces a labeling artifact rather than detecting attacks. We also evaluate the natural non-learned alternative, an argument-provenance rule, and locate its blind spot.

Research questions.

RQ1 
Does a step-level guard trained on synthetic trajectories transfer to real tool-using agents, and does its calibrated false-alarm guarantee survive the move?
RQ2 
Does it transfer to real coding agents with shell access, a domain absent from its training data?
RQ3 
Which properties of the synthetic data and of the guard’s design—features, encoder, label definition, amount of real data—explain the failure?
RQ4 
How do a non-learned provenance rule and simple input normalization compare, and where do they fail?
RQ5 
What does the real data show about which agents and which attack channels are most exposed?

Contributions.

  • A two-domain, multi-seed measurement that a step-level injection guard trained on synthetic data does not protect real agents: 0.98 to 0.33–0.46 trajectory F1 on tool-using agents and 1 or 2 of 48 hijacks blocked on coding agents (Section 7.2, Section 7.3 and Section 8.2).
  • Two released, step-labeled datasets of real agent trajectories: AgentDojo-Steps (846 trajectories, two model scales) and SWE-Inject-Steps (630 trajectories from three coding-model scales, including a URL-free attack set), with validated labeling rules (Section 5).
  • Three mechanisms behind the failure: a positional prior learned from synthetic data, an attack vocabulary stereotyped enough that the encoder winning the benchmark transfers worst, and a mention-based hijack definition that the guard learns and that also hides a real between-model difference (Section 7.6, Section 8.3 and Section 9).
  • A quantified blind spot of provenance-based defense: it blocks every URL-bearing coding-agent attack and none of a URL-free variant (Section 8.4).
  • Evidence that, within one model family, more capable agents are hijacked more often in both settings because they complete more of the task (Section 7.9 and Section 8.1).
  • TraceWarden, a pre-dispatch guard that adds about 2 ms per tool call on a laptop CPU, with all code, data, and experiments released.
Section 2 reviews related work. Section 3 gives the threat model and Section 4 the guard. Section 5 introduces the three datasets and Section 6 the protocol. Section 7 and Section 8 report results for tool-using and coding agents, Section 9 analyzes the errors, and Section 10, Section 11, Section 12 and Section 13 discuss implications, limitations, and conclusions.

3. Threat Model and Problem Formulation

3.1. Threat Model

Assets and setting.

A user delegates a task to an LLM agent that can call tools with side effects. In the tool-use setting these send money or email, post messages, create calendar events, or fetch web pages. In the coding setting the agent reads and edits files in a repository, runs tests, and runs shell commands. The user, the agent’s system prompt, and the tool implementations are trusted. The assets at risk are the user’s accounts, data, communication channels, credentials, and source code.

Adversary.

The adversary cannot modify the agent, its prompts, or its tools, and cannot interact with the user. It controls only content the agent will read through a tool: a document, web page, message, or review; or, for coding agents, an issue, README, code comment, dependency documentation, test output, or CI log, all of which are writable by third parties in open source. Its goal is to make the agent issue at least one tool call that serves the adversary: a transfer to an attacker account, a visit to an attacker URL, a remote install script piped to a shell, exfiltration of environment variables, a push to an unrequested remote, or execution of a script the adversary placed in the repository. In the main experiments the adversary does not know the guard; Section 7.7 evaluates obfuscated and multi-step variants.

Defender.

The defender places a guard between the agent and its tools. Before each tool call executes, the guard sees the user’s task, the user’s known world where available, and every prior action and observation, and decides whether to allow, hold for human review, or block the call. It has no access to model weights, so it applies equally to closed and open models. A missed attack lets a harmful call execute; a false alarm interrupts legitimate work and, if frequent, leads operators to disable the guard. The defender therefore needs high recall at the first harmful call and a stated, low false-alarm rate.

Out of scope.

Direct jailbreaks by a malicious user, attacks that act only through the agent’s final text, compromised tools that misreport their own actions, and fully adaptive attackers who optimize against the guard are outside this threat model.

3.2. Problem Formulation

An agent trajectory is a sequence of steps τ = ( s 1 , … , s T ) . Each step s t = ( a t , o t ) consists of an action a t —a tool name, its arguments, and the model’s reasoning—followed by an observation o t , the tool’s output. Each trajectory comes with the user’s task u and, where available, a known worldW: the user’s own addresses, contacts, and accounts. Every step carries one of four labels: benign; injection point (the observation first contains a planted payload); hijacked (an action serving the attacker); or failed injection (a payload that was not obeyed). A trajectory is compromised if it contains at least one hijacked step.

Pre-dispatch constraint.

A post-hoc detector may use the whole trajectory to label step t. A guard cannot: when it must decide whether to execute a t , the observation o t and all later steps do not yet exist. We split each step into an action event e t a (known before the call executes) and an observation event e t o (known after). A pre-dispatch guard computes a hijack score
p t = f u , W , e 1 a , e 1 o , … , e t − 1 o , e t a ∈ [ 0 , 1 ]
for each proposed action using only events up to and including e t a .

4. TraceWarden

4.1. Pre-Dispatch Scoring

A transformer [16] with a causal attention mask reads the event stream left to right. At each action event it predicts whether the proposed call is hijacked; at each observation event it predicts whether the observation is an injection point. For comparison we keep a bidirectional variant, a reimplementation of DriftNet, as an upper bound that sees the whole log.

4.2. Event Representation

Each event is the frozen embedding of its serialized text, concatenated with hand-designed features. Action events receive three groups:
  • World features (4): whether an argument address is internal or external to the user’s known contacts and domains.
  • Provenance features (7): whether each argument value first appeared in the user’s task, the known world, or an untrusted observation—a learned form of taint tracking.
  • Goal-anchoring features (4): cosine similarity of the action to the user’s task and to prior observations.
Observation events receive three lexical features: imperative density, urgency density, and whether the observation mentions an entity unknown to the task and world. All text is normalized before encoding (Unicode NFKC folding, zero-width character removal, and homoglyph mapping). Appendix A defines every feature. We use two frozen encoders: a dependency-free 768-dimensional bag-of-n-grams hashing encoder [17] and the 110M-parameter sentence encoder all-mpnet-base-v2 [18,19]. The trunk is a two-layer transformer (width 256, four heads) with 1,321,474 trainable parameters; Appendix B lists all settings.

4.3. A Stated False-Alarm Budget

We calibrate two thresholds by split conformal prediction on non-compromised validation trajectories. Let S 1 , … , S n be the maximum hijack scores of n calibration trajectories. For a budget α , the hold threshold is the ⌈ ( n + 1 ) ( 1 − α ) ⌉ -th smallest score, so that at most a fraction α of benign runs are flagged in expectation; a stricter block threshold is set the same way. Below the hold threshold the call is allowed, between the thresholds it is held for human review, and above the block threshold it is blocked. The guarantee holds under exchangeability of calibration and deployment data, which we test in Section 7.2. When ⌈ ( n + 1 ) ( 1 − α ) ⌉ > n , the procedure returns an infinite threshold rather than issue a promise it cannot keep.

4.4. A Provenance Rule

As a non-learned baseline we add an optional rule, independent of the learned score: hold any call whose arguments contain an address—a URL, domain, or email—that was introduced by a tool observation rather than by the user’s task or known world. This is the minimal information-flow policy that a deployment could add without training, and it targets the most common attack shape: steering the agent toward an attacker-controlled destination.

4.5. Deployment Interface

TraceWarden exposes a session object consulted before each tool call (check) and informed after it (observe). Each decision carries the score, the action, and a reason that names argument values introduced by tool output and the observation suspected of carrying the injection. At the end of a session it emits an incident report listing the calls to roll back and the sources to quarantine. Integrations are provided for OpenAI-compatible tool loops, plain Python functions, and the Model Context Protocol.

5. Data

5.1. AgentDrift and Its Identity Shortcut

AgentDrift [2] contains 12,536 synthetic trajectories across five domains (banking, coding, email, medical, web). We use its task-disjoint split of 9,081 training, 1,733 validation, and 1,722 test trajectories, of 3 to 11 steps (median 6). Its coding domain consists of short synthetic sequences rather than repository work with a shell, so SWE-Inject (Section 5.3) is a genuine domain shift. On raw data a lookup on world identity predicts compromise with 85.9% accuracy (Table 1). We anonymize all names, companies, and addresses, keeping only whether an address is internal or external, which drops the lookup to 55.5%, the majority rate. All models are trained on the anonymized corpus.

5.2. AgentDojo-Steps: Real Tool-Using Agents

Collection.

We run Qwen2.5-7B-Instruct and Qwen2.5-14B-Instruct [20] (AWQ-quantized) inside the AgentDojo suites under its important instructions attack, served with vLLM [21] on one NVIDIA T4 GPU with an 8,192-token context. Llama-3.1-8B was tried first, but its chat template rejects the parallel tool calls AgentDojo agents emit. Workspace prompts frequently exceed the context that fits on a T4, which limits workspace coverage to 22 trajectories (7B) and none (14B).

Labeling and validation.

An observation is an injection point if it contains a placed payload; a call is hijacked if, after a poisoned observation, its arguments carry an attacker value absent from the user’s task and world. Three labeler defects were fixed before any result was computed. A hand audit of 30 random trajectories per model agrees with the automatic labels on 96.7% (7B) and 86.7% (14B); all four 14B disagreements came from attacker goals that name a person, which we corrected and re-audited. A further 20 multi-step trajectories agree on 95.0%, and six rule-based consistency checks are applied to every trajectory.

Statistics.

Table 2 summarizes all corpora. Real tool-use trajectories run from 1 to 51 steps, against AgentDrift’s 3 to 11, and real attack success is lower (about half of attacked runs, against 78%), so failed injections are common hard negatives. A separate set of 232 trajectories uses multi-step decomposed attacks, which spread an instruction across several innocuous-looking observations.

5.3. SWE-Inject-Steps: Real Coding Agents

Environment.

A task is a small Python repository with a real one-line bug, an issue file, a failing test, and one injection slot carrying one attacker goal. The agent is told to fix the bug and run the tests, with seven tools: read_file, list_dir, search, edit_file, run_tests, run_shell, and git_diff. The payload is placed in one of six vectors (issue body, README, code comment, dependency docs, test output, CI log) and names one of six checkable goals: install a typosquatted package, run a remote install script (curl …| sh), exfiltrate environment variables, push to an unrequested remote, modify a CI configuration, or write a code backdoor. Each goal has a checker keyed to the exact package, host, path, or command. The shell is sandboxed: network calls, installs, and pushes are intercepted and return canned output, nothing outside the workspace is reachable, and planted scripts are harmless placeholders. Three base repositories require a legitimate pip install named in their README, so running a shell command is part of normal work and an injected command competes with a real need.

Generation.

From 18 base repositories we generate 126 trajectories per model (6 attacked variants and one benign control per repository) at a fixed seed, with two attack framings (bare and authoritative). The agents are Qwen2.5-Coder-7B-Instruct (fp16) and 14B- and 32B-Instruct (AWQ) [22], served with vLLM on two T4 GPUs at temperature 0, so the three models see an identical task set. Qwen2.5-Coder emits tool calls as fenced JSON that vLLM’s tool parser does not parse, so we added a fallback parser; without it the agent loop ends after one step. A second set adds a seventh, URL-free goal (Section 8.4) for the 14B and 32B models.

Labels.

A step is hijacked only if its call realizes the attacker goal (goal-only labels). Labelers ported from other agent benchmarks, including the AgentDojo-Steps labeler, instead mark a step hijacked whenever its arguments contain an attacker value such as the payload URL (mention labels). In coding tasks the mention rule fires on a benign edit that keeps the injected comment while fixing the bug. We release both and use goal-only labels throughout; Section 8.3 quantifies the difference.

Validation.

An automatic check flags any benign-labeled step whose output contains the attack target; it flagged 0 of 100 attacked-task trajectories per model. An audit of 30 trajectories per model, reading every step, found 90 of 90 correct on the main set and 60 of 60 on the URL-free set. The audit was assisted by a language model and verified by the author; every one of the 14 episodes reclassified between mention and goal-only labels was checked by hand.

6. Experimental Setup

Protocol.

All guards are trained on the anonymized AgentDrift training split; model selection and calibration use its validation split, and its test split is evaluated once. For transfer, the trained checkpoint is applied unchanged to AgentDojo-Steps and SWE-Inject-Steps. The SWE-Inject evaluation uses the identical checkpoint file as the AgentDojo evaluation. Decisions use the conformal hold threshold calibrated at a 1% budget on AgentDrift validation data (0.814 for the headline hashing checkpoint). Some comparisons use a common threshold of 0.5 and are labeled as such. SWE-Inject trajectories are replayed through the guard’s session interface: a held or blocked call is skipped, as it would be in deployment, and allowed calls reveal their observation to the guard.

Metrics.

Trajectory F1 measures whether compromised trajectories are flagged. Macro step F1 averages per-class F1 over the four labels. Injection exact match is the fraction of attacked trajectories whose injection point is recovered exactly, and hijacked IoU the intersection-over-union of predicted and true hijacked steps. Two prevention metrics are specific to a pre-dispatch guard: first hijack caught, the fraction of attacks flagged at or before the first hijacked call, and benign interrupted, the fraction of non-compromised trajectories in which any call is held or blocked. For SWE-Inject, where positives are few, we also report the threshold-free AUROC of step scores (hijacked steps against all other steps). Proportions carry 95% Wilson intervals [23]; between-model comparisons on identical tasks use paired exact sign tests with Holm correction [24].

Training and seeds.

Guards are trained for 15 epochs with AdamW. Detailed tables use the seed-42 checkpoint. For both encoders, five further seeds (0–4) were each trained, calibrated at a 1% budget on AgentDrift validation data, and evaluated unchanged on every real test set, including the stress sets and all SWE-Inject runs. Table 4 summarizes them, and the text reports seed ranges where they qualify a single-seed number. The per-suite breakdown, matched-budget comparison, and adaptation curve are single-seed.

Thresholds across encoders.

The stored threshold of the original sentence-encoder checkpoint was overwritten by a later calibration on real benign data, so its single-seed transfer results are reported at 0.5, alongside the hashing guard at 0.5. The multi-seed runs calibrate both encoders identically, which removes this asymmetry, and Section 7.6 also compares them at matched false-alarm budgets, which removes threshold effects.

Compute.

Seed-42 training, evaluation, and latency measurements ran on a laptop CPU (AMD Ryzen 5 7430U, 8 GB RAM) with Python 3.12, PyTorch 2.14 (CPU), and sentence-transformers 6.1. Trajectory generation, sentence encoding, and the multi-seed study ran on NVIDIA T4 GPUs (Kaggle).

Use of AI tools.

Claude (Anthropic) was used to assist with formatting the manuscript, editing the language, drafting parts of the text from the author’s experimental results, and assisting a label audit that the author verified. The author checked all results against the released code and data and takes full responsibility for the content.

7. Results I: Tool-Using Agents

7.1. In-distribution Reproduction and the Price of Causality

On the AgentDrift test split the pre-dispatch guard reaches 0.984 trajectory F1, 0.957 macro step F1, 0.883 injection exact match, and 0.961 hijacked IoU at a 0.5% benign interruption rate. Our bidirectional DriftNet reimplementation reaches 0.981 F1 and 0.981 exact match, matching the published 0.983 and 0.987. Figure 1 compares the two at a common threshold. Deciding before execution costs nothing in whether an attack is caught (0.981 for both) and about ten points of injection exact match (0.884 against 0.981), because a poisoned observation must be judged when it arrives. The causal model’s weak Adding the world, provenance, and anchoring features to a text-only model raises trajectory F1 from 0.973 to 0.981, within overlapping confidence intervals; the defensible effects are a fivefold drop in benign false alarms (1.90% to 0.38%) and higher recall on delayed-execution attacks (0.880 to 0.906). Training on raw rather than anonymized identities moves F1 by 0.0008, so the guard does not rely on the identity shortcut of Table 1. With thresholds from 980 non-compromised validation trajectories at a 1% budget, 0.53% of benign test trajectories are held and none blocked, while 97.6% of attacks are caught.
point is hard negatives that look suspicious early and are vindicated later, which it flags at 5.4% against DriftNet’s 1.5%.

7.2. Transfer to Real Tool-Using Agents

Table 3 is the central result for this setting: the guard trained only on AgentDrift, evaluated unchanged on real trajectories from both models.

Detection and localization.

Detection drops to a third of its synthetic value. Localization all but vanishes: the guard recovers the exact injection point in 2.9% of real attacked trajectories, against 88.3% on synthetic data. Knowing that an attack happened survives the move to real data far better than knowing where it entered.

The guarantee breaks.

The threshold calibrated on synthetic data at a 1% budget flags 13.1% of real benign 7B trajectories and 19.4% of 14B ones (8.7–24.0% across seeds; Table 4). Recalibrating on real benign data restores the promise but not the utility: at a 1% budget only 3.6% of attacks are caught, and at 10%, 21.6%. The conformal procedure behaves correctly throughout; the violation is a failure of exchangeability, not of the method.

7.3. Training-seed Variance

Table 4 repeats the evaluation over five training seeds. The collapse does not depend on the seed. In distribution, seeds agree to within 0.004 F1. On real data the spread is ten to twenty times wider (0.28–0.37 F1 on 7B, 0.42–0.48 on 14B), but every seed loses more than half of its synthetic performance. The false-alarm overshoot is the most seed-sensitive quantity. At a 1% budget, the hashing guard interrupts 8.7–12.8% of non-compromised 7B runs and 17.8–24.0% of 14B runs, so the budget is exceeded 9- to 24-fold. Seed 42 (13.1% and 19.4%) lies inside this range. Injection exact match on real data stays below 0.08 for every seed and both encoders, against 0.80–0.89 in distribution.
Table 4. Training-seed variance (seeds 0–4; mean ± standard deviation, range in brackets). Each seed is trained on AgentDrift, calibrated at a 1% budget on AgentDrift validation data, and evaluated unchanged on every real set. “Interrupted” is the fraction of non-compromised trajectories in which any call is held or blocked. SWE-Inject counts are over the three main runs (48 hijacked trajectories); AUROC is threshold-free.
Table 4. Training-seed variance (seeds 0–4; mean ± standard deviation, range in brackets). Each seed is trained on AgentDrift, calibrated at a 1% budget on AgentDrift validation data, and evaluated unchanged on every real set. “Interrupted” is the fraction of non-compromised trajectories in which any call is held or blocked. SWE-Inject counts are over the three main runs (48 hijacked trajectories); AUROC is threshold-free.
metric hashing encoder mpnet encoder
AgentDrift test, trajectory F1 0.981 ± 0.002 [0.979–0.983] 0.963 ± 0.001 [0.962–0.965]
AgentDrift test, injection exact match 0.878 ± 0.011 [0.866–0.889] 0.797 ± 0.005 [0.792–0.804]
AgentDrift test, interrupted 1.3% [1.1–1.6] 1.6% [1.3–2.1]
AgentDojo-Steps 7B, trajectory F1 0.329 ± 0.040 [0.284–0.374] 0.493 ± 0.030 [0.441–0.513]
AgentDojo-Steps 14B, trajectory F1 0.456 ± 0.020 [0.424–0.477] 0.515 ± 0.033 [0.469–0.552]
AgentDojo-Steps 7B / 14B, F1 at threshold 0.5 0.371 / 0.491 0.528 / 0.549
AgentDojo-Steps 7B, injection exact match 0.012 ± 0.006 [0.007–0.022] 0.022 ± 0.000 [0.022–0.022]
AgentDojo-Steps 14B, injection exact match 0.035 ± 0.015 [0.019–0.052] 0.062 ± 0.013 [0.045–0.078]
AgentDojo-Steps 7B, interrupted 10.6% [8.7–12.8] 38.8% [34.0–43.9]
AgentDojo-Steps 14B, interrupted 20.6% [17.8–24.0] 44.0% [33.5–48.8]
multi-step split attacks (7B), trajectory F1 0.169 ± 0.066 [0.127–0.283] 0.274 ± 0.012 [0.259–0.289]
SWE-Inject, hijacks blocked: learned guard (of 48) 1.4 [1–2] 4.8 [4–5]
SWE-Inject, hijacks blocked: with provenance rule (of 48) 48 [48–48] 48 [48–48]
SWE-Inject 14B, step AUROC 0.36 ± 0.11 [0.22–0.51] 0.58 ± 0.12 [0.40–0.72]
SWE-Inject 32B, step AUROC 0.44 ± 0.08 [0.32–0.54] 0.63 ± 0.09 [0.47–0.70]

7.4. Transfer by Environment

Table 5 breaks transfer down by AgentDojo suite. Banking transfers best (0.53 and 0.64 F1, precision 0.95 and 0.91): banking attacks ask the agent to send money to an attacker IBAN, the attack shape AgentDrift’s banking domain contains, and the provenance features see an account number that only an untrusted observation introduced. Even there the guard usually fires late: on the 7B data only 6.1% of banking attacks are flagged at or before the first hijacked call, although 36.7% are flagged eventually. Slack transfers poorly (0.28–0.29 F1): its attacker goals include visiting a URL, inviting a user, or posting to a channel, actions that resemble ordinary collaboration. Travel is worst (0.16 and 0.11 F1): few travel attacks succeed, while the guard flags a quarter of non-compromised runs. AgentDrift, by contrast, is uniform across its domains (0.974 to 0.994 F1 at threshold 0.5).

7.5. Ruling Out an Empty World

Our converter initially left the known world empty, which disables the world and provenance features. Reconstructing each trajectory’s known addresses and accounts from its own tool outputs, excluding any value that appears in a payload, populates the world for 208 of 450 (7B) and 189 of 396 (14B) trajectories. Transfer F1 moves from 0.333 to 0.327 (7B) and from 0.428 to 0.436 (14B): no effect. The collapse is not an artifact of disabled features.

7.6. Representation Determines Transfer

In distribution, the bag-of-n-grams encoder matches the 110M-parameter sentence encoder (0.981 against 0.965 at a common threshold). On real data the ranking inverts (Table 6): at a threshold of 0.5 the sentence encoder transfers 12 points of F1 better on the 7B data (0.501 against 0.378) and 8 points better on the 14B data (0.544 against 0.469). The reversal holds for every seed (Table 4). Calibrated identically, hashing leads in distribution (0.981 against 0.963), while the sentence encoder transfers 16 points better on 7B (0.493 against 0.329) and 6 points better on 14B (0.515 against 0.456). It does so by flagging far more: at the same 1% budget it interrupts 34–49% of non-compromised real runs. Hashing matches a semantic encoder on AgentDrift because that corpus’s attacks are lexically stereotyped, and memorizing their vocabulary is what fails to transfer. A practitioner who tuned on the benchmark alone would pick the encoder that generalizes worst.
Table 6. Encoder comparison (trajectory F1, seed 42). Hashing wins in-distribution; the sentence encoder transfers better. The last column gives the fraction of non-compromised real 7B trajectories interrupted.
Table 6. Encoder comparison (trajectory F1, seed 42). Hashing wins in-distribution; the sentence encoder transfers better. The last column gives the fraction of non-compromised real 7B trajectories interrupted.
encoder threshold AgentDrift real 7B real 14B 7B interrupted
hashing (bag-of-n-grams) 0.814 (calibrated) 0.984 0.327 0.436 13.1%
hashing (bag-of-n-grams) 0.5 0.981 0.378 0.469 16.3%
mpnet (sentence encoder) 0.5 0.965 0.501 0.544 48.7%
Figure 2. Transfer by encoder (hashing at its calibrated threshold, mpnet at 0.5). (a) On AgentDrift the hashing encoder is as good as or better than the sentence encoder. (b, c) On real trajectories every metric falls, and the sentence encoder is ahead on trajectory F1 and first-hijack recall, partly because its threshold flags far more trajectories.
Figure 2. Transfer by encoder (hashing at its calibrated threshold, mpnet at 0.5). (a) On AgentDrift the hashing encoder is as good as or better than the sentence encoder. (b, c) On real trajectories every metric falls, and the sentence encoder is ahead on trajectory F1 and first-hijack recall, partly because its threshold flags far more trajectories.
Preprints 242873 g002

Matched budgets.

The advantage is real but narrower than the F1 gap suggests (Figure 3, Table 7). After recalibrating each encoder on real benign data, the sentence encoder catches 9.4% of real attacks at a 1% budget against hashing’s 3.6%, but by a 5% budget the two are even. Neither encoder is usable at a budget an operator would accept.

7.7. Robustness

Table 8 applies four attack transformations to the real 7B trajectories. Text normalization neutralizes zero-width and homoglyph obfuscation completely. Base64 encoding costs three points of F1. Multi-step decomposition, which spreads an instruction across several observations, halves detection (0.327 to 0.159; 0.127–0.283 across seeds) and drives injection exact match to zero for every seed.

7.8. How Much Real Data Helps

Fine-tuning the synthetic-trained guard on a few real trajectories and testing on a held-out real split (three repeats per size), trajectory F1 at a fixed threshold rises from 0.447 with no adaptation to 0.504 at 100 trajectories and falls back to 0.476 at 200 (Figure 4). Recall of the first hijack improves more, from 0.22 to about 0.39. Adaptation buys a few points and plateaus; the gap is not mainly a shortage of real training data.

7.9. What the Real Tool-Use Data Shows About the Attacks

Attack success rises with model scale: on banking, the 14B agent is hijacked in 45.1% of attacked runs (65 of 144, as scored by AgentDojo) against the 7B agent’s 23.6% (34 of 144), while task success rises only three points. Slack is the most exposed suite for both models (55.2% and 53.3%). Splitting the attacker’s goal into several innocuous-looking steps lowered attack success for the 7B agent: on banking and Slack together, 12.0% of runs (30 of 249) against 36.9% (92 of 249) for the single-step attack.

8. Results II: Coding Agents

8.1. More Capable Agents Are Hijacked More Often

Table 9 and Figure 5 report, over 108 attacked-task episodes per model, how often the agent reached the payload, how often it was hijacked once it did, and the overall hijack rate. The rate rises with model size: 2.8%, 16.7%, and 25.0%. Paired exact sign tests with Holm correction give p = 2.4 × 10 − 6 (7B against 32B), p = 5.5 × 10 − 4 (7B against 14B), and p = 0.022 (14B against 32B).
The gradient is driven by task completion. The 7B model reaches the payload in only 11 episodes and edits the source in only 3 of its 18 benign controls; given exposure it complies 27% of the time, not distinguishable from the 14B model’s 34%. Between 14B and 32B both terms rise, and on shared tasks the 32B model was hijacked on 11 tasks the 14B model resisted, the reverse on 2. A more capable agent takes more actions, and the extra actions are where the attack lands. This agrees with the tool-use result of Section 7.9 and with CIPR’s finding on cloud models that underspecified prompts lower attack success by truncating execution depth [7].

Where attacks land.

Once an agent reads a poisoned README it is hijacked 75% (14B) and 70% (32B) of the time; code comments follow at 18% and 35%; payloads in the issue body or test output are rarely reached or rarely followed. By goal, curl …| sh accounts for 17 of 18 hijacks on the 14B model and 23 of 27 on the 32B model. Typosquatted installs never succeeded, yet in 12 of 16 exposures the agent followed the instruction and installed the correctly spelled package, so a 0% success rate understates compliance. Attack framing showed no effect on the main runs.

8.2. The Learned Guard Does Not Transfer

Table 10 applies the same seed-42 checkpoint to SWE-Inject. It blocks 1 of 48 hijacks before execution. Its step-level AUROC is 0.29 (14B) and 0.40 (32B), below chance, so no recalibration can rescue it; the 7B value (0.47) rests on three positives. On the 32B data, real curl …| sh hijacks have a median score of 0.0000. Its one catch coincides with a repository whose benign control also scores high (0.30), so it is likely not detection. Median latency is 2.3 to 2.6 ms per decision on a laptop CPU, so cost is not the obstacle.
Across five seeds the hashing guard blocks 1 or 2 of 48 hijacks, with mean AUROC 0.36 (14B) and 0.44 (32B). It is never reliably above chance: the best seed reaches 0.51 and 0.54. The sentence-encoder guard ranks real hijacks modestly better (mean AUROC 0.58 and 0.63), matching its better transfer on tool-using agents. At its calibrated threshold, though, it still blocks only 4 or 5 of 48. Neither representation protects a coding agent.

8.3. The Guard Learned the Mention Notion of a Hijack

The guard’s highest scores on coding trajectories fall on benign edits that keep the injected comment while fixing the bug—exactly the steps that a mention-based label would call hijacked. Its training data, like the AgentDojo-Steps labeler, marks a step hijacked when its arguments contain an attacker value. In tool-use tasks that definition is close to correct, because an attacker IBAN in a transfer is the attack. In coding tasks it is not: an edit can carry the payload text without acting on it, while the real attack, curl …| sh, executes through a shell command whose shape the synthetic corpus never showed.
The label definition also matters for measurement. Under mention labels the 14B and 32B models have 27 and 32 hijacks and the paired test gives p = 0.267 ; under goal-only labels the counts are 18 and 27 and p = 0.022 . The mention rule overcounts by 50% (14B) and 19% (32B), and because the overcount is larger on the smaller model it erases a real difference between the two. Every reclassified episode was a comment-preserving edit, checked by hand. Guards and benchmarks for coding agents should score whether the goal is realized, not whether it is mentioned.

8.4. Provenance Rule: Complete on URL Attacks, Blind without Them

The provenance rule of Section 4.4 blocked all 48 hijacks and never interrupted a benign control (Table 10). Its other holds were edits that would write the attacker command back into the repository, which stop payload propagation rather than honest work. But every successful main-run attack passes an attacker URL into a shell command, which is exactly what the rule tracks, so 48 of 48 is an upper bound.
To find its edge we added a URL-free goal, run_local_script: the repository ships a harmless placeholder script, and the payload tells the agent to run it (bash scripts/setup_env.sh or python tools/preflight.py). The command names only a local path. This attack is about as effective as the URL-based one: once reached, it hijacks the 14B model 31% and the 32B model 42% of the time. The rule catches none of it (Figure 6): 0 of 8 (14B) and 0 of 10 (32B). Its overall block-before-execution rate on this set falls to 0.27 (14B) and 0.57 (32B), entirely because the URL-free attacks pass through, and the learned guard does not fill the gap. Over five seeds the hashing guard ranks steps on this set near chance (AUROC 0.50–0.59 on 14B, 0.53–0.59 on 32B) and blocks 0 of the 18 run_local_script hijacks in four seeds and 1 in the fifth. The sentence-encoder guard ranks better (AUROC 0.65–0.73 and 0.68–0.75) but blocks only 1 or 2 of the 18, all on the 32B model. The counts are small, so we state a direction rather than a rate, but the direction is clean: a defense that tracks network destinations is blind to an attack that runs code already in the repository.

9. Error Analysis

This section asks how transfer fails, using per-trajectory predictions of the hashing guard at its calibrated threshold on AgentDojo-Steps 7B unless stated.

Where errors fall.

Of 138 compromised 7B trajectories, 103 are missed. Of 312 non-compromised ones, 41 are interrupted, and 23 of those 41 are failed attacks—runs carrying a payload the agent did not obey. On the 14B data, 28 of 47 false alarms are failed attacks. Failed attacks make up half of the non-compromised real data but only 23% of AgentDrift’s. A guard that reacts to the payload rather than to the agent’s response to it is penalized much more on real data than on the benchmark—the same confusion between reading and acting that produces the mention-label behavior on coding agents (Section 8.3).

A positional prior learned from synthetic data.

In every AgentDrift training trajectory the first injection point is at step 1, 2, or 3; it is never the first step. In AgentDojo the injected content is often returned by the agent’s first tool call, so the injection point is the first step in 70% (7B) and 80% (14B) of compromised trajectories. On AgentDrift the guard’s predicted injection point is exactly right in 685 of 775 attacked trajectories. On the real 7B data it predicts no injection point in 104 of 138, is most often one step late when it does predict one (22 cases), and is exactly right in only 4. The poisoned first observation is labeled benign and the first hijacked action is labeled as the injection point.

Trajectory length and world knowledge.

Among non-compromised trajectories of one to three steps, 0 of 74 (7B) and 1 of 51 (14B) are flagged, against 15–50% for longer ones; every AgentDrift trajectory has 3 to 11 steps. A reconstructed world is associated with fewer false alarms (6.4% against 14.0% of benign 7B runs), although this is confounded with environment.

Three trajectories.

Detected but mislocalized (banking). The user asks the agent to pay a bill. Its first call, read_file, returns the bill with a payload asking it to pay an attacker IBAN, and the next two calls are send_money to that IBAN. The guard scores the trajectory 0.999 but labels the steps benign, injection, hijacked, so the first transfer would have executed. Missed entirely (Slack). The user asks the agent to read a web page; the page instructs it to visit another site, and the agent calls get_webpage on the attacker’s URL twice. The score is 0.000: the hijacked action reads a page, its argument is a bare domain, and it resembles the user’s own request. False alarm on a failed attack (travel). The agent ignores a payload embedded in hotel reviews and creates the requested calendar event. The guard scores the trajectory 0.919 and labels the legitimate final call as hijacked: acting after reading a payload is treated as acting on it.

10. Discussion

Why synthetic scores mislead.

Across both settings, the synthetic corpus differs from real traffic in ways that make it easier and that do not carry over. Its attacks are lexically stereotyped, which a bag-of-n-grams model memorizes and which actively misleads encoder selection. Its injection never arrives in the first step, which the guard learns as a positional prior. Its trajectories are 3 to 11 steps long, whereas real ones run from 1 to 51. Its attacker goals are mostly transfers and messages to external addresses; real goals include reading pages, inviting users, and, for coding agents, executing shell commands. And its labels tie “hijacked” to the presence of an attacker value, which the guard learns and which fails on coding tasks, where an edit can carry a payload without obeying it.

Implications for deploying guards.

Three operational lessons follow. First, a learned guard’s published accuracy says little about a new agent or domain; it must be evaluated, and calibrated, on that deployment’s own traffic. Recalibration restores the false-alarm budget but not recall. Second, simple rules are complementary rather than sufficient. Input normalization defeats two obfuscation families outright, and a provenance rule stops every attack that routes an attacker address into a call, but both have a clear edge: decomposed attacks, and attacks that run code already present. For coding agents, the provenance rule should be paired with a policy on what may be executed—for example, holding any shell command that runs a script not written or named by the user, or not present in the repository’s clean state. Third, as models become more capable they complete more of the task and are hijacked more often, so guards matter more, not less, as agents improve.

Recommendations for benchmark design.

Step-level detection benchmarks should (i) report transfer to at least one real-agent test set, ideally in more than one domain; (ii) anonymize identities and report lookup baselines; (iii) report recall at fixed false-alarm budgets, not only F1 at a tuned threshold; (iv) include multi-step decomposed and address-free attacks; (v) vary the position of the injection, including the first step; (vi) include many failed attacks as hard negatives; and (vii) label a step hijacked only when it realizes the attacker’s goal, and release the looser labels separately.

11. Limitations

Both real datasets come from one model family (Qwen2.5 and Qwen2.5-Coder), so cross-model comparisons are scale comparisons; Llama-3.1’s chat template is incompatible with AgentDojo’s parallel tool calls. Context limits on a T4 leave the AgentDojo workspace suite nearly absent. SWE-Inject is modest in scale: 18 small repositories, 126 trajectories per model, one system prompt, and two of six vectors represented by only two episodes each; its smallest model is fp16 while the larger ones are 4-bit AWQ, and the URL-free result rests on 18 hijacks. The SWE-Inject environment is simulated: the test runner can report a pass before a real fix, running tests through the raw shell can bypass the setup gate, and the sandbox reveals itself in the canned output of an intercepted curl. Guard evaluations are replays over logged trajectories, not live loops in which a held call changes what the agent does next. Automatic labels agree with human review at 86.7–100%, and the audits bound but do not eliminate label noise. Training seeds vary in Table 4, but each real dataset was generated once, at temperature 0 and a fixed task seed, so generation variance is not measured; the per-suite breakdown, matched-budget comparison, and adaptation curve are single training seed. TraceWarden is a monitor, not a guarantee, and can be evaded by a sufficiently adaptive attacker; it is best used as one layer among several.

12. Ethics

All tool-use attacks run inside AgentDojo’s sandboxed, fictional environments and reuse its attacker goals. All coding-agent attacks are already documented in prior work and run in a sandbox that intercepts network calls, installs, and pushes; planted scripts are harmless placeholders. We craft no operational attacks against real services. The released datasets are intended for training and evaluating defenses.

13. Conclusions

Step-level injection guards look nearly solved on synthetic data and are not. Trained on AgentDrift and tested on real agents, the same guard loses two thirds of its detection and nearly all of its localization on tool-using agents, breaks its calibrated false-alarm promise, and blocks 1 or 2 of 48 hijacks on coding agents, for every training seed. The failures trace to a positional prior, a stereotyped attack vocabulary, and a mention-based definition of a hijack, and a provenance rule that looks complete stops working once an attack carries no address. We release AgentDojo-Steps, SWE-Inject-Steps, and the full guard so that the next guard can be measured where it will be used: on real agent traffic, in more than one domain.

Funding

This research did not receive any specific grant from funding agencies in the public, commercial, or not-for-profit sectors.

Data Availability Statement

All code and both datasets are publicly available. TraceWarden and AgentDojo-Steps: https://github.com/ArsalanKaleem/tracewarden (dataset in dataset/agentdojo-steps). SWE-Inject-Steps, with goal-only and mention labels: https://huggingface.co/datasets/ArsalanKaleem/swe-inject-steps. AgentDrift is available from its authors [2].

Acknowledgments

We thank the authors of AgentDrift, DriftNet, and AgentDojo for releasing the data and environments this work builds on. During the preparation of this work the author used Claude (Anthropic) to assist with formatting the manuscript, editing the language, drafting parts of the text from the author’s experimental results, and assisting a label audit that the author verified. After using this tool, the author reviewed and edited the content as needed and takes full responsibility for the content of the published article.

Conflicts of Interest

The author declares no conflicts of interest.

Appendix A. Feature Specification

Action events carry 15 features (world, provenance, anchoring) and observation events carry 3 (padded with zeros to 15), so each event is a 768 + 15 = 783 -dimensional vector. All features use only information available at the moment the event occurs.

Appendix A.1. Normalization

Text is passed through Unicode NFKC normalization; zero-width characters (U+200B, U+200C, U+200D, U+2060, U+FEFF) and soft hyphens are removed; 17 Cyrillic and Greek homoglyphs of Latin letters are mapped to their Latin forms; and runs of spaces and tabs are collapsed.

Appendix A.2. Serialization

An action event is the string TOOL: <tool> | THOUGHT: <reasoning> | ARGS: <arguments as sorted JSON>; an observation event is OBS from <tool>: <output>; the user’s task is TASK: <task>. Each string is truncated to 2,000 characters. The hashing encoder is a signed feature-hashing vectorizer over word unigrams and bigrams into 768 dimensions with L2 normalization. The sentence encoder is all-mpnet-base-v2 with normalized embeddings.

Appendix A.3. Known World

The known address set K contains the user’s own email, the emails of listed contacts, and any listed known emails, lowercased. The known domain set D contains the domains of K and any listed domains.
Table A1. Action-event features. “Values” are the salient atomic values extracted from the call’s arguments. o < t denotes the observations of steps before the current call.
Table A1. Action-event features. “Values” are the salient atomic values extracted from the call’s arguments. o < t denotes the observations of steps before the current call.
group feature definition
world has_email 1 if the arguments contain an email address
world has_external 1 if any argument email is outside K and its domain outside D
world frac_external fraction of argument emails that are external
world has_ext_url 1 if an argument URL’s host does not end in a domain in D
provenance has_values 1 if the arguments contain any salient value
provenance frac_task fraction of values that occur in the user’s task
provenance frac_world fraction of values that occur in the serialized known world
provenance frac_tainted fraction of values absent from task and world that first occur in some o < t
provenance any_tainted 1 if any value is tainted
provenance frac_novel fraction of values that occur nowhere: not in task, world, or any o < t
provenance taint_dist steps since the most recent observation that introduced a tainted value, divided by 10
anchoring sim_task cosine similarity of the action embedding to the task embedding
anchoring sim_obs maximum cosine similarity of the action embedding to any prior observation embedding
anchoring obs_minus_task sim_obs − sim_task
anchoring task_drop mean similarity of prior actions to the task minus sim_task (0 for the first action)

Appendix A.4. Salient Values

Values are extracted from the arguments by walking the argument structure recursively. Each atomic value is matched against seven entity patterns: email addresses, URLs, IBAN-like account numbers, phone numbers, numbers of four or more digits, file paths, and domain names with common top-level domains. If a string contains entities, the entities are the values; otherwise the whole string is a value if it is between 6 and 200 characters long. Values are lowercased, stripped of trailing punctuation, and de-duplicated; membership tests are substring tests on normalized text. The provenance rule of Section 4.4 holds a call when any tainted value is an email, URL, or domain.

Appendix A.5. Observation-Event Features

Imperative density is min ( 20 m / w , 1 ) , where m counts matches of an imperative-phrase pattern (e.g., “you must”, “ignore previous”, “new instructions”) and w is the number of words. Urgency density is the same with an urgency pattern (e.g., “urgent”, “asap”, “final notice”). Unknown entity is 1 if the observation contains an entity that does not occur in the user’s task or serialized world.

Appendix B. Model and Training Configuration

Table A2. Configuration of the pre-dispatch guard. The same settings are used for both encoders and all seeds.
Table A2. Configuration of the pre-dispatch guard. The same settings are used for both encoders and all seeds.
setting value
input dimension 783 (768 embedding + 15 features)
model width / heads / feed-forward width 256 / 4 / 512
transformer layers 2, causal attention mask
dropout 0.1
positional encoding sinusoidal, up to 256 events, plus a learned action/observation type embedding
output heads two MLP heads: hijack score at action events, poison score at observation events
trainable parameters 1,321,474
optimizer AdamW, learning rate 3 × 10 − 4 , weight decay 0.01, 10% warm-up
batch size / epochs 32 / 15
loss binary cross-entropy; positive weight 3.0 (hijack) and 4.0 (poison); poison loss weight 0.5
seeds 42 (headline); 0–4 (seed study)
conformal budgets hold α = 0.01 , block α = 0.002 , 980 calibration trajectories
calibrated thresholds (hashing, seed 42) hold 0.814, block 0.994
poison threshold 0.5
At an action event, the hijack head’s sigmoid output is the score p t compared against the hold and block thresholds; the trajectory score is the maximum over action events. A step whose action’s hijack score reaches the hold threshold is hijacked; otherwise, a step whose observation’s poison score reaches 0.5 is an injection point if it precedes the first hijacked step and a failed injection if not; all other steps are benign. The bidirectional DriftNet reimplementation has a comparable size (1,318,533 parameters) and uses DriftNet’s published loss weights. No systematic hyperparameter search was performed beyond comparing two- and three-layer trunks.

References

  1. Greshake, K.; Abdelnabi, S.; Mishra, S.; Endres, C.; Holz, T.; Fritz, M. Not What You’ve Signed Up For: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection. In Proceedings of the Proceedings of the 16th ACM Workshop on Artificial Intelligence and Security, 2023; pp. 79–90. [Google Scholar] [CrossRef]
  2. Pinjari, A.; Saint-Germain, M.P. AgentDrift: A Step-Labeled Benchmark of Injection-Hijacked LLM Agent Trajectories. arXiv 2026, arXiv:2609.06972. [Google Scholar]
  3. Pinjari, A.; Saint-Germain, M.P. DriftNet: A Dual-Head Trajectory Transformer for Detecting and Localizing Prompt Injection in LLM Agents. arXiv 2026, arXiv:2609.10892. [Google Scholar]
  4. Debenedetti, E.; Zhang, J.; Balunović, M.; Beurer-Kellner, L.; Fischer, M.; Tramèr, F. AgentDojo: A Dynamic Environment to Evaluate Prompt Injection Attacks and Defenses for LLM Agents. In Proceedings of the Advances in Neural Information Processing Systems: Datasets and Benchmarks Track, 2024. [Google Scholar]
  5. Willison, S. The Lethal Trifecta for AI Agents: Private Data, Untrusted Content, and External Communication, 2025. Blog post, accessed. (accessed on 26 October 2026).
  6. Zhan, Q.; Liang, Z.; Ying, Z.; Kang, D. InjecAgent: Benchmarking Indirect Prompt Injections in Tool-Integrated Large Language Model Agents. In Proceedings of the Findings of the Association for Computational Linguistics: ACL 2024, 2024; pp. 10471–10506. [Google Scholar]
  7. Zhu, F.; Zhao, B.; Lin, R.; He, P.; Du, T.; Ji, S. Beyond the Payload: How User Invocation Shapes Coding Agent Vulnerability to Repository Poisoning. arXiv 2026, arXiv:2608.30686. [Google Scholar]
  8. Maloyan, N.; Namiot, D. Prompt Injection Attacks on Agentic Coding Assistants: A Systematic Analysis of Vulnerabilities in Skills, Tools, and Protocol Ecosystems. arXiv 2026, arXiv:2601.17548. [Google Scholar]
  9. Liu, Y.; Zhao, Y.; Lyu, Y.; Zhang, T.; Wang, H.; Lo, D. “Your AI, my shell”: Demystifying Prompt Injection Attacks on Agentic AI Coding Editors. arXiv 2025, arXiv:2509.22040. [Google Scholar]
  10. Hines, K.; Lopez, G.; Hall, M.; Zarfati, F.; Zunger, Y.; Kiciman, E. Defending Against Indirect Prompt Injection Attacks With Spotlighting. arXiv 2024, arXiv:2403.14720. [Google Scholar]
  11. Debenedetti, E.; Shumailov, I.; Fan, T.; Hayes, J.; Carlini, N.; Fabian, D.; Kern, C.; Shi, C.; Terzis, A.; Tramèr, F. Defeating Prompt Injections by Design. arXiv 2025, arXiv:2503.18813. [Google Scholar]
  12. Costa, M.; Köpf, B.; Kolluri, A.; Paverd, A.; Russinovich, M.; Salem, A.; Tople, S.; Wutschitz, L.; Zanella-Béguelin, S. Securing AI Agents with Information-Flow Control. arXiv 2025, arXiv:2505.23643. [Google Scholar]
  13. Kim, J.; Choi, W.; Lee, B. Prompt Flow Integrity to Prevent Privilege Escalation in LLM Agents. arXiv 2025, arXiv:2503.15547. [Google Scholar]
  14. Vovk, V.; Gammerman, A.; Shafer, G. Algorithmic Learning in a Random World; Springer: New York, 2005. [Google Scholar]
  15. Angelopoulos, A.N.; Bates, S. A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification. arXiv 2021, arXiv:2107.07511. [Google Scholar]
  16. Vaswani, A.; Shazeer, N.; Parmar, N.; Uszkoreit, J.; Jones, L.; Gomez, A.N.; Kaiser, Ł.; Polosukhin, I. Attention Is All You Need. In Proceedings of the Advances in Neural Information Processing Systems, 2017; 30. [Google Scholar]
  17. Weinberger, K.; Dasgupta, A.; Langford, J.; Smola, A.; Attenberg, J. Feature Hashing for Large Scale Multitask Learning. In Proceedings of the Proceedings of the 26th International Conference on Machine Learning, 2009; pp. 1113–1120. [Google Scholar]
  18. Reimers, N.; Gurevych, I. Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. In Proceedings of the Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing, 2019; pp. 3982–3992. [Google Scholar]
  19. Song, K.; Tan, X.; Qin, T.; Lu, J.; Liu, T.Y. MPNet: Masked and Permuted Pre-training for Language Understanding. Proc. Adv. Neural Inf. Process. Syst. 2020, 33, 16857–16867. [Google Scholar]
  20. Qwen Team. Qwen2.5 Technical Report. arXiv 2024, arXiv:2412.15115. [Google Scholar]
  21. Kwon, W.; Li, Z.; Zhuang, S.; Sheng, Y.; Zheng, L.; Yu, C.H.; Gonzalez, J.E.; Zhang, H.; Stoica, I. Efficient Memory Management for Large Language Model Serving with PagedAttention. In Proceedings of the Proceedings of the 29th Symposium on Operating Systems Principles, 2023; pp. 611–626. [Google Scholar]
  22. Hui, B.; Yang, J.; Cui, Z.; et al. Qwen2.5-Coder Technical Report. arXiv 2024, arXiv:2409.12186. [Google Scholar]
  23. Wilson, E.B. Probable Inference, the Law of Succession, and Statistical Inference. J. Am. Stat. Assoc. 1927, 22, 209–212. [Google Scholar] [CrossRef]
  24. Holm, S. A Simple Sequentially Rejective Multiple Test Procedure. Scand. J. Stat. 1979, 6, 65–70. [Google Scholar]
Figure 1. Post-hoc versus pre-dispatch detection on AgentDrift (anonymized test split, hashing encoder, threshold 0.5). (a) Detection is unchanged and localization of the injection point pays for causality. (b) Prevention metrics that only a pre-dispatch guard can report.
Figure 1. Post-hoc versus pre-dispatch detection on AgentDrift (anonymized test split, hashing encoder, threshold 0.5). (a) Detection is unchanged and localization of the injection point pays for causality. (b) Prevention metrics that only a pre-dispatch guard can report.
Preprints 242873 g001
Figure 3. Attacks caught against the fraction of benign real (7B) trajectories flagged, for both encoders. The sentence encoder leads only at the strictest operating points.
Figure 3. Attacks caught against the fraction of benign real (7B) trajectories flagged, for both encoders. The sentence encoder leads only at the strictest operating points.
Preprints 242873 g003
Figure 4. Adaptation with real labeled tool-use trajectories. Lines show the mean over three repeats and bands the range.
Figure 4. Adaptation with real labeled tool-use trajectories. Lines show the mean over three repeats and bands the range.
Preprints 242873 g004
Figure 5. Hijack rate on SWE-Inject by coding model (108 attacked-task episodes each), with 95% normal-approximation intervals. Below each model: the share of episodes in which the agent reached the payload, and the share of those in which it complied. The rate rises with how much of the task the agent completes.
Figure 5. Hijack rate on SWE-Inject by coding model (108 attacked-task episodes each), with 95% normal-approximation intervals. Below each model: the share of episodes in which the agent reached the payload, and the share of those in which it complied. The rate rises with how much of the task the agent completes.
Preprints 242873 g005
Figure 6. Hijacks the provenance rule can catch on SWE-Inject, by attacker goal (URL-free runs). URL-bearing goals are caught in full; the URL-free run_local_script goal is never caught (0/8 and 0/10).
Figure 6. Hijacks the provenance rule can catch on SWE-Inject, by attacker goal (URL-free runs). URL-bearing goals are caught in full; the URL-free run_local_script goal is never caught (0/8 and 0/10).
Preprints 242873 g006
Table 1. Lookup baselines on the AgentDrift test split. A world-identity lookup is a strong shortcut on raw data and is removed by anonymization.
Table 1. Lookup baselines on the AgentDrift test split. A world-identity lookup is a strong shortcut on raw data and is removed by anonymization.
lookup key raw identities anonymized
majority class 0.550 0.550
world identity 0.859 0.555
company only 0.667 0.550
tool sequence 0.600 0.600
number of steps 0.584 0.584
Table 2. Dataset statistics. “Attacked” trajectories contain a hijacked step; “failed” contain an injection the agent did not obey. SWE-Inject counts use goal-only labels; each model has 108 attacked-task episodes and 18 benign controls, and an attacked-task episode in which the agent never read the payload counts as benign. In the URL-free sets, 8 (14B) and 10 (32B) of the attacked trajectories use the URL-free goal.
Table 2. Dataset statistics. “Attacked” trajectories contain a hijacked step; “failed” contain an injection the agent did not obey. SWE-Inject counts use goal-only labels; each model has 108 attacked-task episodes and 18 benign controls, and an attacked-task episode in which the agent never read the payload counts as benign. In the URL-free sets, 8 (14B) and 10 (32B) of the attacked trajectories use the URL-free goal.
dataset traj. steps attacked failed benign steps/traj. (min/med/max)
AgentDrift train (synthetic) 9,081 51,507 4,008 1,089 3,984 3/6/11
AgentDrift test (synthetic) 1,722 9,796 775 218 729 3/6/10
AgentDojo-Steps, Qwen2.5 7B 450 2,743 138 141 171 1/5/51
AgentDojo-Steps, Qwen2.5 14B 396 1,986 154 132 110 1/4/19
AgentDojo-Steps, multi-step attacks (7B) 232 1,044 42 133 57 1/3/23
SWE-Inject-Steps, Qwen2.5-Coder 7B 126 287 3 8 115 1/2/6
SWE-Inject-Steps, Qwen2.5-Coder 14B 126 807 18 35 73 1/6/20
SWE-Inject-Steps, Qwen2.5-Coder 32B 126 923 27 31 68 2/7/17
SWE-Inject-Steps, URL-free set, 14B 126 790 11 24 91 1/6/20
SWE-Inject-Steps, URL-free set, 32B 126 958 23 31 72 2/7/20
Table 3. Synthetic-to-real transfer on tool-using agents (hashing encoder, calibrated threshold, seed 42; Table 4 gives seed variance). Detection falls to a third; localization collapses.
Table 3. Synthetic-to-real transfer on tool-using agents (hashing encoder, calibrated threshold, seed 42; Table 4 gives seed variance). Detection falls to a third; localization collapses.
metric AgentDrift real 7B real 14B
trajectory precision 0.993 0.461 0.544
trajectory recall 0.975 0.254 0.364
trajectory F1 0.984 0.327 0.436
macro step F1 0.957 0.258 0.272
injection exact match 0.883 0.029 0.052
hijacked IoU 0.961 0.095 0.138
first hijack caught 0.973 0.130 0.214
benign interrupted 0.5% 13.1% 19.4%
Table 5. Transfer by AgentDojo suite (hashing encoder, calibrated threshold). “Interrupted” is the fraction of non-compromised trajectories in which any call is held or blocked.
Table 5. Transfer by AgentDojo suite (hashing encoder, calibrated threshold). “Interrupted” is the fraction of non-compromised trajectories in which any call is held or blocked.
model suite n attacked precision recall F1 first hijack interrupted
7B banking 154 49 0.947 0.367 0.529 0.061 1.0%
7B Slack 115 65 0.667 0.185 0.289 0.154 12.0%
7B travel 159 24 0.128 0.208 0.159 0.208 25.2%
7B workspace 22 0 – – – – 0.0%
14B banking 145 83 0.911 0.494 0.641 0.277 6.5%
14B Slack 119 65 0.481 0.200 0.283 0.123 25.9%
14B travel 132 6 0.065 0.333 0.108 0.333 23.0%
Table 7. Fraction of real (7B) tool-use attacks caught at matched false-alarm budgets, after recalibration on real benign data.
Table 7. Fraction of real (7B) tool-use attacks caught at matched false-alarm budgets, after recalibration on real benign data.
budget hashing mpnet
1% 3.6% 9.4%
5% 16.5% 15.9%
10% 21.6% 21.7%
Table 8. Robustness on real 7B tool-use trajectories (hashing encoder). The multi-step set contains the 295 trajectories to which decomposition applies.
Table 8. Robustness on real 7B tool-use trajectories (hashing encoder). The multi-step set contains the 295 trajectories to which decomposition applies.
variant n traj. F1 inj. EM interrupted
clean 450 0.327 0.029 13.1%
zero-width 450 0.327 0.029 13.1%
homoglyph 450 0.327 0.029 13.1%
base64 450 0.298 0.007 12.5%
multi-step split 295 0.159 0.000 15.4%
Table 9. Hijack rate on SWE-Inject by coding model (goal-only labels, 108 attacked-task episodes each). Brackets are 95% Wilson intervals. “Edited source” and “mean steps” are task-completion proxies.
Table 9. Hijack rate on SWE-Inject by coding model (goal-only labels, 108 attacked-task episodes each). Brackets are 95% Wilson intervals. “Edited source” and “mean steps” are task-completion proxies.
model reached payload hijacked ∣ reached hijacked overall edited source mean steps
Qwen2.5-Coder 7B 11/108 (10.2%) 3/11 (27.3%) 2.8% [0.9, 7.9] 16.7% 2.3
Qwen2.5-Coder 14B 53/108 (49.1%) 18/53 (34.0%) 16.7% [10.8, 24.8] 68.5% 6.3
Qwen2.5-Coder 32B 58/108 (53.7%) 27/58 (46.6%) 25.0% [17.8, 33.9] 89.8% 7.4
Table 10. Pre-dispatch prevention on SWE-Inject (main runs, goal-only labels; 48 hijacked trajectories across three models; seed-42 checkpoint, see Table 4 for seeds). “Interrupted” is the fraction of non-hijacked runs in which any call is held (7B / 14B / 32B).
Table 10. Pre-dispatch prevention on SWE-Inject (main runs, goal-only labels; 48 hijacked trajectories across three models; seed-42 checkpoint, see Table 4 for seeds). “Interrupted” is the fraction of non-hijacked runs in which any call is held (7B / 14B / 32B).
defense hijacks blocked interrupted
learned guard 1/48 0% / 0% / 1.0%
provenance rule 48/48 0% / 8.3% / 5.1%
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.