Examples (JavaScript / TypeScript)¶
Every block below is copy-pasteable. Use .mjs (or "type": "module") for import and top-level await. Catalog guests have python3, not python.
Hello from a microVM¶
import { Sandbox } from "@sistemo/sdk";
const sb = await Sandbox.create();
try {
const r = await sb.run("uname -a");
console.log(r.stdout);
console.log(r.exitCode); // 0
} finally {
await sb.close();
}
Save as hello.mjs and run node hello.mjs.
Run Node inside the guest¶
import { Sandbox } from "@sistemo/sdk";
const sb = await Sandbox.create({ stack: "node" });
try {
const r = await sb.run("node -e 'console.log(2 + 2)'");
console.log(r.stdout); // 4
if (r.exitCode !== 0) console.error(r.stderr);
} finally {
await sb.close();
}
Install a package, then run it¶
import { Sandbox } from "@sistemo/sdk";
const sb = await Sandbox.create({ stack: "node" });
try {
await sb.run("npm init -y");
const r = await sb.run("node -e 'console.log(process.version)'");
console.log(r.stdout);
} finally {
await sb.close();
}
Write a file, then execute it¶
import { Sandbox } from "@sistemo/sdk";
const script = "console.log('from a file')";
const sb = await Sandbox.create({ stack: "node" });
try {
await sb.run(`cat > /tmp/run.js <<'EOF'\n${script}\nEOF`);
console.log((await sb.run("node /tmp/run.js")).stdout);
} finally {
await sb.close();
}
Run AI-generated code¶
import { Sandbox } from "@sistemo/sdk";
const code = "console.log([...Array(10).keys()].reduce((a, b) => a + b, 0))";
const sb = await Sandbox.create({ stack: "node" });
try {
const r = await sb.run(`node -e ${JSON.stringify(code)}`);
if (r.exitCode === 0) console.log(r.stdout);
else console.error(r.exitCode, r.stderr);
} finally {
await sb.close();
}
Timeouts¶
import { Sandbox } from "@sistemo/sdk";
const sb = await Sandbox.create();
try {
const r = await sb.run("python3 -c 'while True: pass'", 5);
console.log(r.exitCode, r.stderr.slice(0, 200));
} finally {
await sb.close();
}
timeoutSec is enforced in the machine (exit 124). Ceiling 24 hours:
See Long-running work.
Catch quota vs auth¶
import { Sandbox, QuotaExceededError, AuthError, APIError } from "@sistemo/sdk";
try {
const sb = await Sandbox.create();
try {
console.log((await sb.run("uname -a")).stdout);
} finally {
await sb.close();
}
} catch (err) {
if (err instanceof QuotaExceededError) {
console.error("quota:", err.detail); // free a machine, then retry
} else if (err instanceof AuthError) {
console.error("key missing, revoked, or read-only");
} else if (err instanceof APIError) {
console.error(err.status, err.detail, err.code);
} else {
throw err;
}
}
Point at another API¶
import { Sandbox } from "@sistemo/sdk";
const sb = await Sandbox.create({
baseUrl: "https://your-own-host:8000",
apiKey: "sk_live_your_key",
});
Next: Sandbox API · Error handling · Connect an LLM