Sapien: A Stateful Policy Engine for Autonomous AI AgentsSapien: A Stateful Policy Engine for Autonomous AI Agents
Sapien uses a stateful context policy to intercept tool calls from a hijacked agent: it blocks 93–95% of attacks on AgentDojo and 62–85% on Toolathlon.
An adversary can hijack the agent LLM (via prompt injection, memory poisoning, or weight modification), forcing it to propose arbitrary tool calls. The policy generator LLM is assumed uncompromised and the input free of malicious data; user sessions, tool documentation, harness, and Sapien instrumentation cannot be bypassed. Provides safety, not liveness.
- The legitimate tool calls of a general-purpose agent depend on the user task and the steps already executed; a static allowlist either permits unauthorized calls or interrupts legitimate tasks. A context-free policy without state still cannot constrain parameters based on runtime data.
- Sapien generates a policy before execution based only on the user prompt and tool documentation, describes allowed call sequences with extended regular expressions, and adds variable predicates, defer holes with delayed expansion, and scope-limited semantic checks; at runtime it compiles to an NFA with variable bindings and enforces it call by call.
- Utility across four models is close to that of a no-policy agent. The analytic safety evaluation assumes the agent is fully hijacked: Sapien blocks 93.2–95.2% of attacks on AgentDojo, 64.6% on the full Toolathlon set (Gemini 3.8 Flash), 62.5–85.0% on the 20-task subset, and about twice the tool allowlist on long-horizon tasks.
- The authors note that the policy generator can still write wrong predicates or overly tight constraints, semantic attacks account for most of the unblocked instances, and liveness is not guaranteed and side channels are not prevented. The evaluation is analytical in nature rather than a measured prompt-injection success rate; Toolathlon uses only 20 tasks except for Flash.
- Evaluated models
- Gemini 3.8 FlashGemini 3.1 ProClaude Sonnet 5Claude Opus 5
- Benchmarks
- AgentDojoToolathlon
- Metrics
- Task Pass Rateattack block ratelatencytoken overhead
Sapien is a policy engine that enforces stateful context policies for autonomous AI agents, specifying allowed tool-call sequences with regular expressions extended with state predicates, and supporting deferred policy generation and scoped semantic checks. The authors claim Sapien's utility is within a few percentage points of an unconstrained agent; even when the agent is fully hijacked, its policy excludes 93-95% of attacks on AgentDojo and 62-85% of attacks on Toolathlon, and intercepts twice as much on long-horizon tasks as a tool allowlist.
Related events and news
1 events · 0 news mentions
- This event's paper
Sapien:面向自主AI Agent的有状态策略引擎
Paper analysis
What problem does this paper attempt to solve?
General agents need to constrain tool calls by task and history; static policies cannot do this.
The legitimate actions of a general-purpose agent depend on the current task and observed data; static or stateless policies cannot simultaneously preserve utility and block unauthorized tool calls.
- Scenario: The authors state that agents rely on LLM planning and external tool calls to complete long-horizon tasks; as trajectories lengthen, they become more susceptible to prompt injection hijacking, or may deviate from goals and misinterpret tool outputs. Examples include clearing an inbox, deleting a production database, attacking external infrastructure, and executing attacker-controlled commands. The authors consider this unreliability a major obstacle to deploying agents in production.
- Existing shortcomings: Classic reference monitors use pre-fixed static policies. For general-purpose agents, the same tool (e.g., send_money) is legitimate in a "refund" task but unauthorized in "summarize inbox." An allowlist that permits the tool leaves room for theft; one that forbids it interrupts legitimate refunds. The authors state that constraining only individual calls, or handing tool outputs back to the LLM each step to rewrite rules, is unsuitable for general-purpose agents whose requests vary.
- Core observation: The authors argue that how tightly a policy can wrap "appropriate trajectories" is limited by the expressiveness of the policy language (Figure 1). Stateless policies can only over-approximate; to block worst-case outcomes, whether the next step is allowed must depend on executed actions and observed data.
- This paper proposes: Sapien, a stateful policy engine. Before execution, it translates the user task prompt and tool documentation into a task-level policy, describing allowed tool call sequences with extended regular expressions, and enforces each tool call at runtime.
- Threat model:
- Goals and capabilities: The adversary can hijack the agent's LLM—via prompt injection in tool outputs, or directly through memory poisoning or weight modification—forcing it to propose arbitrary tool calls.
- Knowledge and isolation: The policy generator LLM is assumed to be normally trained and uncompromised, following Sapien's instructions as long as inputs contain no malicious data. The authors do not assume the generator resists prompt injection, so the generation phase only sees the user task prompt and tool documentation.
- Environment assumptions: The user session is uncompromised, and the task prompt comes from the user; tool behavior matches documentation; the harness and Sapien instrumentation are unbypassable and mediate every proposed tool call.
- Boundaries: Sapien provides safety (blocking unauthorized tool calls) but not liveness; it does not intervene when the agent is persuaded to stop or refuse tasks. A compromised agent may still leak information through timing or the order of allowed calls. The policy only specifies which calls are allowed, not when they occur or which path within the allowed set is taken.
What related research exists?
The authors position Sapien between contextual agent safety and runtime policy enforcement.
The authors position Sapien in terms of classic system defenses, contextual policies, and existing agent policy languages.
Reference monitors and static policies
- Anderson (1972), Saltzer and Schroeder (1975)—use a reference monitor to check program actions against explicit policies. Subsequent work includes system call filtering and path isolation.
- The authors' distinction: such policies come from fixed uses known at development time. The authors argue that a general agent's only fixed purpose in advance is "do what the user asks," which is too broad to yield a meaningful static policy.
Contextual agent safety
- Tsai and Bagdasarian (2025, Conseca)—synthesize task-specific policies on the fly from the user prompt for each request, enforced by a reference monitor on tool calls. The AllowList baseline follows this style, generating a tool-name allowlist from the task prompt.
- The authors' distinction: the authors adopt this framework but argue that tightly constraining long-horizon agents requires a stateful policy language; Conseca-style coarse-grained lists allow or deny a tool for an entire task without looking at arguments or execution state.
Policy systems with cross-call dependencies
- Existing systems (named in the text, including Progent, and systems discussed in §8 such as CaMeL and AgentSpec that depend on tool-call relationships)—express dependencies between tool calls, but the authors say their policies are static, derived in advance (by humans or offline LLMs) from fixed domain rules, suitable for single-purpose agents.
- Progent—uses an LLM to generate task-specific policies, but the language constrains only a single tool call; to adapt across steps, it feeds tool outputs back to the LLM after each call to rewrite the rules. The authors consider this different from "isolating untrusted content during generation."
- Judges that review agent behavior holistically with an LLM—the authors contrast this with Sapien's semantic predicates: the check is narrow and local, and the judge receives only the inputs needed to answer a yes/no question, not the full execution trace.
Baselines and benchmarks
- Baseline methods: NoPolicy (no policy) and AllowList (a per-task tool-name allowlist generated in a single LLM call in the Conseca style, without Sapien's self-correction round).
- Benchmarks/datasets: AgentDojo (97 short tasks, four suites) and Toolathlon (108 long-horizon tasks).
The authors frame the contribution as: the policy language and automaton execution engine target general agents whose legitimate actions can change with each user request, and current LLMs can synthesize fine-grained policies from natural language without requiring humans to write or audit policies.
How does the paper address this problem?
Generate a stateful policy before execution, and at runtime check each call with a binding-aware automaton.
Sapien works in two phases: before execution, a generator LLM synthesizes a task policy using only the task prompt and tool documentation; at runtime, an executor intercepts every tool call, and if disallowed, returns the rejection reason to the agent for self-correction rather than escalating to the user.
Problem setup and completeness
- Allowance condition: the extended trajectory (history calls plus the candidate call) must be a legal prefix of a sequence accepted by the policy.
- Policy completeness: the authors call "the generated policy reflects user intent" an informal invariant. An adversary-controlled policy is equivalent to having no policy. Isolation applies only to the generation phase; during execution, fixed policy checks can still use data observed by the agent, and the authors say this does not change the decision rules themselves.
- Non-goals: does not review whether the task prompt is harmful or accurately expresses the user's intent; ambiguous prompts yield broader policies. Human confirmation for high-risk operations can be placed after Sapien.
Policy language
The grammar in Figure 3 extends regular expressions with four kinds of primitives. Classic operators include sequencing (·), choice (+), and repetition (*, +); there is also shuffle (∥), which allows independent subtasks to interleave arbitrarily while preserving each one's internal order.
- Bindings and predicates: call patterns can bind arguments and return values to variables (@x); arguments can be literals or PREDICATE(p). p is a Python function supplied with the policy, evaluated only at runtime on concrete arguments. Bindings under iteration accumulate a list of records in execution order.
- defer: defer(g) leaves a hole in the policy. g takes no arguments and returns a policy-generation instruction string. At runtime the agent must call resolve; Sapien evaluates g on the bound variables, then has the generator produce a sub-policy and splice it into the hole. The authors argue that when the user delegates a subtask to an external source, expanding according to that source is closer to user intent than allowing arbitrary tools after fetching; if the source is tampered with, the sub-policy will be wrong, similar to a tampered task prompt.
- Semantic predicates: natural-language properties that cannot be checked in code are handled by the runtime helper verify_with_ai, which asks the LLM a scope-limited yes/no question with only the concrete values needed to answer. The authors say this predicate can only narrow the policy: even if the judge is fooled into returning True, the surrounding deterministic constraints still execute.
Automaton execution
- Compilation: the policy AST is translated via Thompson construction into a single-entry, single-exit NFA. shuffle takes the Cartesian product of the two operands' state sets. defer holes compile into a resolve transition.
- Configuration: the executor maintains active configurations (q, ρ), i.e., automaton state q plus variable assignments ρ on that path. can_advance(a, p) only checks without changing state; it allows if some configuration can take tool a after ε transitions and the argument constraints hold under ρ. advance(r) steps matching configurations after a call returns, extends bindings, and discards non-matching ones.
- Interface: init(u) generates and installs a policy when a user request arrives; on rejection it returns which argument failed which predicate and its source. The policy expression, predicate definitions, and generation rationale are appended to the agent context.
Prototype implementation
- Integration: a Python library that plugs into Google ADK and the AgentDojo and Toolathlon evaluation harnesses. Model calls go through the Gemini Enterprise Agent Platform. The same model both executes the agent and generates policies.
- Generation: a fixed system prompt defines the language and gives examples, requiring deterministic predicates first and verify_with_ai only for properties code cannot check. Two LLM calls per task: first draft a rationale and candidate policy, then self-correct against a checklist (e.g., syntax, whether necessary read-only tools are allowed) and produce the final policy and Python blocks. Delayed sub-policies replace the user prompt with the instruction string and include the parent policy as additional context.
- Evaluation and expansion: predicates reference bindings as free variables; the executor execs the Python block once in a custom global dict, fills in records from the current ρ, calls, then clears. The prototype does not use per-configuration expansion from §5.2 but does AST-level replacement, recompilation, and replay of the recorded trace. The authors say this simplification covers all tasks in the evaluation and requires at runtime that each hole be resolved at most once and that each configuration receive the same instruction string at that hole.
- Toolathlon extra constraints: all agents refuse local_python_execute in advance; Sapien is required to specify a command predicate for terminal_run_command.
What experiments did the paper conduct?
Utility is close to no-policy; under full hijacking AgentDojo blocks about 93–95% of attacks.
Experimental Setup
- Models: Gemini 3.8 Flash, Gemini 3.1 Pro, Claude Sonnet 5, Claude Opus 5. In each run, the agent execution and policy generation (Sapien or AllowList) use the same model.
- Benchmarks: AgentDojo has 97 short tasks (mostly within five turns), distributed across four suites: workspace, Slack, travel, banking, with 11–28 tools per suite; all four models run all 97 tasks and 949 attack instances. Toolathlon has 108 long-horizon tasks (tens of turns), including local files/shell and 32 applications, exposing over 600 tools via MCP; Gemini 3.8 Flash runs all 108 tasks and 212 attack instances, while the other three models, due to cost, run only a random 20 tasks and 40 attack instances.
- Baselines: NoPolicy; AllowList, generated by a single LLM call in Conseca style, without self-correction.
- Utility: Proportion of tasks completed in benign environments, using each benchmark's own completion criteria. AgentDojo compares the final environment state or tool call trajectory against per-task specifications; Toolathlon uses per-task verification scripts against the workspace and queries modified external services.
- Analytic safety: Assumes the attacker has already hijacked the agent, asking only whether the policy admits any sequence of tool calls that achieves the attack goal. Only two types of LLM calls are assumed faithful: (i) initial policy generation; (ii) defer resolution on inputs not contaminated by attacker data. All other calls are considered compromised: the agent can propose arbitrary tool calls, every verify_with_ai passes, and defer holes resolved on contaminated instructions allow all tool calls. Attack success is determined by three automated checks plus human adjudication: necessary tool check, trajectory replay (AgentDojo has ground-truth attack trajectories), and adversarial search by Gemini 3.8 Flash.
- Attack instances: AgentDojo pairs each user task with each injection task within a suite, yielding 949 instances; the authors retain instances where the user task never reads attacker data, because the agent is assumed compromised. Toolathlon has no pre-existing attack targets; the authors write 1–2 targets per user task aimed at that task's own tools and data, yielding 212 instances. The paper does not report the number of repetitions for utility or safety experiments.
Main Results
Utility and interception rate (interception rate = proportion of instances in the analytic evaluation where the attack goal is not achieved):
Swipe horizontally to read the table
Setting NoPolicy AllowList Sapien AgentDojo utility, Gemini 3.8 Flash (Figure 5, 97 tasks) 95.9% 94.8% 93.8% AgentDojo utility, Claude Opus 5 94.8% 92.8% 93.8% AgentDojo utility, Claude Sonnet 5 85.6% 88.7% 88.7% AgentDojo utility, Gemini 3.1 Pro 96.9% 91.8% 94.8% AgentDojo interception rate, four models (Figure 7, 949 instances) 0% 82.7–86.8% 93.2–95.2% Toolathlon full-set interception rate, Gemini 3.8 Flash only (212 instances) 0% 32.4% 64.6% Toolathlon 20-task subset interception rate, four models (40 instances) 0% 22.5–35.0% 62.5–85.0% - Utility: The authors report that on AgentDojo, Sapien completes 1–5 fewer tasks than NoPolicy (out of 97), and AllowList completes 0–2 fewer. On the full Toolathlon set, Gemini 3.8 Flash's Sapien task success rate is within 4% of NoPolicy. On the 20-task subset, across four models, Sapien succeeds in 43/80 task runs versus 45 for NoPolicy; Sapien fails at most 2 more tasks on any model, ties Gemini 3.1 Pro, exceeds NoPolicy on Claude Sonnet, and fails 1 and 2 more tasks on Gemini 3.8 Flash and Claude Opus 5, respectively. The authors state that AllowList is worse than Sapien and NoPolicy on all models, except tying on Opus 5.
- Safety: The authors report NoPolicy blocks 0%. On AgentDojo, Sapien blocks 93.2–95.2%, AllowList 82.7–86.8%. On Toolathlon, attack targets use tools required by the user task, and AllowList often permits them; on the full Flash set, Sapien blocks 64.6% versus AllowList's 32.4%, and on the subset 62.5–85.0% versus 22.5–35.0%. The abstract states AgentDojo 93–95%, Toolathlon 62–85%, and claims about twice the tool allowlist on long-horizon tasks.
- Unblocked attacks: The authors categorize them into three types, with semantic attacks accounting for 82.1% of unblocked instances on AgentDojo and 84% on Toolathlon. The paper text begins defining semantic attacks here (distinguishing benign from malicious is a semantic problem); the remaining categories are not fully listed in the provided text and are not supplemented.
Utility Failure Reasons
- What was tested: The authors discuss cases where Sapien policies cause task failure.
- Results: The generator does not see the runtime environment and may make incorrect assumptions about data or processes, e.g., the format or values expected by predicates may not match actual strings in the library; verify_with_ai may reject updates of a different type in the environment based on literal prompt wording; or it may omit necessary read-only tools and overly restrict the process.
- Authors' interpretation: The authors believe Sapien utility can be higher than AllowList for two reasons. AllowList must make an all-or-nothing decision on sensitive tools in advance and often does not permit them when the prompt does not explicitly require; Sapien can use parameter predicates and defer to tighten usage while permitting the tool. Second, staged policies give the agent implicit step guidance. One example: on AgentDojo's email TODO task, AllowList rejects send_email causing failure, while Sapien uses defer, and the resolved sub-policy only allows sending to the sender. The case where Sapien exceeds NoPolicy on Claude Sonnet occurs on a task where NoPolicy reaches the maximum number of turns; the authors state the policy helps the agent stay on a trajectory that can complete the task.
Other Ablations and Analyses
The provided text mentions efficiency (latency and overhead) at the start of §6.3 and states that on Toolathlon, Sapien's average number of inference calls is lower than a comparison (consistent with staged policy guidance), but specific latency, token, and inference counts do not appear in readable tables, so no numbers are filled. The paper does not report statistical significance tests.
What are some points that can be further explored?
Policies can still be too tight or miss semantic attacks; the analytical evaluation assumes the model is fully hijacked.
Limitations and future directions noted by the authors
The provided text has no separate Limitations or Future Work section. The following retains only what the authors explicitly mark as not done in the system assumptions and non-goals:
- No liveness guarantee: if a prompt injection only makes the agent stall or refuse the task, no unauthorized tool call occurs, and Sapien does not intervene (§3.1).
- No side-channel defense: a compromised agent could still leak information through timing or through the order between allowed calls; the policy does not specify when calls occur or which path among allowed options is taken (§3.1).
- No review of user intent itself: it does not judge whether the prompt is harmful or misstates the target, nor infer from the prompt whether high-risk operations need human confirmation; the latter can be placed in a separate confirmation policy (§3.3).
- Semantic gaps: the authors argue that in general no policy exists that admits only appropriate trajectories, because appropriateness may depend on natural-language semantics that are hard to specify precisely; semantic predicates are only a best-effort (§2.3, §4.4), and the judge can still be fooled by prompt injection.
- The generator can make mistakes: policies may use wrong formats due to unseen runtime data, overly literal semantic checks, or overly tight flows, thereby hindering task completion (§6.1).
Experimental coverage
- Models tested are Gemini 3.8 Flash, Gemini 3.1 Pro, Claude Sonnet 5, and Claude Opus 5, 4 in total; the same model both generates policies and executes the agent (§6).
- AgentDojo uses all 97 tasks, 949 attack instances, and four models; Toolathlon uses the full set of 108 tasks and 212 attack instances only for Gemini 3.8 Flash, while the other three models use a random 20 tasks and 40 attack instances (§6).
- Safety numbers come from an analytical method: the agent is assumed hijacked, verify_with_ai always passes, and defer on poisoned data allows all tools; only the initial policy generation and defer resolution on uncontaminated inputs are faithful (§6).
- Baselines are NoPolicy and a single-call AllowList without self-correction; utility uses each benchmark's built-in completion criteria (§6, §6.1).
- Prototype limitations: defer expansion in the evaluation is AST replacement with trace replay, requiring each hole to be resolved at most once and each configuration to receive the same instruction string (§5.3). The paper does not report the number of repetitions, nor specific latency numbers from the efficiency section (the text mentions §6.3, but the readable text has no corresponding table).
Summarize the main content of the paper
Sapien uses stateful contextual policies to constrain tool sequences, blocking most hijacked trajectories while approximately preserving utility.
Sapien is a stateful policy engine for general-purpose AI agents: before execution, it translates the user prompt into a task policy, and at runtime it only permits tool call sequences admitted by that policy.
- Problem: Legitimate calls vary with the task and observed data. Static allowlists either permit arbitrary parameters for tools like send_money or forbid legitimate uses. The authors argue that tight constraints require state: the next step depends on executed actions and return values.
- Method: The policy is an extended regular expression with shuffles, variable bindings, Python predicates, defer holes, and scope-limited verify_with_ai. The generator sees only the prompt and tool documentation, producing the policy through two rounds of drafting and self-correction. The executor compiles the policy into an NFA, tracks progress with (state, variable assignment) configurations, and returns predicate-level feedback on rejection. defer generates sub-policies after obtaining external sub-tasks.
- Utility: On AgentDojo, across four models, Sapien's task pass rates are 93.8%, 93.8%, 88.7%, 94.8% (Figure 5), completing 1–5 fewer tasks than NoPolicy (out of 97). On Toolathlon's 20 tasks × four models, Sapien succeeds in 43/80 runs versus 45 for NoPolicy; the full-set Flash success rate is within 4% of NoPolicy.
- Safety: Under the analytic setting where the agent is fully hijacked, NoPolicy intercepts 0%. Sapien intercepts 93.2–95.2% on AgentDojo's 949 instances (AllowList 82.7–86.8%); on Toolathlon's full set of 212 instances with Gemini 3.8 Flash, it intercepts 64.6% (AllowList 32.4%), and on the 20-task subset of 40 instances, 62.5–85.0% (AllowList 22.5–35.0%). Among unblocked instances, semantic attacks account for 82.1% on AgentDojo and 84% on Toolathlon.
- Authors' conclusion: The authors believe current LLMs can synthesize fine-grained policies from natural language, providing protection across diverse tasks without manual policy writing or auditing; statefulness is necessary to block worst-case outcomes in real tasks. At the same time, Sapien does not provide liveness, does not prevent side channels, and the policy generator may still write incorrect constraints due to lack of runtime data.