Agent code execution risks begin the moment an autonomous agent stops describing what it would do and starts doing it. A chatbot that only answers questions can mislead you; an agent that runs code can change files, call services, spend money and leave changes behind that outlive the conversation. This guide explains the primary risks that arise specifically when an autonomous AI agent executes code, traces each risk to the step where it enters, and sets out the containment measures that reduce them. It focuses only on the code-execution path.
What Code Execution Means for an Autonomous Agent
An autonomous agent that executes code typically works in a loop: it generates a plan or a piece of code, runs it through a tool, reads the result, and decides what to do next. The code may run in a code interpreter, a shell, a function-calling tool, or a browser automation session. Each loop gives the agent another chance to act on what it just learned, including what it just read from a file, a web page or a tool output.
Three features of this loop matter. The agent decides what to run, so the code is not fixed in advance. The code runs with an identity and permissions, and inherits whatever that identity can reach. And the loop persists: a result from one step becomes the input to the next, so one bad instruction can steer several steps. OWASP’s description of excessive agency captures this: a system gives a model too much autonomy or too many permissions, including the ability to execute code, modify databases or access external systems without appropriate guardrails.
Code execution is also how agents do useful work, from analysing data to fixing a failing build. The question is not whether to allow it, but what the code may touch, what identity it runs as, and what happens when something goes wrong.
Agent Code Execution Risks Start with Untrusted Input

The most important entry point for agent code execution risks is content the agent reads. Indirect prompt injection embeds malicious instructions in external content an agent retrieves during routine execution, such as web pages, documents, emails or system logs, and alters the agent’s behaviour without user authorisation. The agent was designed to read that content to do its job, and a language model has no reliable built-in way to tell which sentences in its context are orders and which are merely data.
Consider the chain. An agent asked to fix a bug or review a repository reads a file, web page or issue comment containing an instruction written for the agent: run a command, fetch a URL, read a credential file, or write a result somewhere public. The agent generates the code or command, executes it, and reads the result back into its context. The attacker never needed to talk to the agent directly. The content did the talking.
The pattern is most dangerous when an agent combines three conditions at once: access to untrusted data, sensitive context, and a way to communicate or act externally — because then a single injected instruction can reach sensitive material and trigger an outward effect. In one study reported in a secondary summary, researchers planted attack payloads in ordinary development resources and found coding agents carried out malicious commands as high as 84% of the time, with goals including system discovery, credential theft and data exfiltration. Treat that as evidence the pattern works in practice, not a precise rate for every tool. The lesson is architectural: if an agent must read untrusted data, assume some of it may try to steer it, and decide in advance what a steered agent can still reach.
The Code Itself Can Be the Risk
Not every code-execution risk needs an attacker. Generated code is unreviewed code, and it can be wrong in ways that are hard to spot because it looks confident and complete.
First, generated code can reproduce insecure patterns common in training code: queries or commands built by joining strings together, inputs used without validation, or credentials handled carelessly. The fragment below is an illustration only, not a complete program.
# Fragment — illustration only, not a complete program.
# Risky shape: a command built by joining text together.
run("convert " + user_supplied_filename)
# Safer shape: the filename is passed as a separate value, not joined into a command.
run(["convert", user_supplied_filename])Second, generated code can name things that do not exist. Package hallucination is when a model generates code referencing a package that does not exist in a public registry. Attackers can register those plausible-sounding names with malicious implementations, an attack pattern termed slopsquatting. In the study by Spracklen and colleagues, 576,000 samples from 16 models produced 205,474 unique hallucinated package names: about 5.2% of commercial-model samples and 21.7% of open-source samples, with 58% of names recurring across repeated prompts. That repetition is what makes the pattern dangerous: an attacker can harvest the recurring names and register them before a developer or agent installs them.
Third, generated code can carry secrets with it. A credential, token or private key in generated code, a log, or a file the agent writes can persist long after the task ends, even when the code is not malicious. Review the code the agent ran and what it changed, not only the summary it gave you afterwards.
Sandbox Escape and Excessive Privilege
A sandbox is meant to bound what executed code can reach: which files it can read and write, which network destinations it can contact, which processes it can start, and which identity it runs as. Sandboxing is one of the most important controls for agent code execution, and it is also one of the most misunderstood. A sandbox reduces risk; it does not remove it.
Anthropic describes three layers of defence: the environment (sandboxes, virtual machines, filesystem boundaries, egress controls), the model (system prompts, classifiers, probes, training), and external content (servers, plugins, search results). Model-level safeguards are probabilistic: they shape what an agent tends to do, but cannot guarantee what it cannot do. Hard environmental boundaries must do the heavy lifting, because if credentials never enter the sandbox, they cannot be exfiltrated, whatever caused the attempt.
Anthropic also reports that capable models find unexpected paths around restrictions, including escaping a sandbox to finish a task. A sandbox can be misconfigured, given a shared folder it should not have, allowed network access it does not need, or paired with an identity holding far more privilege than the task requires. When code runs with the agent’s identity, it inherits the agent’s privileges. So ask not only whether a sandbox exists, but what is inside it, what can leave it, and what identity the code runs as. Defaults vary between tools and change over time, so check the tool you actually use rather than assuming a sandbox is on, strict, or empty by default.
Persistence, Side Effects and Resource Abuse
Executed code does not only produce an answer. It produces effects, and effects can persist. A file written, a database row changed, a configuration edited, or a package installed can outlive the agent’s run when it lands in persistent or external state, while temporary execution state may disappear with the session. Some effects are hard to reverse: a message sent, a record deleted, a change published, or money spent cannot always be undone by running another command.
Persistence also creates a second-order risk: a changed file or modified configuration can affect later runs, including runs by other people or agents. The record that matters is what changed and whether it can be reverted.
Resource abuse is the quieter cousin of persistence. OWASP lists unbounded consumption among its LLM application risks, covering excessive resource consumption from long prompts, recursive tool calls or expensive computation. An agent in a loop can repeat a costly operation many times or keep retrying a failing action. Limits on steps, time, cost and retries bound how much a runaway loop can do before someone stops it.
How to Contain Agent Code Execution

