← Sandbox SDK / sandbox / api
Relace
Vytvářejte shellové relace uvnitř sandboxu. Každá relace si udržuje vlastní stav shellu, proměnné prostředí a pracovní adresář, přičemž sdílí souborový systém a prostor procesů sandboxu. Další informace najdete v Správa relací.
Metody
createSession()
Vytvoří novou shellovou relaci.
const session = await sandbox.createSession(options?: SessionOptions): Promise<ExecutionSession>Parametry:
options(volitelné):id- Vlastní ID relace (pokud není zadáno, vygeneruje se automaticky)env- Proměnné prostředí pro tuto relaci:Record<string, string | undefined>cwd- Pracovní adresář (výchozí:"/workspace")commandTimeoutMs- Maximální doba v milisekundách, po kterou může libovolný příkaz v této relaci běžet, než vyprší časový limit. Jednotlivé příkazy ji mohou přepsat pomocítimeoutmožnost naexec().
Vrací: Promise<ExecutionSession> se všemi metodami sandboxu navázanými na tuto relaci
// Separate workflow environments
const prodSession = await sandbox.createSession({
id: "prod",
env: { NODE_ENV: "production", API_URL: "https://api.example.com" },
cwd: "/workspace/prod",
});
const testSession = await sandbox.createSession({
id: "test",
env: {
NODE_ENV: "test",
API_URL: "http://localhost:3000",
DEBUG_MODE: undefined, // Skipped, not set in this session
},
cwd: "/workspace/test",
});
// Run in parallel
const [prodResult, testResult] = await Promise.all([
prodSession.exec("npm run build"),
testSession.exec("npm run build"),
]);
// Session with a default command timeout
const session = await sandbox.createSession({
commandTimeoutMs: 5000, // 5s timeout for all commands
});
await session.exec("sleep 10"); // Times out after 5s
// Per-command timeout overrides session-level timeout
await session.exec("sleep 10", { timeout: 3000 }); // Times out after 3s// Separate workflow environments
const prodSession = await sandbox.createSession({
id: 'prod',
env: { NODE_ENV: 'production', API_URL: 'https://api.example.com' },
cwd: '/workspace/prod'
});
const testSession = await sandbox.createSession({
id: 'test',
env: {
NODE_ENV: 'test',
API_URL: 'http://localhost:3000',
DEBUG_MODE: undefined // Skipped, not set in this session
},
cwd: '/workspace/test'
});
// Run in parallel
const [prodResult, testResult] = await Promise.all([
prodSession.exec('npm run build'),
testSession.exec('npm run build')
]);
// Session with a default command timeout
const session = await sandbox.createSession({
commandTimeoutMs: 5000 // 5s timeout for all commands
});
await session.exec('sleep 10'); // Times out after 5s
// Per-command timeout overrides session-level timeout
await session.exec('sleep 10', { timeout: 3000 }); // Times out after 3sgetSession()
Načte existující relaci podle ID.
const session = await sandbox.getSession(sessionId: string): Promise<ExecutionSession>Parametry:
sessionId- ID existující relace
Vrací: Promise<ExecutionSession> vázaný na zadanou relaci
// First request - create a task-specific session
const session = await sandbox.createSession({ id: "build" });
await session.exec("git clone https://github.com/user/repo.git");
await session.exec("cd repo && npm install");
// Second request - resume session (environment and cwd preserved)
const session = await sandbox.getSession("build");
const result = await session.exec("cd repo && npm run build");// First request - create a task-specific session
const session = await sandbox.createSession({ id: 'build' });
await session.exec('git clone https://github.com/user/repo.git');
await session.exec('cd repo && npm install');
// Second request - resume session (environment and cwd preserved)
const session = await sandbox.getSession('build');
const result = await session.exec('cd repo && npm run build');deleteSession()
Odstraní relaci a vyčistí její prostředky.
const result = await sandbox.deleteSession(sessionId: string): Promise<SessionDeleteResult>Parametry:
sessionId- ID relace ke smazání (nemůže být"default")
Vrací: Promise<SessionDeleteResult> obsahující:
success- Zda se smazání zdařilosessionId- ID smazané relacetimestamp- Časové razítko smazání
// Create a temporary session for a specific task
const tempSession = await sandbox.createSession({ id: "temp-task" });
try {
await tempSession.exec("npm run heavy-task");
} finally {
// Clean up the session when done
await sandbox.deleteSession("temp-task");
}// Create a temporary session for a specific task
const tempSession = await sandbox.createSession({ id: 'temp-task' });
try {
await tempSession.exec('npm run heavy-task');
} finally {
// Clean up the session when done
await sandbox.deleteSession('temp-task');
}setEnvVars()
Nastavte proměnné prostředí v sandboxu.
await sandbox.setEnvVars(envVars: Record<string, string | undefined>): Promise<void>Parametry:
envVars- Dvojice klíč-hodnota proměnných prostředí k nastavení nebo zrušenístringhodnoty: Nastavte proměnnou prostředíundefinednebonullhodnoty: Zrušte nastavení proměnné prostředí
const sandbox = getSandbox(env.Sandbox, "user-123");
// Set environment variables first
await sandbox.setEnvVars({
API_KEY: env.OPENAI_API_KEY,
DATABASE_URL: env.DATABASE_URL,
NODE_ENV: "production",
OLD_TOKEN: undefined, // Unsets OLD_TOKEN if previously set
});
// Now commands can access these variables
await sandbox.exec("python script.py");const sandbox = getSandbox(env.Sandbox, 'user-123');
// Set environment variables first
await sandbox.setEnvVars({
API_KEY: env.OPENAI_API_KEY,
DATABASE_URL: env.DATABASE_URL,
NODE_ENV: 'production',
OLD_TOKEN: undefined // Unsets OLD_TOKEN if previously set
});
// Now commands can access these variables
await sandbox.exec('python script.py');Metody ExecutionSession
ExecutionSession objekt má všechny metody sandboxu navázané na konkrétní relaci:
| Kategorie | Metody |
|---|---|
| Příkazy | exec(), execStream() |
| Procesy | startProcess(), listProcesses(), killProcess(), killAllProcesses(), getProcessLogs(), streamProcessLogs() |
| Soubory | writeFile(), readFile(), mkdir(), deleteFile(), renameFile(), moveFile(), gitCheckout() |
| Prostředí | setEnvVars() |
| Terminál | terminal() |
| Code Interpreter | createCodeContext(), runCode(), listCodeContexts(), deleteCodeContext() |
Související zdroje
- Koncept správy relací - Jak fungují relace
- Commands API - Spouštění příkazů