Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

セッション管理

最終更新 Markdown で表示Agent セットアップ

セッションは、サンドボックス内の bash シェル実行コンテキストです。同じコンピューター上のターミナルタブのようなものです。

  • Sandbox = ユーザーまたはタスクのワークスペース
  • Session = そのワークスペース内のシェル

セッションは、1 つのサンドボックス内で作業を整理するのに向いています。ファイルシステムとプロセス空間を共有するため、ユーザー間のセキュリティ境界ではありません。

デフォルトセッション

既定では、すべてのサンドボックスにデフォルトセッションがあります。コンテナが動いているあいだ、コマンド間でシェル状態を保持します。

const sandbox = getSandbox(env.Sandbox, 'my-sandbox');

// These commands run in the default session
await sandbox.exec("cd /app");
await sandbox.exec("pwd");  // Output: /app

await sandbox.exec("export MY_VAR=hello");
await sandbox.exec("echo $MY_VAR");  // Output: hello

作業ディレクトリ、環境変数、export した変数はコマンド間で引き継がれます。非アクティブでコンテナが再起動すると、この状態はリセットされます。

getSandbox() 呼び出し時に enableDefaultSession: false を設定すると、明示的な sessionId なしの操作はデフォルトセッションを使わず、分離して実行されます。

const sandbox = getSandbox(env.Sandbox, 'my-sandbox', {
  enableDefaultSession: false
});

await sandbox.exec("cd /app");
await sandbox.exec("pwd");  // Output: /workspace (cd was not inherited)

デフォルトセッションがない場合、2 つ目のコマンドは 1 つ目のシェル状態を引き継ぎません。将来の Sandbox SDK リリースではこの設定がデフォルトになるため、常にこの設定を使うことをおすすめします。コマンド間でシェル状態を共有したいときは、明示的なセッションを作成または取得してください。

セッションの自動作成

コンテナは、初回利用時にセッションを自動作成します。存在しないセッション ID を参照すると、デフォルト設定で作成します。

// This session does not exist yet
const result = await sandbox.exec('echo hello', { sessionId: 'new-session' });
// Container automatically creates 'new-session' with defaults:
// - cwd: '/workspace'
// - env: {} (empty)

この動作は、セッション削除後に特に関係します。

// Create and configure a session
const session = await sandbox.createSession({
  id: 'temp',
  env: { MY_VAR: 'value' }
});

// Delete the session
await sandbox.deleteSession('temp');

// Using the same session ID again works - auto-created with defaults
const result = await sandbox.exec('echo $MY_VAR', { sessionId: 'temp' });
// Output: (empty) - MY_VAR is not set in the freshly created session

自動作成のため、存在しないセッションを参照してもコマンドは動きます。ただし、削除後はカスタム設定(環境変数、作業ディレクトリ)は失われます。

セッションを作成する

同じサンドボックス内で別々のワークフロー用に、追加セッションを作成できます。

const buildSession = await sandbox.createSession({
  id: "build",
  env: { NODE_ENV: "production" },
  cwd: "/build"
});

const testSession = await sandbox.createSession({
  id: "test",
  env: { NODE_ENV: "test" },
  cwd: "/test"
});

// Different shell contexts
await buildSession.exec("npm run build");
await testSession.exec("npm test");

セッション内のすべてのコマンドに、デフォルトのコマンドタイムアウトも設定できます。

const session = await sandbox.createSession({
  id: "ci",
  commandTimeoutMs: 30000 // 30s timeout for all commands
});

await session.exec("npm test"); // Times out after 30s if still running

個別のコマンドは、exec()timeout オプションでセッションのタイムアウトを上書きできます。詳細は Sessions APIコマンド実行ガイド を参照してください。

セッションにスコープされるもの

各セッションは次を独自に持ちます。

シェル環境:

await session1.exec("export MY_VAR=hello");
await session2.exec("echo $MY_VAR");  // Empty - different shell

作業ディレクトリ:

await session1.exec("cd /workspace/project1");
await session2.exec("pwd");  // Different working directory

環境変数createSession のオプションで設定):

const session1 = await sandbox.createSession({
  env: { API_KEY: 'key-1' }
});
const session2 = await sandbox.createSession({
  env: { API_KEY: 'key-2' }
});

セッション間で共有されるもの

同じサンドボックス内のすべてのセッションは、次を共有します。

ファイルシステム:

await session1.writeFile('/workspace/file.txt', 'data');
await session2.readFile('/workspace/file.txt');  // Can read it

プロセス:

await session1.startProcess('node server.js');
await session2.listProcesses();  // Sees the server

セッションを使う場面

次の場合はセッションを使います:

  • 1 人のユーザーの作業ごとに、別々のシェル状態が必要なとき
  • 異なる環境で並列操作を動かすとき
  • AI エージェントの認証情報を、アプリのランタイムから分けておきたいとき

例 - 開発環境とランタイム環境を分ける:

// Phase 1: AI agent writes code (with API keys)
const devSession = await sandbox.createSession({
  id: "dev",
  env: { ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY }
});
await devSession.exec('ai-tool "build a web server"');

// Phase 2: Run the code (without API keys)
const appSession = await sandbox.createSession({
  id: "app",
  env: { PORT: "3000" }
});
await appSession.exec("node server.js");

次の場合は別のサンドボックスを使います:

  • 信頼できないコードを完全に分離する必要があるとき
  • ユーザーごとに別のワークスペースが必要なとき
  • ユーザーデータを分けておく必要があるとき
  • 独立したリソース割り当てが必要なとき

ベストプラクティス

セッションのクリーンアップ

一時セッションはクリーンアップし、サンドボックスは動かしたままリソースを解放します。

try {
  const session = await sandbox.createSession({ id: 'temp' });
  await session.exec('command');
} finally {
  await sandbox.deleteSession('temp');
}

デフォルトセッションは削除できません:

// This throws an error
await sandbox.deleteSession('default');
// Error: Cannot delete default session. Use sandbox.destroy() instead.

ファイルシステムのスコープ

セッションはサンドボックスのファイルシステムを共有します。ファイル操作はすべてのセッションに影響します。

// Bad - affects all sessions
await session.exec('rm -rf /workspace/*');

// For user data or untrusted code, use a separate sandbox
const userSandbox = getSandbox(env.Sandbox, `user-${userId}`);

関連リソース

役に立ちましたか?