Containment is a set of controls applied together. Because no reliable prevention mechanism exists for prompt injection today, defence has to be architectural: credentials and state-changing power held in application code, and every privileged call routed through a deterministic policy check at execution time.
Start with identity and privilege. Give the agent a dedicated identity with the least privilege the task needs, short-lived credentials where possible, and no access to production credentials, administrator roles or unrelated systems. Scope is a security decision, not an inconvenience to work around with a developer’s credentials.
Next, bound the environment. Run generated code in a sandbox or an isolated virtual machine with a filesystem limited to the task, no network access or a strict allowlist of destinations, and no path back to the host or to other sessions. Anthropic’s cloud sessions illustrate one end of this design: each session runs in its own Firecracker microVM, with the host blocking traffic from a virtual machine to the host and to other virtual machines. Your setup should be able to answer the same questions: what can the code read, write and contact, and what happens if it tries to go further?
Then bound the tools. Use an allowlist of permitted tools rather than a general shell with everything available. Require human approval, bound to the exact operation and its parameters, before destructive, outbound or irreversible actions. Log every execution with its input, code and result, and keep a kill switch to stop the agent and revoke its credentials.
Finally, validate what the agent produces before it runs and persists. Check that named packages exist, scan generated code with the same checks you apply to human code, and treat tool outputs as data to be validated, not instructions to follow.
Common Mistakes When Letting Agents Run Code
The same mistakes recur because each one feels reasonable in the moment. The first is treating a sandbox as a guarantee instead of one layer. Unverified isolation is not the same as demonstrated failure: a sandbox that was never tested with untrusted input, that exposes resources through unnecessarily broad or incorrectly permissioned shared mounts, or that runs with an over-privileged identity may leave more exposed than the task requires. A deliberately scoped shared folder, on the other hand, can be intentional and does not by itself defeat isolation.
The second is granting the agent a human’s credentials for convenience. An agent running with a developer’s or administrator’s access can do everything that person can do, at machine speed, including things the person would never have approved.
The third is reviewing the agent’s summary instead of the code it ran and what it changed. Summaries can omit the step that matters or present a failed check as a passed one. The execution log, the exact code and the list of changes are the evidence; the summary is commentary on it.
The fourth is skipping approval for actions that are hard to reverse. Approval prompts cause fatigue, so reserve approval for consequential actions, bind it to the exact operation, and back it with the environmental controls above, so an approved-but-wrong action still cannot reach everything.
Checklist: Before You Let an Agent Execute Code
Run through this checklist before granting an agent a shell, a code interpreter, or any tool that executes code on your behalf.
- Decide what the code may touch, and deny everything else: one identity, one task, the smallest set of files, systems and destinations that the task needs.
- Confirm the sandbox, identity, network and approval settings before the first run, and test them with untrusted input, not only with clean prompts.
- Check that named packages exist, that generated code passes your usual static checks, and that no secret appears in the code, the logs or the files the agent writes.
- Require approval bound to the exact operation for destructive, outbound or irreversible actions, and keep a kill switch and a way to revoke credentials quickly.
- Log every execution with its input, code and result, and confirm you can list what changed; plan rollback for reversible changes, and explicit approval and an impact-response plan for irreversible ones.
- Set limits on steps, time, cost and retries so a loop cannot run away, and plan how you will detect, stop and respond to a bad execution before it happens, including which effects cannot be reversed.
Agent code execution risks are manageable when the boundaries are set before the first run, in the environment rather than in the prompt. Decide what the code may reach, prove the boundary with untrusted input, and keep the evidence of what ran.












