> ## Documentation Index
> Fetch the complete documentation index at: https://novita.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# アイドルタイムアウト

export const SandboxConfigHint = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    return <Note>Before running the example code in this document, please ensure you have properly configured environment variables. For details, please refer to <a href="/docs/ja/guides/sandbox-your-first-agent-sandbox#configure-environment-variables">Configure Environment Variables</a>.</Note>;
  }
};

サンドボックスに **アイドルタイムアウト** を設定すると、アクティブな接続が検出されない場合に自動的に停止または一時停止できます。これにより、未使用のサンドボックスが無期限に実行され続けることを防ぎ、コストを削減できます。

<SandboxConfigHint />

<Note>
  アイドルタイムアウトは、サンドボックス作成時に `metadata` フィールドで設定します。キーは `idle_timeout` で、値は秒数（文字列）です。
</Note>

## 基本的な使い方

サンドボックスを作成するときに、`metadata` オブジェクト内で `idle_timeout` キーを渡します。値はアイドルタイムアウトの期間を **秒** で表したもの（文字列）です。指定した期間、サンドボックスにクライアントが接続されていない場合、サンドボックスは自動的に kill または一時停止されます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Create a sandbox that will be automatically killed after 60 seconds of inactivity.
  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '60',
    },
  })

  // The sandbox is running...
  // After 60 seconds with no active connections, it will be killed automatically.
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Create a sandbox that will be automatically killed after 60 seconds of inactivity.
  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "60",
      },
  )

  # The sandbox is running...
  # After 60 seconds with no active connections, it will be killed automatically.
  ```
</CodeGroup>

## アイドルタイムアウトの仕組み

アイドルタイムアウト機能は、サンドボックスへのアクティブな接続を監視します。

1. **アクティブな接続がない場合** — サンドボックスの終了時刻が `current_time + idle_timeout_seconds` に設定されます。
2. **接続が再びアクティブになった場合** — サンドボックスの終了時刻は、元の最大サンドボックス有効期間に戻されます。
3. **再接続がないままアイドルタイムアウトが経過した場合** — サンドボックスは kill されます（`autoPause` が有効な場合は一時停止されます）。

つまり、少なくとも 1 つのアクティブなクライアントがサンドボックスに接続されている限り、サンドボックスは停止されません（例: `Sandbox.connect()` 経由、または開いている WebSocket/HTTP 接続）。

## kill ではなく一時停止する

デフォルトでは、アイドル状態のサンドボックスはアイドルタイムアウトが期限切れになると **kill** されます。後で再開できるように、代わりにサンドボックスを **一時停止** したい場合は、`autoPause` オプションを有効にします。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Create a sandbox that will be paused (instead of killed) after 60 seconds of inactivity.
  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '60',
    },
    autoPause: true,
  })

  // After 60 seconds of inactivity, the sandbox will be paused.
  // You can resume it later with Sandbox.connect().
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Create a sandbox that will be paused (instead of killed) after 60 seconds of inactivity.
  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "60",
      },
      auto_pause=True,
  )

  # After 60 seconds of inactivity, the sandbox will be paused.
  # You can resume it later with Sandbox.connect().
  ```
</CodeGroup>

<Note>
  `autoPause` が有効な場合、アイドルタイムアウト時にサンドボックスの状態は `paused` に遷移します。後で実行を再開するには、そのサンドボックスに [connect](/docs/ja/guides/sandbox-connect) できます。
</Note>

## 他の metadata との組み合わせ

`idle_timeout` metadata キーは、すでに使用している他の metadata キーと組み合わせることができます。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '120',
      env: 'production',
      userId: 'user-123',
    },
  })

  console.log('Sandbox ID:', sandbox.sandboxId)
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "120",
          "env": "production",
          "user_id": "user-123",
      },
  )

  print("Sandbox ID:", sandbox.sandbox_id)
  ```
</CodeGroup>

## タイムアウトの制約

| 制約        | 値            | 説明                                                            |
| --------- | ------------ | ------------------------------------------------------------- |
| **最小**    | 30 秒         | 30 秒未満の値は、急速な start/stop サイクルを防ぐために「アイドル無効」として扱われます。          |
| **デフォルト** | 無効 (0)       | `idle_timeout` が指定されていない場合、この機能は無効になり、サンドボックスは最大有効期間まで実行されます。 |
| **最大**    | サンドボックスの有効期間 | アイドルタイムアウトは、サンドボックスに設定された `timeout`（最大有効期間）を超えることはできません。      |

<Warning>
  `idle_timeout` を最小しきい値（30 秒）未満の値に設定した場合、そのサンドボックスではアイドルタイムアウト機能が **サイレントに無効化** されます。サンドボックスは最大有効期間が切れるまで実行されます。
</Warning>

## アイドルタイムアウトを無効にする

サンドボックスのアイドルタイムアウトを明示的に無効にするには、metadata から `idle_timeout` キーを省略するか、`"0"` に設定します。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // No idle timeout — sandbox runs until its maximum lifetime.
  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '0',
    },
  })

  // Alternatively, omit idle_timeout entirely:
  const sandbox2 = await Sandbox.create()
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # No idle timeout — sandbox runs until its maximum lifetime.
  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "0",
      },
  )

  # Alternatively, omit idle_timeout entirely:
  sandbox2 = Sandbox.create()
  ```
</CodeGroup>

## 一般的なユースケース

### 短時間の実行タスク

1 回限りのタスクを実行し、クライアントの切断後に保持する必要がないサンドボックスには、短いアイドルタイムアウトを使用します。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create({
    metadata: { idle_timeout: '60' },
  })

  // Execute code and get results...
  const result = await sandbox.runCode('print("Hello!")')

  // Disconnect — sandbox will be killed after 60 seconds of inactivity.
  await sandbox.kill()
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create(
      metadata={"idle_timeout": "60"},
  )

  # Execute code and get results...
  result = sandbox.run_code('print("Hello!")')

  # Disconnect — sandbox will be killed after 60 seconds of inactivity.
  sandbox.kill()
  ```
</CodeGroup>

### 長時間実行されるインタラクティブセッション

ユーザーが一時的に離席する可能性があるインタラクティブセッションで使用されるサンドボックスには、より長いアイドルタイムアウトを使用します。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create({
    metadata: { idle_timeout: '600' }, // 10 minutes
    autoPause: true,
  })

  // The sandbox will pause after 10 minutes of inactivity,
  // and can be resumed when the user returns.
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create(
      metadata={"idle_timeout": "600"},  # 10 minutes
      auto_pause=True,
  )

  # The sandbox will pause after 10 minutes of inactivity,
  # and can be resumed when the user returns.
  ```
</CodeGroup>
