Manuscript Offprint
arXiv:2611.06039Securing Web Agents with the Compile-Then-Execute Paradigm
Annabella Chow UC Berkeley
Jinhao Zhu UC Berkeley
Sylvie Venuto UC Berkeley
Abdulaziz Alharbi KACST
Basel Alomair KACST
Raluca Popa UC Berkeley
David Wagner UC Berkeley
Julien Piet UC Berkeley
Abstract
Web agents commonly follow the ReAct paradigm, selecting each action from runtime observations that inherently mix trusted and untrusted content. This design makes their control flow vulnerable to prompt injections embedded in webpages. We introduce Baya¹, a compile-then-execute web agent designed to prevent prompt-injection-driven control-flow hijacking by design. Before accessing the live website, Baya compiles the user's request into an executable Python program that calls a Trusted Website API. The planning model does not observe live website content; only the compiled program processes it. Untrusted data may determine program values or select among branches defined during compilation, but it cannot redefine the user task or cause the model to synthesize new website operations at runtime. The Trusted Website API gives the compiler a unified view of the website's action space, enabling ahead-of-time planning without the stepwise action discovery required by reactive agents. Our evaluation across 581 valid WebArena Verified tasks shows that Baya achieves 77.8% aggregate utility, outperforming browser-only ReAct (55.1%) and API-enabled ReAct (66.7%). On WASP, a security benchmark for web agents, Baya achieves 0% attack success rate, compared with 16.2% for API-enabled ReAct and 25.5% for browser-only ReAct.
1 Introduction
Web agents have emerged as a promising interface for automating complex web tasks, such as retrieving information, shopping online, or planning travel. Modern web agents typically operate in a reactive loop: they observe the current webpage, reason about the next action, execute it through a browser interface, and repeat until the task is complete [37]. This ability to adapt to information revealed during execution
enables agents to operate on dynamic websites and complete complex, multi-step tasks.
The same adaptability creates a fundamental security risk. Unlike traditional software interfaces, webpages inherently contain a mixture of trusted and untrusted information, including content from the website itself, users, and third parties. When a reactive agent incorporates this content into its reasoning, attacker-controlled content can influence not only the data it processes but also the actions it selects. This opens the door to indirect prompt-injection attacks [10, 38], in which malicious web content can cause the agent to deviate from the user's intended task and perform attacker-chosen actions [33]. In this paper, we focus on preserving control-flow integrity: preventing untrusted web content from introducing attacker-chosen operations beyond the user's intended workflow.
Separating planning from execution and committing to a pre-compiled plan provides a structural defense against control-flow hijacking. Instead of allowing the agent to continuously decide its next action based on runtime webpage content, the agent first compiles a task-specific plan and then carries out that plan against the web. In this architecture, information retrieved from webpages is treated as runtime data consumed by a compiled plan, rather than as instructions that can arbitrarily redefine the agent's control flow. Prior work, such as CaMeL and FIDES, has demonstrated that compile-then-execute is an effective foundation for secure tool-calling agents [1,8,9,20]. A prior analysis of WebArena found that all benchmark tasks are compatible with this paradigm, assuming complete trusted APIs [28]. However, applying compile-then-execute to web agents is more challenging than to conventional tool-calling agents.
First, compile-then-execute requires knowledge, before execution, of which operations are available and what they mean. This is typically available to tool-calling agents through predefined and documented tool interfaces. In contrast, web agents must interact with heterogeneous websites whose operations and semantics may be undocumented, incomplete, or difficult to determine in advance. Most websites do not expose complete, documented, and semantically meaningful APIs
¹Baya is named after the Baya Weaver, a Southeast/South Asian native bird known for building intricate hanging nests that protect eggs and chicks, a parallel to our compile-then-execute design, which constructs a secure plan before execution.
for all actions available through their user interfaces. As a result, there is a missing abstraction between today's web infrastructure and the stable semantic interface required by a compile-then-execute agent.
Second, even when trusted website APIs are available, there typically is little or no documentation of their semantics, dependencies, and site-specific rules. As a result, the agent must discover these rules, catch failures, diagnose their cause, and adapt the plan securely. Past work typically focuses on “one-shotting” the plan, but we’ve found that web agents must revise and repair failing plans, which is challenging to do securely.
In this paper, we introduce Baya, a web agent based on the compile-then-execute paradigm that addresses these challenges for tasks whose workflows can be determined before execution. During compilation, the agent emits an executable program, fixing its control flow and possible API interactions before live execution begins. Runtime data may fill program variables or select among branches defined during compilation, but it cannot introduce new task instructions.
Baya consists of three main components. First, we take a first step toward understanding what API abstractions are sufficient for web agents by manually constructing a Trusted Website API that presents native REST endpoints and wrappers for UI-only functionality through a unified, documented interface augmented with site-specific execution constraints and prerequisites. This interface is prepared for each website before user tasks are processed; automating its construction remains future work. Second, a sandboxed coding agent compiles the user's task into a Python program and validates it using mocked tests without accessing the live website. A catalog of available APIs, search tools over this catalog, and site-specific guidance help Baya find the relevant operations and write a program that uses them correctly. Third, an isolated execution engine runs the program against the live website. If execution fails, it exposes restricted diagnostic feedback to help the compiler repair the program. Feedback is restricted to prevent it becoming a channel for attack.
By separating task compilation from runtime web interaction, Baya limits the ability of untrusted webpage content to alter the agent's intended control flow while retaining the ability to consume web data during execution. Outcome manipulation and general data-flow security are outside our scope. Beyond security, Baya improves utility by providing a structured view of the website's available operations, reducing uncertainty about how to accomplish the user's task.
We evaluate Baya along three dimensions: utility, security, and efficiency. We measure task completion using WebArena Verified [12], a manually audited revision of WebArena [42]. We compare Baya to two simple ReAct agents (ReAct_web + API and ReAct_web) and to Untrusted Content Masking (UCM), a secure ReAct-style web agent that masks and quarantines untrusted content [25], and evaluate latency and execution cost. To assess security, we evaluate Baya on
Table 1: Overview of utility, security, and efficiency. Utility is averaged over four environments, security over two.
| System | Utility ↑ | ASR ↓ | Latency (s) ↓ |
|---|---|---|---|
| Baya | 77.8% | 0.0% | 327.15 |
| ReAct_web + API | 66.7% | 16.2% | 86.60 |
| ReAct_web | 55.1% | 25.5% | 59.91 |
| UCM² | 75.3% | 0.0% | 469.04 |
WASP [13], measuring its robustness against prompt-injection attacks embedded in web content. Across four environments, Baya has the highest aggregate utility with all three models, outperforming ReAct_web + API and ReAct_web by 11.1 and 22.7 percentage points, respectively. On GitLab, Baya also outperforms UCM by 17.6 percentage points. Moreover, Baya achieves 0% observed intermediate and end-to-end ASR on WASP, compared to the ReAct baselines' aggregate ASRs of 16.2% and 25.5%, respectively.
At the interaction layer, vision-based agents operate on screenshots and issue keyboard or pointer actions [18, 41]. DOM-based agents inspect structured page representations, such as the DOM or accessibility tree, and invoke browser actions on referenced elements [7, 42]. API-based agents invoke structured website operations without directly manipulating the browser interface [28, 29], while hybrid agents combine API and browser access [30, 39]. These interfaces determine how an action is expressed, but they do not determine when or how the agent selects that action.
At the control layer, a common architecture is ReAct, which interleaves model reasoning with environment interaction [37]. At each step, the model receives the user goal and the latest environment observation, selects one action, executes the action, and observes the result before selecting its next action. Consequently, the agent's future actions and control flow remain unspecified until runtime observations become available. This property applies regardless of whether the observation originates from a screenshot, a structured page representation, or an API response.
2.1 Security Challenges
The web is a mixed information environment. A single webpage often combines trusted, site-provided interface elements
²UCM is evaluated on GitLab environment only.
with untrusted content from users or third parties, such as product reviews, forum posts, advertisements, and embedded widgets. The trust boundary is often ambiguous, making it difficult for agents to tell apart trusted from untrusted information. Even if they could, ignoring untrusted data would sacrifice utility; for example, an agent tasked with summarizing product reviews inherently needs to read user-supplied text to succeed.
This mixed environment creates a security flaw for ReAct-based agents. Because ReAct determines its control flow dynamically, untrusted web content is presented to the language model exactly when it is deciding on its next action. By collapsing observation and action selection into a single inference step, the agent's decision process can be hijacked by untrusted content through indirect prompt injection attacks.
We distinguish between two primary goals an attacker might pursue via prompt injection: control-flow hijacking and outcome manipulation. Baya protects against control-flow hijacking, outcome manipulation is out of scope.
Control-flow hijacking is the most severe threat, analogous to arbitrary code execution. Because a ReAct agent continuously generates arbitrary tool calls on the fly, an attacker can use prompt injection to make the model deviate from the user's intent and synthesize entirely new, unauthorized actions at runtime. For example, malicious text in a forum post could instruct an agent to navigate to a settings page and exfiltrate the user's private data. This is a "confused deputy" vulnerability: because web agents often act with the user's logged-in authority, injected instructions can trick the privileged agent into using its authority on behalf of the attacker. The more tools and permissions the agent has access to, the more reach the attacker has.
Outcome manipulation, on the other hand, is closer to a data-only attack. Here, the attacker influences the outcome of the user's task without changing the task itself or forcing the agent to invoke unintended tools. For instance, an adversarial seller might use injected text to trick an agent into purchasing a counterfeit product instead of the legitimate item the user requested.
The distinction is whether untrusted content can expand or redefine the agent's workflow. Outcome manipulation changes runtime values or selects among branches already permitted by the workflow, whereas control-flow hijacking introduces attacker-directed operations or branches.
2.2 The Architectural Gap
Several existing defenses attempt to secure the ReAct loop by hardening the underlying language models to ignore malicious instructions, by wrapping the agent in runtime monitors to block unauthorized actions, or by having the agent write a high-level plan before proceeding with a ReAct loop. These methods fail to address the core architectural flaw: interleaving planning with untrusted observations [23, 31, 32, 40].
A recent line of work in structural defenses, such as CaMeL [9], attempts to remove this vulnerability by strictly separating planning from execution. In this paradigm, a language model converts the trusted user query into a program before any interaction with the environment occurs, and this code is then executed by an interpreter. Because the control flow is fixed as a static program before runtime data is observed, untrusted content is confined to variables. It cannot modify the program's execution path or synthesize new actions.
However, these plan-then-execute approaches have so far only been applied to simple agentic environments with a small, well-defined action space [1,8–10]. In these settings, the agent has full visibility into the available tools, and the side effects of each action are known prior to execution.
Existing web interfaces do not naturally provide this abstraction. Low-level browser actions, such as clicking or typing, derive their meaning from the current rendered page, and many actions become visible only after earlier interactions. Native backend APIs provide more stable operations, but they are frequently incomplete, undocumented, or inconsistent with functionality exposed through the user interface. Consequently, neither browser actions nor raw backend APIs directly provide the complete, semantically specified action space required for compile-then-execute.
3 Problem Setup
3.1 Goals
Our design pursues two goals: preserving the control-flow integrity of the user's task and maintaining utility on user tasks.
Security. Our primary security goal is to completely prevent control-flow hijacking. An attacker must not be able to override the user's original intent or synthesize new, unauthorized actions at runtime. The operations available to the agent and their control dependencies must be determined exclusively from the trusted user request and trusted website interface before live execution begins. Untrusted runtime data may instantiate program variables and select among branches defined during compilation, but it must not introduce new operations, execution branches, or tasks.
Our security objective is limited to preventing control-flow hijacking. Outcome manipulation, misinformation, false information, denial-of-service attacks, and compromises of trusted components are outside our scope.
Utility. We also seek to build a useful web agent that can execute user tasks. A fundamental limitation of compile-then-execute is that it cannot support tasks where the workflow is not determined by the user task (e.g., “open my email inbox, find the email from my boss, and do whatever it says to do”). To evaluate how many user tasks are compatible with

