Why All‑In‑One Sandbox Beats Traditional Sandboxes: A Deep Dive into AgentRun’s Cloud‑Native Solution
This article explains how AgentRun’s All‑In‑One (AIO) sandbox integrates browser, shell, and code execution into a single cloud‑native container, eliminating file‑sharing headaches, simplifying tool coordination, reducing environment setup complexity, and cutting both memory usage and network latency for AI‑driven automation tasks.
Background
AgentRun’s Agentic AI platform needed a unified sandbox because existing solutions were fragmented across browsers, code execution and shell environments, causing file‑sharing pain points, complex tool coordination, heavy environment configuration and high cost.
Why All‑In‑One (AIO) Sandbox
File sharing: browser sandbox files must be uploaded to NAS/OSS before code sandbox can use them, leading to slow transfers.
Tool coordination: multiple sandboxes require manual orchestration of start, communication and data passing.
Environment configuration: separate installations of Node.js, browsers and system dependencies cause version conflicts and resource pollution.
Cost: running several sandboxes doubles memory usage and adds network I/O latency.
Core Advantages
Zero‑configuration deployment via a single SDK call.
All components—browser, shell, code execution and a shared file system—run inside one container.
Isolated, resource‑limited execution for each function.
Architecture
All components share the directory /home/user/data/ inside the sandbox, eliminating cross‑sandbox file transfers.
Key stack:
Chromium 136+ (fixed version) for the browser.
WebSocket CDP endpoint ws://localhost:5000/ws/automation (port 5000).
Isolated function‑compute resources with strict limits.
Dynamic NAS/OSS mounting for persistent storage.
Performance Comparison (AIO vs Traditional Multi‑Sandbox)
Startup time: 5 s for a single AIO instance vs 4–15 s for two separate containers.
File transfer: direct access < 100 ms vs 2–3 s through OSS.
Memory usage: 2 c2g for shared container vs 2 c2g + 2 c2g for two containers.
Ready‑to‑Use Capabilities
Code execution with built‑in Node.js and Puppeteer.
File handling via a FileSystem API.
State persistence using mounted OSS/NAS.
Real‑time streaming logs.
Integrated VNC, terminal and code execution tools.
Access Methods
Code Execution API : run Node.js or Python scripts.
VNC : visual browser interaction and manual intervention.
Terminal WebSocket : real‑time shell access.
File API : read/write persistent files under /home/user/data/.
Quick Start (Python SDK)
pip install agentrun-sdk[server,playwright] from agentrun.sandbox import Sandbox, TemplateType
import asyncio
async def quick_start():
sandbox = Sandbox.create(
template_type=TemplateType.AIO,
template_name="quick-test",
sandbox_idle_timeout_seconds=600,
)
print(f"Sandbox created: {sandbox.sandbox_id}")
code = """
const puppeteer = require('puppeteer-core');
const browser = await puppeteer.connect({browserWSEndpoint: 'ws://localhost:5000/ws/automation'});
const page = (await browser.pages())[0];
await page.goto('https://example.com');
console.log(await page.title());
await browser.disconnect();
"""
await sandbox.context.execute_async(code=code, language="javascript")
sandbox.destroy()
asyncio.run(quick_start())Multi‑Step Task Mode
Useful when login, human interaction or large data volumes are required.
Open login page → manual VNC login.
Save cookies to /home/user/data/.
Reuse cookies for subsequent data extraction.
Tips:
Set sandbox_idle_timeout_seconds >= 1800 to keep the sandbox alive.
Always use browser.disconnect() instead of browser.close() to preserve browser state.
Store intermediate files under /home/user/data/.
Cookie Persistence Mode
// Save cookies after manual login
const cookies = await page.cookies();
fs.writeFileSync('/home/user/data/cookies.json', JSON.stringify(cookies, null, 2));
// Load cookies for later runs
const cookies = JSON.parse(fs.readFileSync('/home/user/data/cookies.json'));
await page.setCookie(...cookies);Batch Task Mode
Choose sequential execution in a single sandbox for dependent steps, or parallel execution with multiple sandboxes for independent tasks.
System Prompt Design (AI Agent Guidance)
You are the code‑generation assistant for AgentRun AIO Sandbox. Generate Puppeteer JavaScript that connects to ws://localhost:5000/ws/automation, performs the required actions, saves results to /home/user/data/, and uses disconnect() to keep the browser alive. Include try‑catch error handling.Error Handling (Production Ready)
try {
await page.goto(url, {waitUntil: 'networkidle2', timeout: 30000});
} catch (error) {
console.error(`Operation failed: ${error.message}`);
if (error.name === 'TimeoutError' && retryCount < maxRetries) {
await new Promise(r => setTimeout(r, 5000));
return executeWithRetry(url, retryCount + 1);
}
throw error;
}Performance Optimizations
Disable unnecessary resources (images, fonts, media) via request interception.
await page.setRequestInterception(true);
page.on('request', req => {
const type = req.resourceType();
if (['image','stylesheet','font','media'].includes(type)) req.abort();
else req.continue();
});Security Considerations
Never commit cookie files; add *_cookies.json to .gitignore.
Validate user‑provided selectors against a whitelist before using them.
const allowed = ['.button-primary', '.submit-btn'];
if (!allowed.includes(userInput)) throw new Error('Invalid selector');
await page.click(userInput);Debugging Tips
Use VNC URL https://vnc.example.com/sandbox/{sandbox_id} to watch the browser in real time.
Take screenshots before and after critical steps.
await page.screenshot({path: '/home/user/data/before.png', fullPage: true});
await page.screenshot({path: '/home/user/data/after.png', fullPage: true});Core Summary
The AIO sandbox solves file‑sharing, tool‑coordination, environment‑setup and cost issues by providing a single persistent container with built‑in Chromium, Node.js, VNC and a shared file system. It enables reliable multi‑step automation, cookie persistence and scalable batch processing while keeping resource consumption low.
Golden Rules
Always use puppeteer.connect(), never puppeteer.launch().
Always use browser.disconnect(), never browser.close().
Persist all data under /home/user/data/.
Split login flows into open‑login‑VNC, save‑cookies, reuse‑cookies steps.
Set cookies after visiting the target domain to avoid cross‑origin issues.
Pass state between steps via the shared file system, not global variables.
Wrap every critical operation in try‑catch with clear logging.
Common Pitfalls & Solutions
Using launch() creates a second browser and wastes memory → switch to connect().
Using close() destroys the browser state → use disconnect().
Not persisting cookies forces repeated logins → save to /home/user/data/cookies.json and reload.
Insufficient wait time leads to missing elements → use waitForSelector and networkidle2.
Incorrect file paths cause “file not found” errors → always use the /home/user/data/ directory.
Appendix: Demo Code & Resources
GitHub repository: https://github.com/devsapp/agentrun-sandbox-demos
Official documentation: https://docs.agent.run/
Sandbox tutorial: https://docs.agent.run/docs/tutorial/core/sandbox
Alibaba Cloud Native
We publish cloud-native tech news, curate in-depth content, host regular events and live streams, and share Alibaba product and user case studies. Join us to explore and share the cloud-native insights you need.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