Figure 1: Architecture of Baya. Baya generates an executable program using trusted API specifications without accessing website data. During execution, untrusted data is consumed by the program but cannot alter its precompiled control-flow structure. Replanning occurs only upon execution failure, with only restricted error diagnostics and the existing code passed back to the Code Generator, without exposing any website data.
compile-then-execute, we classify web tasks into one of three categories:
- Safe. The complete task can be expressed as a deterministic program that processes runtime data without invoking a language model. For example, adding the highest-rated noise-canceling headphones under $200 to a cart requires retrieval, sorting, and a predetermined cart operation.
- Safe with Influence. The website operations and control-flow structure can be fixed before execution, but the task may require a runtime model to interpret unstructured data. For example, summarizing product reviews requires semantic processing, but the runtime model need not invoke tools or modify the compiled workflow.
- Replan-Needed. The operations required to complete the task must be derived from untrusted runtime content. For example, a request to read incoming emails and complete every action item requires the agent to treat untrusted email content as a source of new tasks.
Compile-then-execute can securely support both Safe and Safe with Influence, but cannot support Replan-Needed tasks, which are incompatible with the restrictions needed for security.
A prior analysis [28] of WebArena [42] classifies 81% of WebArena tasks as Safe, 19% as Safe with Influence, and none as Replan-Needed. This suggests that compile-then-execute can support many web tasks.
3.2 Threat Model
We focus on indirect prompt-injection attacks against web agents. The user assigns the agent a benign web task, and the attacker embeds malicious instructions in content that the agent may process while completing that task.
We consider third-party attackers, such as commenters, reviewers, forum users, third-party sellers, and advertisers. We assume that website operators and model providers are trusted and do not participate in the attack. Accordingly, the website backend and the code implementing its APIs are part of our trusted computing base. We assume that these components correctly implement the website's intended functionality.
In contrast, content originating from website users or other third parties is untrusted. This content remains untrusted whether the agent retrieves it through a rendered webpage, a native website API, or a browser-backed API wrapper. We treat any such content encountered during live execution as potentially attacker-controlled.
4 System Design
Baya³ processes web tasks in two isolated phases (Fig. 1). During compilation, a sandboxed coding harness generates and validates a Python program using the Trusted Website
³https://github.com/apechow/Baya
API, without accessing live website content. During execution, a separate engine runs the program against the live website.
4.1 Constructing the Trusted API
Central to this architecture is the Trusted Website API, which acts as the core abstraction enabling ahead-of-time planning. We require the Trusted Website API to be functionally complete over the target task space, strictly typed to support static code generation, and richly documented so that Baya can determine the semantic meaning of each operation prior to execution.
Baya does not assume that such an interface is already provided by the website. Thus, before Baya processes user tasks, we construct a Trusted Website API for each target website that exposes the operations the agent may need. This construction is part of the trusted, offline setup of the system: once the interface is fixed, Baya plans only over these predefined operations and cannot introduce new website capabilities at runtime. Consequently, replanning can correct how an existing operation is used, but cannot recover an operation that is absent from the Trusted Website API.
To construct this interface in WebArena, we begin with the website's native backend REST APIs, which provide structured access to much of the site's functionality. We manually inspect each website's backend and available API documentation to identify its supported operations, extract their schemas, normalize inconsistencies in their request and response specifications, and augment them with missing semantic constraints needed for correct use. Native APIs, however, do not cover all functionality exposed through the website UI. Through manual inspection of the website's functionality, we identify gaps in the available backend operations and fill them with trusted browser-automation operations implemented using Playwright. These additional operations are exposed through the same typed interface, providing sufficient coverage of the website's functionality for agents to accomplish user tasks without direct browser interaction. The resulting Trusted Website API is thus a curated combination of native backend operations and additional trusted operations.
Constructing this interface is nontrivial because real websites expose heterogeneous schemas, omit execution-critical constraints, and often lack backend operations corresponding to UI functionality. Below, we use the WebArena websites as a case study to characterize these challenges and then describe the contract we impose on every operation in the Trusted Website API.
4.1.1 Challenges in Real-World Website APIs
Challenge 1: Heterogeneous and Underspecified Schema Dialects. Even among REST APIs, request formats and parameter conventions differ substantially across websites. For example, searching and filtering on the Shopping site requires a specific nested bracket parameter format: searchCriteria[filterGroups][0][filters][0][conditionType]. The composition semantics are not self-explanatory: filters with the same filterGroups index are combined using OR, whereas filters with different indices are combined using AND. Furthermore, although Shopping and Shopping Admin share the same Magento backend, they assign different semantics to identical features: item variants are represented as option IDs in Shopping, but as distinct child products with individual SKUs in Shopping Admin. Additionally, websites use conflicting conventions for request bodies: GitLab describes parameters using formData or a generic body field, whereas Shopping uses auto-generated parameter names that do not match actual JSON payload keys, hindering valid request serialization. Representative API schema excerpts are provided in Fig. 7.
Challenge 2: Incomplete Descriptions and Undocumented Constraints. Schemas frequently omit constraints required for successful execution. For example, GitLab exposes extensive REST APIs but omits response descriptions. Shopping's add-to-cart documentation marks product options as optional. In reality, configurable products (such as clothing or shoes) fail unless specific size and color options are supplied. Because option types and valid values vary per product, the agent must first inspect the product's available options before constructing the add-to-cart mutation. Such dependencies and identifier formats (e.g., whether an endpoint expects a numeric user ID or a username string) are absent from raw endpoint schemas.
Challenge 3: Incomplete Task Coverage and UI Semantic Disconnect. Backend REST APIs frequently fail to cover the full range of operations supported by website user interfaces. For example, WebArena's Postmill forum supports only 16 REST APIs, which are enough for only 33% of its tasks [28]; operations such as voting or replying to a forum have no REST counterpart. In GitLab, administrative actions such as generating an RSS token are UI-only. Similarly, Shopping Admin reports on popular search terms and best-selling items are accessible exclusively through the admin dashboard. Furthermore, REST endpoints for search often support only exact-match searches, whereas the UI supports fuzzy search. For instance, Shopping's product-search API requires the exact product title, failing on descriptive queries such as "reorder the makeup removal kit I bought in summer 2022", which the storefront search UI resolves natively.
These coverage gaps cannot be resolved by schema normalization alone because the required backend operation simply does not exist. During construction of the Trusted Website API, we therefore identify task-relevant UI functionality not covered by native APIs and implement corresponding trusted Playwright operations. These operations expose the same high-level semantics as native API operations while hiding low-level browser interaction from Baya.
4.1.2 API Contracts
To bridge these gaps, Baya structures its action space as a Trusted Website API. Formally, we define a Trusted Website API as a collection of callable operations , where each operation is governed by a machine-readable contract structured as:
-
Type Signature (): A function signature . All input parameters and return structures are defined as strongly typed records (e.g., Python data-classes) with explicit primitive types, structural constraints, and field-level docstrings.
-
Preconditions (P): Constraints on input states required prior to invocation. This includes authentication token availability, session requirements, or prerequisite queries (e.g., querying the available stock of an item before adding it to the cart), and API-specific parameter conventions.
-
Postconditions & Side Effects (Q): What the function returns and how it changes the state of the website upon successful invocation. Contracts explicitly categorize operations into idempotent reads (pure data retrieval) and stateful mutations (e.g., order submission, entity creation).
-
Error Domain (E): An exhaustive declaration of structured error conditions (e.g., entity not found, invalid parameter, authentication expired) mapped to typed exceptions, ensuring that partial failures do not emit unstructured or untyped side effects.
This contract directly overcomes the three practical challenges. By canonicalizing request parameters and response schemas into strongly typed signatures , the contract eliminates the dialect heterogeneity of raw HTTP interfaces (Challenge 1). By encoding prerequisite lookups, identifier formats, and execution constraints within preconditions and side-effect guarantees within postconditions , the specification provides known execution requirements upfront (Challenge 2). Finally, the contract establishes a uniform interface whose underlying implementation is chosen based on backend availability: an operation is implemented via a backend REST API when available, or via Playwright browser automation when functionality is exposed exclusively through the user interface or requires fuzzy storefront search (Challenge 3). Because both implementations satisfy the exact same signature and return structure , the planner targets a complete, consistent action space without exposing the planning process to DOM-level mechanics.
4.1.3 Worked Example: Product Search Endpoint
Figure 2 illustrates this architecture with a concrete worked example for an e-commerce product search endpoint.
Contract Specification. As shown at the top of Figure 2, the operation search_products defines a formal contract returning a list of ProductListing objects. The return structure specifies exact fields: sku, name, price, in_stock, rating, and url. The preconditions require non-empty queries and valid authentication. The postconditions certify that the operation is an idempotent read with zero server-side mutations and returns an empty list [] when no products match, while the error domain maps HTTP 401/403 to AuthenticationError and returns an empty list [] when no products match.
Implementation Alternatives. The lower half of Figure 2 illustrates two alternative implementations of this contract depending on backend availability:
-
REST Implementation (Left): Serializes the query into Magento's complex nested bracket parameter structure (searchCriteria[filterGroups]...), issues a GET/rest/V1/products request with authorization headers, checks response status, and maps raw JSON dictionary keys into typed ProductListing dataclass instances.
-
Playwright Implementation (Right): Launches a headless browser, navigates to the storefront search URL (/catalog search/result/?q=...), locates rendered product cards via DOM selectors (.product-item-info), parses price strings and stock availability indicators, and returns a list of ProductListing instances identical in structure and type to the REST binding.
During compilation, Baya writes and tests its program against the abstract ProductListing contract using mocked unit tests, targeting a uniform typed interface regardless of whether a given function executes via REST or Playwright.
API Construction Limitations. While we manually construct Trusted Website APIs for the fixed WebArena environments, extending Baya to arbitrary websites requires scalable methods for discovering and validating trusted operations. Existing systems such as Libretto demonstrate how browser interactions can be converted into reusable workflows [22]. However, automating this process introduces a new security challenge: prompt injections encountered during website exploration could influence operations subsequently treated as trusted. We discuss this further in Section 6.2.
4.2 Compile-then-Execute
To complete web tasks without exposing the planning process to untrusted live-site content, Baya separates program generation from live execution. It uses a two-phase Compile-then-Execute architecture. During compilation, a coding harness connected to an LLM translates the task into an executable program using the provided API information, site-specific rules, and output requirements. During execution, a separate execution engine runs the generated program against the live site. The two phases communicate through generated artifacts and restricted error diagnostics rather than through an interactive session.
RFC-Style Contract Specification: search_products
- Signature (Σ): search_products(query: str) -> List[ProductListing]
- Data Structure (O): ProductListing {sku: str, name: str, price: float, in_stock: bool, rating: Optional[float], url: str}
- Preconditions (P): len(query) > 0; valid auth token for protected catalogs.
- Postconditions (Q): Returns matching listings ordered by relevance. Idempotent read; no state mutation.
- Error Domain (E): Raises AuthenticationError on 401/403; returns [] on zero matches.
- Backend REST Implementation
search_products(min_price, max_price): params <- { filterGroups[0].filters[0] = price >= min_price filterGroups[0].filters[1] = price <= max_price }
response <- GET /products with params return response.items as ProductListing
- Headless Playwright Implementation
search_products(query): navigate to search page with query results <- displayed products
for each result: extract sku, name, price
return results as ProductListing
Figure 2: Example Trusted Website API contract and its REST and Playwright implementations for an e-commerce product search endpoint.
4.2.1 Compilation
Because Baya cannot probe the live site, it must receive enough information to construct a working program in advance. At the beginning of each task, the agent receives the task intent, starting project path, account identity, authentication instructions, output requirements, and Trusted Website API information. These specifications include a complete endpoint catalog, tools for searching and inspecting API contracts, and site-specific execution requirements. For each operation, the contract specifies its signature (Σ), preconditions (P), such as prerequisite lookups and identifier resolution, postconditions and side effects (Q), and structured error conditions (E).
API Discovery. Baya’s API discovery is efficient and scalable, avoiding the context-window costs of loading complete API schemas upfront. Loading an entire website’s API schema into an LLM’s context window is impractical. A single website may expose hundreds or thousands of operations, and loading schemas for additional websites upfront causes context consumption to grow accordingly. For example, GitLab exposes 1,028 executable REST APIs, and its schema file size is approximately 1.8 MB. Loading the complete schema would consume a substantial portion of the agent’s context window before it begins reasoning about the task.
To address this challenge, Baya provides several levels of API discovery without requiring the agent to read the complete schema. Site-specific execution requirements describe common pitfalls and preferred endpoint choices, while a compact endpoint catalog lists all available paths and methods. The agent can then use Baya’s curated tools to search for relevant endpoints and retrieve detailed schemas only for the selected operations. Anthropic’s Tool Search Tool follows a similar high-level principle, avoiding loading all tool definitions upfront and instead discovering and expanding only those relevant to the current task [35].
Reliable program construction. Discovering the relevant API operations is only one part of compilation; the agent must also compose them into a program that executes reliably within its resource budget.
Efficient retrieval presents a tradeoff between underconstrained searches that retrieve too many candidates and overly restrictive filters that discard valid results. For example, a generic product search on the Shopping website may fetch and inspect up to 100 pages, potentially requiring additional API calls for every product on each page. Such searches can quickly exhaust the execution-time budget. Server-side filters and deterministic local matching can reduce this cost, but they may be insufficient for tasks requiring semantic judgment. For example, a task asking for reviewers who mention that a product’s ear cups are too small cannot be solved reliably by matching only the word “small,” since reviewers may describe the same issue using different words or phrases.
To balance these competing concerns, we prompt Baya to use server-side filters, bound pagination, and apply deterministic matching utilities whenever possible. For tasks requiring semantic judgment, the generated program may instead include a narrowly scoped runtime LLM call after deterministically narrowing the candidate set. This approach aims to reduce unnecessary API calls while preserving flexibility for
Figure 3: Pseudocode of a program generated by Baya to update a user's biography on the discussion forum.
| Generated Program (Pseudocode) |
|---|
| USERNAME <- "MarvelsGrantMan136"NEW_BIO <- "Freelance Web Developer" |
| update_biography():response <- POST /update_biography {username: USERNAME,biography: NEW_BIO} |
| if request failed orresponse.success is false:report error and exit |
| report success |
semantic matching, although both underconstrained retrieval and overly restrictive filtering remain possible. We examine these failure modes in our evaluation.
Generated artifacts. Baya produces two artifacts in the compilation phase: a task-specific Python program and a companion unit-test file (e.g., Fig. 3 and Fig. 4). The generated program is a restricted Python script: it uses the Python standard library for local computation, invokes only the trusted APIs for website access, and does not use arbitrary code execution or unrestricted network access. Retrieval, filtering, counting, arithmetic, sorting, and exact or fuzzy matching are implemented using deterministic code. When a task requires semantic interpretation of free-form text that cannot be expressed reliably using deterministic logic, the program may include a narrowly scoped, data-only LLM call. Such a call operates only on candidate data already retrieved and narrowed through trusted APIs; it cannot retrieve additional data or perform actions on the website. During compilation, Baya has no access to the live website and validates the program entirely against local mocks. The companion test file mocks all HTTP requests, authentication and credentials, and any LLM client used by the program, and tests both successful execution and expected error paths. Section 9.4 Fig. 6 illustrates a toy program and artifacts that Baya might generate.
4.2.2 Design Guarantees and Restrictions
The security of the design depends on preventing live-site data from influencing the program while it is being generated. Therefore, compilation and execution are separated in time, process, privilege, and information. Code is generated before live execution begins, and the coding harness and execution engine run as separate processes. The compilation process receives only the information and permissions needed
Figure 4: Pseudocode of generated unit tests that validate successful execution, anticipated failures, and final-answer formatting without contacting the live service.
| Generated Tests (Pseudocode) |
|---|
| test_success():mock successrun update_biography()assert correct request and success |
| test_failures():for failure in [HTTP error, API failure, invalid JSON, exception]:mock failureassert update_biography() exits |
| test_final_answer():mock successoutput <- main()assert output contains NEW_BIO |
to generate and test the program, whereas the execution process receives the runtime domains and credentials needed to interact with the live site.
To enforce this boundary, Baya can read only the provided task context, approved API schemas and supporting tools, and files in its assigned task directory. It can write only to that task directory. It cannot access any websites, the network, web search, credentials, evaluation tests, coding-harness memory, Git metadata, or unrelated files. Consequently, the agent must construct the program using the task and trusted API information rather than information retrieved from the web or live site.
These restrictions are enforced through multiple layers, including coding-harness permissions, tool restrictions, an OS-level filesystem sandbox, a network sandbox, and explicit prompt instructions. The concrete harness settings, filesystem allowlists, permitted commands, and network-sandbox configuration are provided in Section 9.4 Fig. 5.
4.2.3 Validation
The goal of validation is not to guarantee that the program will avoid every runtime failure, but to verify that it detects and reports anticipated classes of failures correctly. In-scope conditions include non-2xx API responses; empty result sets; missing, null, or incorrectly typed parameters or response fields; operations over empty inputs; and unparseable dates or numbers. The tests also verify that identifiers are resolved from mocked runtime responses rather than hardcoded and, when the program uses an LLM for filtering, that the call uses the configured model and correctly handles a “none of these” result.
For example, suppose a task asks Baya to add a clothing item to the user's wishlist. The API schema marks the quantity parameter as optional, so the compiled program may omit it, even though the live /wishlist endpoint actually requires it and returns an HTTP 500 response when it is absent. Validation cannot infer this undocumented requirement or prevent the runtime failure. It can, however, verify that if an API call returns a non-2xx response, the program detects the error, reports relevant diagnostic information, and exits with an error code rather than producing a final answer. During live execution, this error is then passed back to Baya, which can regenerate a new plan that accounts for the previously undocumented requirement.
Thus, unit testing verifies the program's behavior under anticipated conditions without performing the task or interacting with the live site. Failures that depend on undocumented or otherwise unobserved live-site behavior are discovered during execution and handled through replanning.
4.2.4 Execution
After validation, a separate execution engine receives the generated program and runs it against the live website in a Python subprocess. The execution engine itself simply executes Python code, which retrieves data or modifies website state through trusted API operations. The code itself may contain LLM calls which are only used for data processing, producing no side effects and returning typed variables. During execution, the program records its progress in a Python output log. If execution succeeds, the program returns its final answer. Otherwise, Baya may replan (generate a new plan, based on the received error code) and retry the program up to three times.
4.2.5 Error Handling and Replanning
Local validation cannot anticipate every failure that may arise when a generated program interacts with the live website, as discussed in Section 4.2.3. When execution fails, Baya may replan using the previously generated program together with the restricted error diagnostic. For example, a failed product query may return:
ERROR search_products returned HTTP 400 ERROR Response body: {"message": "Invalid filter field: category"} ERROR Product search failed
This feedback allows the compiler to revise the program, for example by replacing an unsupported category filter with a supported query parameter.
This error channel does not expose arbitrary website content to the planning model. The program itself was generated before execution and therefore contains no content obtained from the live website. In particular, non-2xx error responses may contain backend-generated diagnostics such as invalid-parameter names, missing required fields, authentication failures, or malformed requests, but they must not contain or reflect stored resources, successful response values, request values derived from website content, or other user-controlled website data. Thus, an endpoint may report that quantity is required, but it cannot include a product description, review, username, post body, or other content obtained from the website.
This restriction is necessary because values manipulated by the generated program may themselves originate from prior API responses. Baya therefore does not rely on whether a value appears in a request or an exception to determine whether it is safe to expose during replanning. Instead, the replanning interface admits only diagnostics explicitly generated by the trusted API implementation; runtime values and website-derived data are excluded. An API operation that reflects attacker-controlled or website-derived content into its error message would violate the Trusted Website API contract and is outside our threat model.
Only an observable failure triggers another compilation attempt. During replanning, the agent receives the previous program and the restricted error diagnostics, then revises the implementation accordingly. Replanning stops once the program successfully returns an answer or after at most three replans. The program distinguishes legitimate empty results from execution failures by reporting the number of results found without exposing their contents, while API failures produce error diagnostics without exposing website data. Legitimate empty results may be returned as “not found,” whereas authentication failures, rate limits, server errors, timeouts, parsing failures, and other execution errors remain failures.
5 Evaluation
We structure our evaluation around three dimensions: utility, security, and efficiency. First, we measure how reliably Baya completes benign web tasks relative to reactive baselines. We then evaluate whether Baya prevents control-flow hijacking while preserving utility on the intended task. Finally, we measure the computational and latency overhead introduced by Baya relative to the evaluated baselines.
We evaluate Baya and the ReAct baselines using three model families: claude-sonnet-4.6 [2], gemini-3.5-f1ash [15], and gpt-5.6-luna [26]. For security evaluation, we replace gpt-5.6-luna with deepseek-v4-flash-0731 [11]. See Section 9.2 for more details.
5.1 Benchmarks
Utility: WebArena [42] evaluates agents on realistic tasks across multiple self-hosted websites. Each task specifies a natural-language intent, one or more starting URLs, and an evaluator that determines whether the task was completed successfully. We evaluate the four environments supported by Baya: GitLab, Shopping, Shopping Admin, and Postmill. We use a subset of the revised task intents and corrected ground truth from WebArena Verified [12], excluding tasks that have vague intents or cannot be evaluated due to the inherent nature of the task (i.e. drafting a message without submitting the form). We adapt the WebArena evaluation suite to score API-based agents by task outcome rather than browser-specific interaction traces. See Section 9.1 for more details.
Security: We evaluate resistance to prompt-injection-driven control-flow hijacking using WASP [13]. We evaluate 12 Git-Lab and 9 Postmill attack templates, each paired with two benign user goals and two injection formats, producing 48 Git-Lab and 36 Postmill attack instances. We report intermediate attack success rate (ASR), end-to-end ASR, and benign-task utility.
5.2 Baselines
We compare Baya against two reactive agent configurations and one security-oriented web agent.
ReAct baselines. We implement a ReAct agent that alternates between model inference and environment interaction. At each step, the model observes the current environment state, reasons about the task, and emits one action. The resulting observation is returned to the model before it selects the next action. This process continues until the agent completes the task, enters a repeated-action loop, or reaches the 30-step limit. We evaluate two tool configurations. ReAct_web interacts with websites exclusively through browser actions. ReAct_web + API can use both browser actions and API calls, and receives the same API schemas and site-specific guidance as Baya. Comparing Baya with ReAct_web + API isolates the effect of compile-then-execute from the effect of providing structured website interfaces.
Untrusted Content Masking. We compare Baya with Untrusted Content Masking (UCM) [25], a security-oriented browser agent that masks untrusted page regions from the primary agent. When the agent must inspect a masked region, UCM routes the content through a quarantined model whose output is restricted by type. Because UCM requires site-specific masking rules, we evaluate it only on GitLab, for which the published implementation provides the necessary rules. We allow UCM up to 120 steps to align with their original evaluation, and we use Claude Sonnet-4.5 for the quarantined model.
Other baselines. We also considered ceLLMate [23] and Single-Shot Planning for Computer Use Agents (CUAs) [14], two defenses against control-flow hijacking attacks. However, neither system can be evaluated directly on WebArena Verified using its published experimental setup. Like Baya, ceLLMate relies on site-specific artifacts prepared before deployment; specifically, it uses a browser-level sandbox to enforce security policies assumed to be provided by each web-
Table 2: Utility on valid WebArena tasks. Bold indicates the highest utility within each model and environment.
| Model | System | GitLab | Shopping | Shopping Admin | Postmill |
|---|---|---|---|---|---|
| n = 154 | n = 171 | n = 150 | n = 106 | ||
| Claude Sonnet-4.6 | Baya | 92.9% | 71.3% | 81.3% | 84.0% |
| ReAct_web | 64.9% | 53.2% | 48.0% | 38.7% | |
| ReAct_web + API | 77.3% | 50.3% | 64.7% | 38.7% | |
| Gemini-3.5 Flash | Baya | 85.1% | 74.3% | 70.7% | 86.8% |
| ReAct_web | 45.5% | 60.2% | 48.7% | 47.2% | |
| ReAct_web + API | 75.3% | 70.8% | 86.0% | 42.5% | |
| GPT-5.6 Luna | Baya | 72.1% | 62.0% | 78.7% | 83.0% |
| ReAct_web | 69.5% | 59.1% | 70.7% | 43.4% | |
| ReAct_web + API | 72.1% | 69.0% | 89.3% | 43.4% |
site. Because the published implementation does not include policies for WebArena Verified, evaluating ceLLMate would require us to construct additional benchmark-specific policies, precluding a direct comparison with the published system. CUA's implementation and evaluation target OSWorld and do not provide an integration with WebArena Verified. We therefore could not report empirical utility or security results for these systems.
5.3 Utility
Table 2 reports utility on the 581 tasks retained by our interface-neutral evaluation protocol. Across all four environments, Baya completes 476/581 tasks (81.9%) with Claude Sonnet-4.6, 456/581 tasks (78.5%) with Gemini-3.5-Flash, and 423/581 tasks (72.8%) with GPT-5.6-Luna. Baya achieves the highest aggregate utility with all three models. Its advantage over the stronger aggregate ReAct baseline ranges from 2.4 percentage points with GPT-5.6-Luna to 22.9 percentage points with Claude Sonnet-4.6.
Comparison with reactive agents. With Claude Sonnet-4.6, Baya achieves the highest utility in every environment and reaches 81.9% aggregate utility, compared with 59.0% for ReAct_web + API and 52.3% for ReAct_web. Across all models and environments, Baya ranks first or ties for first in nine of the twelve model-environment combinations. Compared specifically with ReAct_web + API, Baya performs better in eight combinations, ties in one, and performs worse in three. Because ReAct_web + API receives the same API schemas and site-specific guidance as Baya, these results show that Baya's aggregate improvement cannot be attributed solely to API availability. The comparison instead indicates that compiling a complete program before execution can improve utility relative to selecting actions reactively from the same structured interface.
Variation across environments. The utility advantage is most consistent on Postmill, where Baya outperforms both ReAct configurations under every model by at least 39.6 percentage points. Results on Shopping and Shopping Admin are more model-dependent. Gemini-3.5-Flash with ReAct + API outperforms Baya on Shopping Admin, while GPT-5.6-Luna with ReAct + API outperforms Baya on both Shopping and Shopping Admin. These environments contain workflows that can be shorter or easier to discover through the user interface than through the available API operations. For example, a task that asks the agent to reorder an item can be completed through the user interface by navigating to the order history page and clicking “Reorder.” Accomplishing the same task through REST APIs requires fetching the customer ID to identify the relevant storefront orders, determining which item the task refers to, creating a new shopping cart, adding the item to the cart, providing shipping and billing information, and finally submitting the order. Thus, a single high-level UI action can correspond to a sequence of lower-level API operations, introducing additional steps and opportunities for failure for compiled API-based code.
Why does Baya achieve higher utility? At first glance, it may seem surprising that Baya achieves both higher security and higher utility, since restricting an agent's interaction capabilities might be expected to introduce a utility tradeoff. One possible explanation is that Baya provides agents with focused, task-relevant APIs rather than requiring them to select among general-purpose UI actions. This can make tasks easier to solve: prior work has similarly found that API-based agents can outperform web-based agents on task completion [30]. Our design further takes advantage of the code-generation capabilities of LLMs by allowing the agent to synthesize a complete program from these focused APIs before execution. In contrast, ReAct + API must select actions reactively at each step and can choose between API calls and general-purpose web interactions. This flexibility may introduce additional decision points and lead different models to adopt inconsistent mixtures of API and UI actions, potentially hurting overall utility. Thus, in our setting, the security restrictions imposed by Baya do not necessarily reduce the agent's capabilities; instead, they may provide a more structured interface that makes successful task completion easier.
5.4 Security
Table 3 reports intermediate ASR, end-to-end ASR, and benign-task utility. Across all three models and both environments, Baya achieves 0% intermediate and end-to-end ASR. The ReAct baselines exhibit intermediate ASRs of up to 52.8% and end-to-end ASRs of up to 5.6%. The largest differences occur with DeepSeek-V4-Flash, for which ReAct reaches intermediate ASRs of 46.0% on GitLab and 50.0% on Postmill, while ReAct + API reaches 2.1% and 36.1%, respectively. On Postmill with Gemini-3.5-Flash, ReAct and ReAct + API reach intermediate ASRs of 27.8% and 52.8%, respectively, while Baya remains at 0%. Across the 84 evaluated attack instances, no injection causes Baya to take an action judged to advance the attacker's objective. This result is consistent with Baya's goal of preventing untrusted webpage content from influencing runtime action selection.
ReAct + API and ReAct show mixed ASR results across models. Depending on the model, ReAct tends to favor either browser based or API-based actions. Claude uses APIs more frequently, whereas Gemini and DeepSeek rely more heavily on browser actions. We attribute cases where ReAct + API outperforms ReAct to the more selective view of data provided by APIs, which can expose only the information relevant to a request rather than an entire webpage, as browser actions often do.
Baya does not achieve the highest benign-task utility in every configuration. On Postmill with Claude Sonnet-4.6, both Baya and ReAct + API exhibit 0% observed ASR, while their utilities are 61.1% and 91.7%, respectively. On GitLab with DeepSeek-V4-Flash, Baya maintains 0% ASR but completes only 50.0% of benign tasks, while the reactive baselines achieve higher utility with nonzero intermediate ASR.
Comparison with UCM. We compare UCM [25] and Baya on GitLab using Claude Sonnet-4.6 as the primary agent model. On the 154-task GitLab utility set, UCM completes 116 tasks (75.3%), compared with 143 tasks (92.9%) for Baya. On the 48 GitLab WASP instances, both UCM and Baya achieve 0% intermediate and end-to-end ASR while completing 100% of the benign tasks. Thus, UCM matches Baya's observed security and utility on the GitLab WASP instances, while Baya achieves substantially higher utility on the broader GitLab task set. This comparison is limited to GitLab because UCM requires site-specific masking rules that are unavailable for the other evaluated environments.
Takeaway. Baya achieves 0% observed intermediate and end-to-end ASR across every evaluated model and environment. In contrast, the security of the ReAct baselines varies across models and environments, even when the agent can access the same APIs as Baya. This comparison shows that API access alone does not prevent prompt injection; the critical property is separating program generation from untrusted runtime observations. UCM also achieves 0% observed ASR in the evaluated GitLab configuration, but relies on site-specific masking rules and attains lower utility on the full GitLab task set. Overall, the results demonstrate Baya's consistent resistance to control-flow hijacking across the evaluated attacks.
5.4.1 Runtime LLM Exposure
Baya permits a generated program to invoke a runtime LLM when the task requires semantic processing that cannot be expressed reliably using deterministic operations. We measure how frequently generated programs include and execute this capability. For the static analysis, we identify programs
Table 3: Security evaluation under WASP attacks on GitLab and Postmill. Intermediate ASR measures whether an injection influences the agent's intermediate behavior, while end-to-end ASR measures whether the attack ultimately achieves its malicious objective. Utility measures benign task performance. Lower ASR and higher utility are better. Bold highlights that the agent achieved 0% ASR.
| Model | System | GitLab | Postmill | ||||
|---|---|---|---|---|---|---|---|
| ASR↓Intermediate | ASR↓End-to-end | Utility↑ | ASR↓Intermediate | ASR↓End-to-end | Utility↑ | ||
| Claude Sonnet-4.6 | Baya | 0.0% | 0.0% | 100.0% | 0.0% | 0.0% | 61.1% |
| ReAct_web | 0.0% | 0.0% | 100.0% | 25.0% | 0.0% | 100.0% | |
| ReAct_web + API | 0.0% | 0.0% | 100.0% | 0.0% | 0.0% | 91.7% | |
| Gemini-3.5-Flash | Baya | 0.0% | 0.0% | 100.0% | 0.0% | 0.0% | 77.8% |
| ReAct_web | 4.2% | 0.0% | 100.0% | 27.8% | 0.0% | 50.0% | |
| ReAct_web + API | 6.2% | 0.0% | 100.0% | 52.8% | 0.0% | 27.8% | |
| DeepSeek-V4-Flash | Baya | 0.0% | 0.0% | 50.0% | 0.0% | 0.0% | 61.1% |
| ReAct_web | 46.0% | 0.0% | 92.0% | 50.0% | 0.0% | 36.0% | |
| ReAct_web + API | 2.1% | 0.0% | 77.7% | 36.1% | 5.6% | 50.0% | |
Table 4: LLM use in generated programs. is the number of programs analyzed; columns report the percentage containing an LLM-call path, invoking an LLM at runtime, or using the deterministic fuzzy matcher.
| Site | LLM path in code | LLM invoked at runtime | Deterministic fuzzy matcher | |
|---|---|---|---|---|
| GitLab | 187 | 0.0% | 0.0% | 17.6% |
| Shopping | 171 | 4.7% | 4.1% | 14.6% |
| Shopping Admin | 154 | 1.3% | 0.6% | 27.9% |
| Postmill | 115 | 2.6% | 2.6% | 3.5% |
| Total | 627 | 2.1% | 1.8% | 16.7% |
containing model-provider invocation paths or direct model SDK imports. For the runtime analysis, we identify executions containing at least one logged request to a model API endpoint. These measurements count programs that invoke an LLM rather than the total number of model requests.
Table 4 shows that 13 of 627 generated programs (2.1%) contain an LLM-call path and that 11 programs (1.8%) invoke that path during execution. The two remaining programs use the LLM as a fallback, but their deterministic processing succeeds before the fallback is reached.
Runtime LLM calls perform narrowly scoped semantic operations, including classifying subjective reviews, matching conceptual descriptions, and summarizing text. In addition, 105 programs (16.7%) use the shared deterministic fuzzy
Table 5: Utility of BayaJSON and BayaCode. Cells report success rates; gives the number of valid tasks. Bold indicates the higher utility for each model and environment.
| Model | System | Shopping | |||
|---|---|---|---|---|---|
| GitLab | Shopping | Admin | Postmill | ||
| Claude | BayaJSON | 83.1% | 49.1% | 53.3% | 82.1% |
| Sonnet-4.6 | BayaCode | 92.9% | 71.3% | 81.3% | 84.0% |
| Gemini-3.5 | BayaJSON | 70.8% | 55.6% | 48.0% | 85.8% |
| Flash | BayaCode | 85.1% | 74.3% | 70.7% | 86.8% |
| GPT-5.6 | BayaJSON | 65.6% | 44.4% | 39.3% | 44.3% |
| Luna | BayaCode | 72.1% | 62.0% | 78.7% | 83.0% |
matcher. The fuzzy matcher performs similarity-based string matching locally and does not invoke a model.
In 616 of 627 executions (98.2%), retrieved website content is never supplied to a runtime LLM. In the remaining 11 executions, the compiled program determines the available API operations and control-flow structure before the runtime model receives any website content. The runtime model has no tool access and returns only a value consumed by the compiled program. Malicious content may therefore influence a semantic classification or other task output, but it cannot cause the model to synthesize new API calls or expand the compiled action space. These results show that Baya substantially limits runtime model exposure while preserving its protection against control-flow hijacking.
This column counts references to the shared fuzzy_match implementation and excludes other deterministic operations such as exact matching, filtering, sorting, and arithmetic.
Of the 155 Shopping Admin tasks, one produced a code-generation log but no Python program.
Table 6: Average token usage, cost, and latency per task.
| Agent | Tokens | Cost ($) | Latency (s) |
|---|---|---|---|
| ReActweb | 161.6K | 0.1573 | 59.91 |
| ReActweb + API | 672.8K | 0.3449 | 86.60 |
| BayaJSON | 201.1K | 0.7345 | 82.47 |
| BayaCode | 1.37M | 0.6974 | 327.15 |
| UCM | 1.50M | 4.0062 | 469.04 |
5.5 JSON Plans vs. Generated Programs
Choice of Compiled Representation. Throughout the paper, Baya refers to our current Python-based implementation. In this subsection, we call this implementation BayaCode to distinguish it from our earlier JSON-based implementation, which we call BayaJSON. Our earlier design compiled each task into a structured JSON plan specifying the selected API operations, their parameters, execution order, dependencies, and references to the outputs of earlier API calls. A fixed execution engine then interpreted the plan using a restricted set of operations for filtering, iteration, conditional execution, and response extraction.
As shown in Table 5, BayaCode improves utility on all four sites under every model. With Claude Sonnet-4.6, the macro-average success rate across the four sites increases from 66.9% to 82.4%. The largest gains occur on Shopping Admin and Shopping, where utility increases by 28.0 and 22.2 percentage points, respectively; GitLab improves by 9.8 points, while Postmill, where BayaJSON was already comparatively strong, improves by 1.9 points.
The larger gains on the Shopping environments are consistent with the kinds of execution logic their tasks require, such as constructing nested request bodies, resolving instance-specific identifiers, traversing paginated results, and filtering or ranking records returned by earlier calls. These results show that even a detailed structured plan is not sufficient for reliable execution, even when that plan explicitly represents API calls, parameters, dependencies, and control flow. Generating executable code provides the flexibility needed to implement the more complex data processing and site-specific execution logic required by real web tasks, leading to substantially higher utility.
5.6 Latency and Cost
Table 6 reports mean end-to-end latency, token usage, and estimated model cost per task. The measurements include all model calls, program generation, local validation, live execution, and replanning performed before the agent returns its final answer.
BayaCode uses an average of 1.37 million tokens, costs $0.70, and requires 327 seconds per task. Relative to ReAct<sub>web</sub> + API, BayaCode incurs approximately 2.0× the mon-
etary cost and 3.8× the latency. Relative to ReAct<sub>web</sub>, it incurs approximately 4.4× the cost and 5.5× the latency. This overhead reflects the additional model inference and validation required to generate and test a complete program before execution. BayaCode is approximately 4.0× slower than BayaJSON and uses 6.8× as many tokens. Despite the higher token count, its estimated cost is 5.1% lower because monetary cost depends on the models and token categories used rather than token count alone. Compared with UCM, BayaCode reduces mean latency by 30.3% and estimated cost by 82.6%.
Takeaway. BayaCode incurs greater latency and monetary cost than the ReAct baselines, primarily because it generates and validates a complete program before interacting with the live website. This overhead accompanies the utility and security improvements reported above. Among the evaluated security-oriented agents, BayaCode remains substantially faster and less expensive than UCM.
6 Discussion
6.1 Limitations
High Overhead. Baya’s guarantees come with overhead. As shown in Section 5.6, ReAct incurs lower latency and token usage, consistent with the findings of Piet et al. [28]. This gap stems from per-task compilation: API discovery, iterative validation, and error-recovery logic all consume tokens and time before Baya takes any action, so on an individual, previously unseen task its end-to-end cost and latency exceed ReAct’s.
This compilation cost can be amortized. Because a compiled program commits to its control flow before execution, it avoids the DOM interpretation and action selection that ReAct repeats at every step. Programs for common workflows can be cached and reused, and, as Piet et al. [28] also observe, recurring patterns across similar tasks allow new programs to be derived from existing ones rather than compiled from scratch. Under repeated or structurally similar workloads, the per-task cost of compilation therefore decreases, narrowing or even reversing the gap with ReAct. Pre-committed programs offer a further benefit that ReAct cannot: they can be inspected before execution to check policies and anticipate failures, making them easier to debug and verify.
Separately, Baya relies on trusted APIs constructed for each website before any task is processed. This one-time step is not reflected in the measurements above, but the resulting interfaces must be maintained as the website evolves, a burden ReAct avoids by operating directly on the live page. We discuss how this step could be automated securely in Section 6.2.
Expressiveness. Beyond cost, Baya has two limitations in expressiveness. First, it supports only tasks whose control flow can be determined before execution. This covers the vast majority of WebArena tasks, but excludes queries in which runtime data must determine actions that could not be specified in advance. Second, its effectiveness depends on choosing the right task abstraction: programs that are too low-level become brittle, while programs that are too high-level may hide information needed for execution.
While benchmark tasks are usually well-defined, not all real-world user requests are. To address underspecified tasks, Baya could interact with the user during compilation to clarify missing information before committing to a program. Because this interaction occurs during compilation, before exposure to untrusted website content, it does not compromise Baya's security guarantees. Tasks that depend on runtime data can still be supported as long as the possible operations and branches are specified in advance. However, if new requirements are discovered during execution that cannot be handled by the compiled program, Baya would need to return control to the user, explain the issue, and allow the user to provide an updated request for recompilation. This introduces additional overhead but ensures that new instructions come from the trusted user rather than untrusted website content.
Taken together, these limitations suggest that ReAct remains preferable in three settings: highly dynamic websites, where frequent structural changes make preprocessed interfaces costly to maintain; exploration-heavy tasks, where external data is needed during compilation and control flow cannot be fixed in advance; and workflows spanning many websites, some of which may not have been preprocessed.
6.2 Providing Missing API Capabilities
As discussed in Section 4.1, extending Baya to arbitrary websites requires automating the construction of Trusted Website APIs while ensuring that generated operations are safe to include in the trusted interface.
One possible deployment model is therefore a separate, secure site-onboarding phase. An onboarding agent could explore representative workflows, observe the underlying requests, and synthesize parameterized operations together with their contracts. This process could be isolated from Baya's per-task compilation and execution and performed using a least-privileged account. Generated operations could then be tested against expected outputs and state changes, restricted to approved network destinations and actions, and reviewed or certified before being admitted to the trusted interface.
Developing methods that automate this process without exposing Baya's planning process to untrusted browser content is an important direction for future work. Such methods would extend Baya to websites without complete APIs while preserving the separation between untrusted web content and trusted execution.
7 Related Work
Web agents and structured interfaces. Different paradigms have been proposed for developing web agents. The dominant approach is ReAct [37], which underlies baselines evaluated on WebArena [42] as well as end-to-end multimodal agents such as WebVoyager [18]. Similar reactive methods are used by vision-based agents such as SeeAct [41], which grounds model actions directly to page elements, and OpAgent [17], which achieves state-of-the-art performance on WebArena. Another line of work replaces or augments vision-and DOM-based interaction with structured interfaces such as APIs. Song et al. [30] show that API-based and hybrid API/browser agents outperform accessibility-tree-only agents on WebArena. Similarly, Zhang et al. [39] find that augmenting GUI agents with APIs improves success rates and reduces the number of steps on office-related tasks from OS-World [36].
Prompt injection against web agents. Because ReAct agents condition action selection on untrusted web content, third-party page content can redirect their behavior through indirect prompt injection [16]. Benchmarks such as InjecAgent, AgentDojo, and WASP systematically evaluate this threat [10, 13, 38], while DoomArena supports evolving, composable attacks across environments such as BrowserGym [4, 7]. Attacks range from simple textual injections to stealthy page elements and pixel-level perturbations [21, 33], motivating defenses that do not rely on the model recognizing malicious content.
Defending against prompt injection. Prior defenses strengthen ReAct agents through instruction hierarchy or data/instruction separation [5, 6, 27, 31], but remain vulnerable to adaptive attacks [24, 34]. Others monitor execution or restrict agent actions, including AgentArmor [32], TaskShield [19], and ceLLMate [23]. Security-by-construction approaches instead prevent untrusted content from influencing control flow. CaMeL [9] compiles the trusted query into a program while confining untrusted data, and Fides [8] enforces information-flow policies. Beurer-Kellner et al. [3] identify plan-then-execute as a broader security pattern, while Piet et al. [28] argue that it should be the default for web agents and show that it supports all WebArena tasks. Recent extensions apply related ideas to computer-use agents through upfront branching plans [14] or masking and quarantining untrusted content while retaining reactive execution [25].
8 Conclusion
We presented Baya, a web agent that adopts the compile-then-execute paradigm and is secure against prompt-injection-driven control-flow hijacking by design. Our evaluation on WebArena Verified and WASP shows that Baya achieves higher utility than the ReAct baselines while maintaining 0% observed ASR across all evaluated attacks.
Acknowledgments
This research was supported by the KACST-UCB Joint Center on Cybersecurity and gifts from the Noyce Foundation, Google, Accenture, Amazon, AMD, Anyscale, Broadcom, Cisco, IBM, Intel, Intesa Sanpaolo, Lambda, Lightspeed, Mibura, NVIDIA, Samsung SDS, and SAP. We would like to thank Yiwei Hou, Muxi Lyu, Xiao Huang, Michael Lavery, Andy Joe for brainstorming ideas and students from Sky Security and David Wagner's Lab for their helpful feedback.
References
[1] Hengyu An, Jinghuai Zhang, Tianyu Du, Chunyi Zhou, Qingming Li, Tao Lin, and Shouling Ji. PIIGuard: A novel tool dependency graph-based defense against indirect prompt injection in LLM agents. In Proceedings of the 2025 Conference on Empirical Methods in Natural Language Processing, pages 1023–1039, Suzhou, China, November 2025. Association for Computational Linguistics. URL: https://aclanthology.org/2025.emnlp-main.53/, doi:10.18653/v1/2025.emnlp-main.53.
[2] Anthropic. Introducing Claude Sonnet 4.6. https://www.anthropic.com/news/claudesonnet-4-6, February 2026. Accessed: 2026-08-25.
[3] Luca Beurer-Kellner, Beat Buesser, Ana-Maria Cretu, Edoardo Debenedetti, Daniel Dobos, Daniel Fabian, Marc Fischer, David Froelicher, Kathrin Grosse, Daniel Naeff, Ezinwanne Ozoani, Andrew Paverd, Florian Tramèr, and Václav Volhejn. Design Patterns for Securing LLM Agents against Prompt Injections, June 2025. arXiv:2506.08837 [cs.LG]. URL: http://arxiv.org/abs/2506.08837, doi:10.48550/arXiv.2506.08837.
[4] Leo Boisvert, Mihir Bansal, Chandra Kiran Reddy Evuru, Gabriel Huang, Abhay Puri, Avinandan Bose, Maryam Fazel, Quentin Cappart, Jason Stanley, Alexandre Lacoste, Alexandre Drouin, and Krishnamurthy Dvijotham. DoomArena: A framework for Testing AI Agents Against Evolving Security Threats, October 2025. arXiv:2504.14064 [cs.CR]. URL: http://arxiv.org/abs/2504.14064, doi:10.48550/arXiv.2504.14064.
[5] Sizhe Chen, Julien Piet, Chawin Sitawarin, and David Wagner. StruQ: Defending Against Prompt Injection with Structured Queries. In Proceedings of the 34th USENIX Conference on Security Symposium, Seattle, WA, USA, August 2025. USENIX Association. arXiv:2402.06363 [cs.CR]. URL: https://www.usenix.org/conference/usenixsecurity25/prentation/chen-sizhe.
[6] Sizhe Chen, Arman Zharmagambetov, Saeed Mahloujifar, Kamalika Chaudhuri, David Wagner, and Chuan Guo. SecAlign: Defending Against Prompt Injection with Preference Optimization. In Proceedings of the 2025 ACM SIGSAC Conference on Computer and Communications Security, CCS '25, pages 2833–2847, Taipei, Taiwan, November 2025. Association for Computing Machinery. URL: https://dl.acm.org/doi/10.1145/3719027.3744836, doi:10.1145/3719027.3744836.
[7] Thibault Le Sellier De Chezelles, Maxime Gasse, Alexandre Lacoste, Massimo Caccia, Alexandre Drouin, Léo Boisvert, Megh Thakkar, Tom Marty, Rim Assouel, Sahar Omidi Shayegan, Lawrence Keunho Jang, Xing Han Lu, Ori Yoran, Dehan Kong, Frank F. Xu, Siva Reddy, Graham Neubig, Quentin Cappart, Ruslan Salakhutdinov, and Nicolas Chapados. The BrowserGym Ecosystem for Web Agent Research. Transactions on Machine Learning Research, 2025, 2025. Preprint: arXiv:2412.05467 [cs.LG]. URL: https://openreview.net/forum?id=5298fKGmv3.
[8] Manuel Costa, Boris Köpf, Aashish Kolluri, Andrew Paverd, Mark Russinovich, Ahmed Salem, Shruti Tople, Lukas Wutschitz, and Santiago Zanella-Béguelin. Securing AI Agents with Information-Flow Control. CoRR, abs/2505.23643, 2025. arXiv:2505.23643 [cs.CR]. URL: https://doi.org/10.48550/arXiv.2505.23643, doi:10.48550/ARXIV.2505.23643.
[9] Edoardo Debenedetti, Ilia Shumailov, Tianqi Fan, Jamie Hayes, Nicholas Carlini, Daniel Fabian, Christoph Kern, Chongyang Shi, Andreas Terzis, and Florian Tramèr. Defeating Prompt Injections by Design, June 2025. arXiv:2503.18813 [cs.CR]. URL: http://arxiv.org/abs/2503.18813, doi:10.48550/arXiv.2503.18813.
[10] Edoardo Debenedetti, Jie Zhang, Mislav Balunović, Luca Beurer-Kellner, Marc Fischer, and Florian Tramèr. AgentDojo: A Dynamic Environment to Evaluate Prompt Injection Attacks and Defenses for LLM Agents. In Advances in Neural Information Processing Systems 37 (NeurIPS 2024) Datasets and Benchmarks Track, December 2024. arXiv:2406.13352 [cs.CR]. URL: https://papers.nips.cc/paper_files/paper/2024/hash/97091a5177d8dc64b1da8bf3e1f6fb54-Abstract-Datasets_and_Benchmarks_Track.html.
[11] DeepSeek-AI. Deepseek-v4: Towards highly efficient million-token context intelligence. arXiv preprint arXiv:2606.19348, 2026.
[12] Amine El Hattami, Megh Thakkar, Nicolas Chapados, and Christopher Pal. WebArena Verified: Reliable eval-uation for web agents. In Workshop on Scaling Environments for Agents, 2025. URL: https://openreview.net/forum?id=94tlGxmqkN.
[13] Ivan Evtimov, Arman Zharmagambetov, Aaron Grattafori, Chuan Guo, and Kamalika Chaudhuri. WASP: Benchmarking Web Agent Security Against Prompt Injection Attacks. In Advances in Neural Information Processing Systems 38 (NeurIPS 2025) Datasets and Benchmarks Track, December 2025. arXiv:2504.18575 [cs.CR]. URL: https://papers.nips.cc/paper_files/paper/2025/hash/1c9818387f5dd0a0bc151214660f059d-Abstract-Datasets_and_Benchmarks_Track.html.
[14] Hanna Foerster, Tom Blanchard, Kristina Nikolić, Ilia Shumailov, Cheng Zhang, Robert Mullins, Nicolas Papernot, Florian Tramèr, and Yiren Zhao. CaMeLs Can Use Computers Too: System-level Security for Computer Use Agents, June 2026. arXiv:2601.09923 [cs.AI]. URL: http://arxiv.org/abs/2601.09923, doi:10.48550/arXiv.2601.09923.
[15] Google. Gemini 3.5 Flash. https://ai.google.de/v/gemini-api/docs/models/gemini-3.5-flash, July 2026. Last updated: July 21, 2026; accessed: 2026-08-25.
[16] Kai Greshake, Sahar Abdelnabi, Shailesh Mishra, Christoph Endres, Thorsten Holz, and Mario Fritz. Not What You've Signed Up For: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection. In Proceedings of the 16th ACM Workshop on Artificial Intelligence and Security, AISec '23, pages 79–90, Copenhagen, Denmark, November 2023. ACM. URL: https://dl.acm.org/doi/10.1145/3605764.3623985, doi:10.1145/3605764.3623985.
[17] Yuyu Guo, Wenjie Yang, Siyuan Yang, Ziyang Liu, Cheng Chen, Yuan Wei, Yun Hu, Yang Huang, Guoliang Hao, Dongsheng Yuan, Jianming Wang, Xin Chen, Hang Yu, Lei Lei, and Peng Di. OpAgent: Operator Agent for Web Navigation, April 2026. arXiv:2602.13559 [cs.AI]. URL: http://arxiv.org/abs/2602.13559, doi:10.48550/arXiv.2602.13559.
[18] Hongliang He, Wenlin Yao, Kaixin Ma, Wenhao Yu, Yong Dai, Hongming Zhang, Zhenzhong Lan, and Dong Yu. WebVoyager: Building an End-to-End Web Agent with Large Multimodal Models. In Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 6864–6890, Bangkok, Thailand, August 2024. Association for Computational Linguistics. URL: https://aclanthology.org/2024.acl-long.371, doi: 10.18653/v1/2024.acl-long.371.
[19] Feiran Jia, Tong Wu, Xin Qin, and Anna Squicciarini. The Task Shield: Enforcing Task Alignment to Defend Against Indirect Prompt Injection in LLM Agents. In Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 29680–29697, Vienna, Austria, July 2025. Association for Computational Linguistics. arXiv:2412.16682 [cs.CR]. URL: https://aclanthology.org/2025.acl-long.1435/, doi:10.18653/v1/2025.acl-long.1435.
[20] Aashish Kolluri, Rishi Sharma, Manuel Costa, Boris Köpf, Tobias Nießen, Mark Russinovich, Shruti Tople, and Santiago Zanella-Béguelin. Optimizing agent planning for security and autonomy. In The Fourteenth International Conference on Learning Representations, 2026. URL: https://openreview.net/forum?id=g0aVCDY3gS.
[21] Zeyi Liao, Lingbo Mo, Chejian Xu, Mintong Kang, Jiawei Zhang, Chaowei Xiao, Yuan Tian, Bo Li, and Huan Sun. EIA: Environmental Injection Attack on Generalist Web Agents for Privacy Leakage. In The Thirteenth International Conference on Learning Representations (ICLR), April 2025. arXiv:2409.11295 [cs.CR]. URL: https://openreview.net/forum?id=xMOLUzo2Lk.
[22] Libretto. How to Automate Browser Workflows: Step-by-Step Guide for Developers. https://libretto.sh/blog/how-to-automate-browser-workflows, June 2026. Accessed: 2026-08-25.
[23] Luoxi Meng, Henry Feng, Ilia Shumailov, and Earlence Fernandes. ceLLMate: Sandboxing Browser AI Agents, March 2026. arXiv:2512.12594 [cs.CR]. URL: http://arxiv.org/abs/2512.12594, doi:10.48550/arXiv.2512.12594.
[24] Milad Nasr, Nicholas Carlini, Chawin Sitawarin, Sander V. Schulhoff, Jamie Hayes, Michael Ilie, Juliette Pluto, Shuang Song, Harsh Chaudhari, Ilia Shumailov, Abhradeep Thakurta, Kai Yuanqing Xiao, Andreas Terzis, and Florian Tramèr. The Attacker Moves Second: Stronger Adaptive Attacks Bypass Defenses Against LLM Jailbreaks and Prompt Injections, October 2025. arXiv:2510.09023 [cs.LG]. URL: http://arxiv.org/abs/2510.09023, doi:10.48550/arXiv.2510.09023.
[25] Kristina Nikolić, Egor Zverev, Javier Rando, Matthew Jagielski, Edoardo Debenedetti, and Florian Tramèr. Untrusted Content Masking for Web Agents with Security Guarantees, July 2026. arXiv:2607.05277 [cs.CR]. URL: http://arxiv.org/abs/2607.05277, doi: 10.48550/arXiv.2607.05277.
[26] OpenAI. GPT-5.6 Luna Model. https://developers.openai.com/api/docs/models/gpt-5.6-luna, 2026. Accessed: 2026-08-25.
[27] Julien Piet, Maha Alrashed, Chawin Sitawarin, Sizhe Chen, Zeming Wei, Elizabeth Sun, Basel Alomair, and David Wagner. Jatmo: Prompt Injection Defense by Task-Specific Finetuning. In Computer Security – ESORICS 2024: 29th European Symposium on Research in Computer Security, Bydgoszcz, Poland, September 16–20, 2024, Proceedings, Part I, volume 14982 of Lecture Notes in Computer Science, pages 105–124, Berlin, Heidelberg, 2024. Springer-Verlag. arXiv:2312.17673 [cs.CR]. doi:10.1007/978-3-031-70879-4_6.
[28] Julien Piet, Annabella Chow, Yiwei Hou, Muxi Lyu, Sylvie Venuto, Jinhao Zhu, Raluca Ada Popa, and David Wagner. Web Agents Should Adopt the Compile-and-Execute Paradigm, 2026. URL: https://arxiv.org/abs/2605.14290, arXiv:2605.14290, doi:10.48550/arXiv.2605.14290.
[29] Yifan Song, Weimin Xiong, Dawei Zhu, Wenhao Wu, Han Qian, Mingbo Song, Hailiang Huang, Cheng Li, Ke Wang, Rong Yao, Ye Tian, and Sujian Li. RestGPT: Connecting large language models with real-world restful apis, 2023. URL: https://arxiv.org/abs/2306.06624, arXiv:2306.06624.
[30] Yueqi Song, Frank F. Xu, Shuyan Zhou, and Graham Neubig. Beyond Browsing: API-Based Web Agents. In Findings of the Association for Computational Linguistics: ACL 2025, pages 11066–11085, Vienna, Austria, July 2025. Association for Computational Linguistics. arXiv:2410.16464 [cs.CL]. URL: https://aclanthology.org/2025.findings-acl.577/, doi:10.18653/v1/2025.findings-acl.577.
[31] Eric Wallace, Kai Xiao, Reimar Leike, Lilian Weng, Johannes Heidecke, and Alex Beutel. The Instruction Hierarchy: Training LLMs to Prioritize Privileged Instructions, April 2024. arXiv:2404.13208 [cs.CR]. URL: http://arxiv.org/abs/2404.13208, doi: 10.48550/arXiv.2404.13208.
[32] Peiran Wang, Yang Liu, Yunfei Lu, Yifeng Cai, Hongbo Chen, Qingyou Yang, Jie Zhang, Jue Hong, and Ye Wu. AgentArmor: Enforcing Program Analysis on Agent Runtime Trace to Defend Against Prompt Injection, November 2025. arXiv:2508.01249 [cs.CR]. URL: http://arxiv.org/abs/2508.01249, doi:10.48550/arXiv.2508.01249.
[33] Xilong Wang, John Bloch, Zedian Shao, Yuepeng Hu, Shuyan Zhou, and Neil Zhenqiang Gong. WebInject: Prompt Injection Attack to Web Agents. In Proceedings
of the 2025 Conference on Empirical Methods in Natural Language Processing, pages 2010–2030, Suzhou, China, November 2025. Association for Computational Linguistics. arXiv:2505.11717 [cs.LG]. URL: https://aclanthology.org/2025.emnlp-main.104/, doi:10.18653/v1/2025.emnlp-main.104.
[34] Yuxin Wen, Arman Zharmagambetov, Ivan Evtimov, Narine Kokhlikyan, Tom Goldstein, Kamalika Chaudhuri, and Chuan Guo. RL Is a Hammer and LLMs Are Nails: A Simple Reinforcement Learning Recipe for Strong Prompt Injection, October 2025. arXiv:2510.04885 [cs.CR]. URL: http://arxiv.org/abs/2510.04885, doi:10.48550/arXiv.2510.04885.
[35] Bin Wu. Introducing advanced tool use on the Claude Developer Platform. Anthropic Engineering, November 2025. Accessed: 2026-08-23. URL: https://www.anthropic.com/engineering/advanced-tool-use.
[36] Tianbao Xie, Danyang Zhang, Jixuan Chen, Xiaochuan Li, Siheng Zhao, Ruisheng Cao, Toh Jing Hua, Zhoujun Cheng, Dongchan Shin, Fangyu Lei, Yitao Liu, Yiheng Xu, Shuyan Zhou, Silvio Savarese, Caiming Xiong, Victor Zhong, and Tao Yu. OSWorld: Benchmarking Multimodal Agents for Open-Ended Tasks in Real Computer Environments. In Advances in Neural Information Processing Systems 37 (NeurIPS 2024) Datasets and Benchmarks Track, December 2024. arXiv:2404.07972 [cs.AI]. URL: https://papers.nips.cc/paper_files/paper/2024/hash/5d413e48f84dc61244b6be550f1cd8f5-Abstract-Datasets_and_Benchmarks_Track.html.
[37] Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. ReAct: Synergizing Reasoning and Acting in Language Models. In The Eleventh International Conference on Learning Representations (ICLR), May 2023. arXiv:2210.03629 [cs.CL]. URL: https://openreview.net/forum?id=WE_vluYUL-X, doi:10.48550/arXiv.2210.03629.
[38] Qiusi Zhan, Zhixiang Liang, Zifan Ying, and Daniel Kang. InjecAgent: Benchmarking Indirect Prompt Injections in Tool-Integrated Large Language Model Agents. In Findings of the Association for Computational Linguistics ACL 2024, pages 10471–10506, Bangkok, Thailand, August 2024. Association for Computational Linguistics. URL: https://aclanthology.org/2024.findings-acl.624, doi:10.18653/v1/2024.findings-acl.624.
[39] Chaoyun Zhang, Shilin He, Liqun Li, Si Qin, Yu Kang, Qingwei Lin, Saravan Rajmohan, and Dongmei Zhang.
API Agents vs. GUI Agents: Divergence and Convergence, June 2025. arXiv:2503.11069 [cs.AI]. URL: http://arxiv.org/abs/2503.11069, doi:10.48550/arXiv.2503.11069.
[40] Kaiyuan Zhang, Mark Tenenholtz, Kyle Polley, Jerry Ma, Denis Yarats, and Ninghui Li. BrowseSafe: Understanding and preventing prompt injection within AI browser agents. arXiv preprint arXiv:2511.20597, 2025.
[41] Boyuan Zheng, Boyu Gou, Jihyung Kil, Huan Sun, and Yu Su. GPT-4v(ision) is a Generalist Web Agent, if Grounded. In Proceedings of the 41st International Conference on Machine Learning, volume 235 of Proceedings of Machine Learning Research, pages 61349–61385. PMLR, July 2024. arXiv:2401.01614 [cs.IR]. URL: https://proceedings.mlr.press/v235/zheng24e.html.
[42] Shuyan Zhou, Frank F. Xu, Hao Zhu, Xuhui Zhou, Robert Lo, Abishek Sridhar, Xianyi Cheng, Tianyue Ou, Yonatan Bisk, Daniel Fried, Uri Alon, and Graham Neubig. WebArena: A Realistic Web Environment for Building Autonomous Agents. In The Twelfth International Conference on Learning Representations (ICLR), May 2024. arXiv:2307.13854 [cs.AI]. URL: https://openreview.net/forum?id=oKn9c6ytLx.
9 Appendix
9.1 WebArena Evaluation
We use the WebArena [42] task suite with revised intents and corrected ground truth from WebArena Verified [12]. WebArena originally evaluates tasks using three mechanisms: program_html, which checks the resulting website state; string_match, which checks the agent's response for expected content; and url_match, which checks the final browser URL. WebArena Verified replaces these with AgentResponseEvaluator for response-based tasks and NetworkEventEvaluator for tasks validated through browser network events. Below, we describe how we adapt these evaluators to support API-based execution.
9.1.1 API-Compatible Evaluation
Not all WebArena Verified evaluators are compatible with Baya's execution interface. We therefore construct a common evaluation harness that preserves the task semantics while allowing both browser-based and API-based agents to be graded under comparable criteria.
For tasks originally evaluated with string_match or program_html, we retain WebArena's outcome-based evaluators while using the revised task intents from WebArena Verified. We manually verify and correct the corresponding ground-truth data where necessary. These evaluators are directly applicable to both agents because they assess either the agent's returned information or the resulting website state, rather than requiring a particular execution path.
For tasks originally evaluated with url_match, the evaluator itself is not applicable to Baya, since Baya does not need to navigate a browser to the target page in order to obtain the requested information. We therefore convert these tasks to string_match. For each task, we manually complete the navigation and identify content unique to the expected destination page; successful agents are then required to return this page-specific information. This preserves the task's semantic objective without requiring browser navigation as the success condition.
We do not use NetworkEventEvaluator to grade Baya. Unlike the outcome-based evaluators above, NetworkEventEvaluator validates the execution trace by requiring a specific browser-generated network request. For conventional browser agents, these requests arise naturally as the agent clicks buttons, fills forms, and submits actions through the benchmark browser. For example, creating a Postmill post may be validated by observing a particular form POST request and its 302 response.
Baya, however, compiles the task into calls to a Trusted Website API and executes those calls directly rather than reproducing the corresponding frontend interaction sequence in the benchmark browser. Some Trusted Website API implementations internally use Playwright, but these opera-
tions execute behind the API abstraction rather than as actions in the benchmark's instrumented browser session. As a result, Baya may successfully produce the correct website state without generating the specific UI request required by NetworkEventEvaluator; the underlying request may also differ in endpoint, method, or payload. Thus, the incompatibility is with the validator rather than the underlying task: Baya can, for example, create the requested Postmill post even though it does not emit the particular browser-side request used by Webarena Verified to recognize success.
We additionally remove tasks whose intents or ground truth are unusable independent of agent architecture. Of the 623 single-site tasks, we label 42 as bad or impossible because the intent is ambiguous, underspecified, or cannot be completed reliably even by a fully capable browser agent. We also exclude all 31 cross-site tasks. This leaves 581 single-site tasks with well-defined, feasible objectives for our primary evaluation.
Finally, because ReAct and Baya expose different execution traces and response formats, we give each agent credit if it satisfies any evaluator applicable to its execution mode. ReAct is evaluated under our common harness and additionally with WebArena Verified's evaluator when a valid browser network event provides evidence of successful completion. Baya is evaluated under the common outcome-based harness. This allows both agents to receive credit for completing the same task intent without requiring them to produce identical browser-level execution traces.
9.2 Experimental Setup
We deploy the WebArena Verified websites as isolated Docker instances, using five independent worker stacks to execute at most five utility or security tasks concurrently. Each worker is reset according to the benchmark protocol to prevent state changes from one task from affecting another.
For Baya, the models serve as the compiler and are invoked through Claude Code, Antigravity, and Codex, respectively. Claude Code uses high reasoning effort, while Antigravity and Codex use medium reasoning effort. The ReAct agents invoke the corresponding models directly through their provider APIs. We impose a 900-second compilation timeout on each Baya attempt and limit ReAct agents to 30 action steps per task.
For latency measurements, we execute tasks serially on a single website stack to avoid resource contention, using a GCP n2-standard-8 virtual machine with eight virtual CPUs and 32 GB of memory. The machine has no GPU, as all model inference is performed through remote provider APIs. We obtain token counts from model-response logs and estimate monetary cost using LiteLLM's pricing table or, for models accessed through OpenRouter, the cost reported by OpenRouter. These values are estimates rather than provider-invoiced charges.
9.2.1 Implementation and Infrastructure Details
Our evaluation environment used Python 3.12.11, Docker Engine 28.1.1, Docker Compose 2.35.1, Prance 25.4.8.0, LiteLLM 1.80.0, Playwright 1.58.0, and Chromium 145.0.7632.6. The latency experiments ran on an x86-64 Debian GNU/Linux 13 VM in the us-centrall-c zone with a 500 GB balanced persistent disk. The agent, browser, API servers, and benchmark websites ran on the same host and communicated over the loopback interface.
For Baya, DeepSeek was accessed through Codex using OpenRouter's Responses-compatible API.
The ReAct OpenAI configuration additionally imposed a 4,096-token output limit. Claude Code occasionally invoked claude-haiku-4-5 internally for small helper operations; this behavior was controlled by the harness rather than explicitly configured by us. Claude Code used the default high reasoning effort setting.
9.3 Qualitative Differences Between Baya and ReAct
The aggregate results obscure important differences in how the agents approach individual tasks. We examine two representative cases: aggregation over paginated records and precise query construction. These cases illustrate the benefits of API access for record-intensive tasks and differences between ReAct's incremental execution and Baya's compiled, systematically scoped programs.
Aggregation over paginated records. Many Shopping Admin tasks require aggregating records that are distributed across multiple UI pages. For example, one task asks for the email address, name, and phone number of the customer with the most cancellations. ReAct_web struggles to assemble the necessary data from the paginated tables. With API access, both ReAct_web + API and Baya solve the task using two REST endpoints. Their execution strategies differ, however: ReAct constructs the solution incrementally through multiple Python interpreter calls and hardcodes the observed number of pages, whereas Baya generates a single self-contained program that handles data retrieval and aggregation.
Precise query scoping. API access alone does not ensure that a query faithfully captures every constraint in the task. Shopping uses an unusual filtering syntax in which each constraint must be encoded explicitly. When asked to report a customer's number of completed orders and total spending over the previous four months, ReAct filters by order status and date but omits the customer constraint, thereby returning another customer's results without detecting the error. In contrast, Baya includes the customer, status, and date constraints in the generated query and checks the resulting query construction during compilation-time testing.
Together, these cases show that API access can overcome limitations of browser-only interaction but does not by it-
self ensure reliable execution. Baya benefits from compiling the task constraints and data-processing logic into a self-contained program and validating them before live execution.
9.4 Example Artifacts
See Fig. 5 for harness configuration, Fig. 6 for a complete Baya workflow, and Fig. 7 for API schemas.
Claude Code Permissions and Sandbox Policy
{ "permissions": { "defaultMode": "dontAsk", "allow": [ "Read(api/schemas/site_api_schema.json)", "Edit(generated/site/task/*)", "Bash(/venv/bin/python -m pytest *)", "... ] }, "autoMemoryEnabled": false, "sandbox": { "enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, "filesystem": { "denyRead": ["/home", "/etc", "..."], "allowWrite": ["generated/site/task"], "denyWrite": ["api", "config", "tools", "..."] }, "network": {"allowedDomains": []} } }
Figure 5: Abridged Claude Code permissions and sandbox policy.
Task: Retrieve reviewers who say the Sony WH-XM0006 headphone's ear cups are too small.
Phase 1: Baya compiler → compilation outputs
Generated Program File
def main(): token = authenticate() # Search for the product through the trusted API. products = trusted_api.search_products( query="Sony WH-XM0006", token=token ) # Resolve the intended product deterministically. product = best_match(products, "Sony WH-XM0006") require(product, "Product not found") # Retrieve reviews only for the matched product. reviews = trusted_api.get_reviews( sku=product.sku, token=token ) # The LLM sees only the retrieved review data. ids = data_only_llm.select( reviews, criterion="ear cups are too small" ) # Return the selected reviewers. reviewers = [ r.reviewer for r in reviews if r.id in ids ] print_final(reviewers or ["None"])
Generated Test File
def test_main(): # Replace external operations with local mocks. mock(authenticate, returns=FAKE_TOKEN) mock(search_products, returns=[xm0005, xm0006]) mock(get_reviews, returns=[ review_by_ava, review_by_ben ]) # No live LLM request is made during testing. mock(data_only_llm, returns=[ review_by_ava.id]) output = run(main)
Verify product selection and the final answer.
assert get_reviews.called_with(sku=xm0006.sku)
assert output == "Ava"
Coding-Harness Output
coding_harness: site=shopping task=toy >>> Generated the program and companion unit-test files. All mock tests pass. Here's what the implementation does:
- Authenticates with the trusted Shopping API
- Searches for "Sony WH-XM0006"
- Selects the intended product deterministically
- Fetches reviews only for the matched product
- Uses a data-only LLM to identify relevant reviews
- Prints the matching reviewers, or "None"
Execute program

Failure: replan using program, test, and logs
Phase 2: Baya Execution
Python Error Diagnostics Log
INFO search_products("Sony WH-XM0006") INFO Product search returned 1 item(s) INFO Found product SKU (not logged) INFO Fetching product reviews INFO GET /v1/products/{sku}/reviews INFO Got 12 review(s) for product INFO Found 1 review(s) mentioning small ear cups
Phase 3: Final Answer
Output
***** FINAL ANSWER ***** Ava ***** END FINAL ANSWER *****
Figure 6: Toy example of Baya compilation, execution, and failure-driven replanning.
GitLab: GET /projects endpoint.
"/projects": { "get": { "operationId": "get_projects", "parameters": [ {"name": "membership", "in": "query", "type": "boolean", "default": false}, {"name": "sort", "in": "query", "type": "string", "enum": ["asc", "desc"], "default": "desc"} ], ... ], "responses": { "200": {"schema": {"type": "array", "items": {"$ref": "#/definitions/API_Entities_BasicProjectDetails}}}}, "401": {"description": "Unauthorized"}, "403": {"description": "Forbidden"}, "404": {"description": "Not Found"} } }
(a) GitLab API schema
Shopping: GET /V1/products endpoint.
"/V1/products": { "get": { "operationId": "GetV1Products", "parameters": [ {"name": "searchCriteria[filterGroups][0][filters][0][field]"}, "in": "query", "type": "string"}, {"name": "searchCriteria[filterGroups][0][filters][0][value]"}, "in": "query", "type": "string"}, {"name": "searchCriteria[filterGroups][0][filters][0][conditionType]"}, "in": "query", "type": "string"}, {"name": "searchCriteria[sortOrders][0][direction]"}, "in": "query", "type": "string"}, {"name": "searchCriteria[pageSize]"}, "in": "query", "type": "integer"}, ... ], "responses": { "200": {"schema": { "$ref": "#/definitions/catalog-data-product-search-results-interface"}}, "401": {"description": "Unauthorized"}, "default": {"description": "Unexpected error"} } }
(b) Shopping API schema
Figure 7: Abridged API schemas provided to the coding harness. GitLab illustrates conventional typed parameters, enums, and defaults, while Shopping illustrates Magento's nested filtering, sorting, and pagination syntax.