# Sandbox

> Sandboxes: a short-lived Linux box to run code in.

```python
with noclick.Sandbox.create(image="python", timeout_s=3600) as sb:
    sb.files.write("/tmp/in.csv", csv_bytes)
    print(sb.exec("python -c 'print(1 + 1)'").stdout)
    build = sb.exec("make all", background=True, timeout_s=1800)   # an Operation
    print(build.wait().exit_code)
# terminated on exit
```

## Sandbox

```typescript
class Sandbox
```

A running sandbox. `with noclick.Sandbox.create() as sb:` terminates it on exit;
otherwise it stops at `expires_at`. Billed per second while it runs, at its
provider's price for the `cpu` and `memory_mb` it reserves.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `status` | `string` |  |
| `image` | `string | null` |  |
| `timeoutS` | `number | null` |  |
| `cpu` | `number | null` |  |
| `memoryMb` | `number | null` |  |
| `region` | `RegionName | null` | The region it runs in, or `null`: wherever NoClick had capacity. |
| `userId` | `string | null` |  |
| `expiresAt` | `Date | null` |  |
| `createdAt` | `Date | null` |  |
| `volumes` | `Record<string, string>` | The volumes it mounts: `{ path: volume id }`. |
| `secretIds` | `string[]` | The secrets in its environment, in order (a later one's key wins). |
| `network` | `NetworkAccess | null` | What it may reach: `false` (nothing), `true` (anywhere) or the hosts it may reach, as sent. |
| `files` | `SandboxFiles` |  |

Types:

```typescript
type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";

/** `true` (anywhere), `false` (nothing) or the hosts it may reach, `"*.example.com"` for a domain and its subdomains. */
type NetworkAccess = boolean | string[];
```

### Sandbox.create

```typescript
static create(options?: SandboxCreateOptions): Promise<Sandbox>
```

Start a sandbox (`image` `"python"` or `"node"`) that lives
at most `timeout_s` seconds. `network=True` allows outbound
internet access, which is off by default. A list of up to 50 hosts allows
only those, over HTTPS on port 443: `"pypi.org"`, or `"*.example.com"` for a
domain and its subdomains (a scheme, path, port or IP address raises
`noclick.InvalidRequest`).

`region` is where it runs (`noclick.regions()`): `region=agent.region`
puts it beside an agent. Without one it runs in your account's default
region, else wherever NoClick has capacity. Pinned to a region it costs what the
provider charges there: 1.15x in `eu` and `ap`, 1.75x in `us-east` and `us-west`.

`volumes` mounts `Volume`s (or their ids or names) read-write at
absolute paths, `{"/data": vol}`, up to 5: the sandbox sees each as it
was when it started, and what it writes there is saved every few seconds
while it runs, and all of it when it ends. A path can't be `/`,
`/workspace` itself or a system folder.

`secrets` (`Secret`s, ids or names; up to 20) become environment
variables for every command, a later secret's key winning a clash; the
sandbox keeps the values it started with. A volume's or secret's name is
the sandbox's user's own, else the account's (a user session's, its own only).

Parameters:

- `options.timeoutS` (`number`): Lifetime before the sandbox is reclaimed.
- `options.cpu` (`number`)
- `options.memoryMb` (`number`)
- `options.network` (`NetworkAccess`): Allow outbound internet access (off by default). A list of up to 50 hosts allows only those, over
HTTPS on port 443: `"pypi.org"`, or `"*.example.com"` for a domain and its subdomains (a scheme,
path, port or IP address throws `InvalidRequest`).
- `options.region` (`RegionName`): Where it runs (`regions()`), for its whole life: `region: agent.region` puts it beside an
agent. Omitted, your account's default region, else wherever NoClick has capacity. Pinned to a
region it costs what the provider charges there: 1.15x in `eu` and `ap`, 1.75x in `us-east` and
`us-west`.
- `options.volumes` (`Record<string, VolumeRef>`): Volumes to mount read-write, by absolute path, up to 5: `{ "/data": Volume.fromName("datasets") }`
(a `Volume`, an id or a name: the sandbox's user's own, else the account's). It sees each as it was
when it started; what it writes there is saved every few seconds while it runs, and all of it when
it ends. Not `/`, `/workspace` itself or a system folder.
- `options.secrets` (`SecretRef[]`): Secrets whose keys become environment variables for every command (a `Secret`, an id or a name:
the sandbox's user's own, else the account's), up to 20; a later secret's key wins a clash, and
the sandbox keeps the values it started with.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.image` (`"python" | "node"`)

Returns: The sandbox, `running` and ready for commands. It stops on its own at `expires_at`.

Types:

```typescript
/** `true` (anywhere), `false` (nothing) or the hosts it may reach, `"*.example.com"` for a domain and its subdomains. */
type NetworkAccess = boolean | string[];

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";

/** A volume to mount: a `Volume`, its id, or its name (the user's own, else the account's). */
type VolumeRef = string | Volume;

/** A secret to pass: a `Secret`, its id, or its name (the user's own, else the account's). */
type SecretRef = string | Secret;

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Sandbox.fromId

```typescript
static fromId(sandboxId: string, options?: CallOptions): Sandbox
```

A lazy reference to a sandbox by id, for one you started earlier.

Parameters:

- `sandboxId` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

Returns: A sandbox that loads the first time you read a field. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Sandbox.get

```typescript
static get(sandboxId: string, options?: CallOptions): Promise<Sandbox>
```

Load a sandbox by id now; an unknown id raises `noclick.NotFound`.

Parameters:

- `sandboxId` (`string`, required)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The sandbox, loaded. Its `status` is `starting`, `running`, `terminated` or `failed`.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Sandbox.list

```typescript
static list(
  options?: ReadOptions & { status?: SandboxStatusFilter; limit?: number },
): Promise<Sandbox[]>
```

`status: "live"` lists the ones still starting or running.

Parameters:

- `options.status` (`SandboxStatusFilter`)
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching sandbox, newest first, fetched page by page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

type SandboxStatusFilter = "live" | "starting" | "running" | "terminated" | "failed";
```

### Sandbox.listPage

```typescript
static listPage(
  options?: ReadOptions & PageOptions & { status?: SandboxStatusFilter },
): Promise<Page<Sandbox>>
```

One page of sandboxes; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.status` (`SandboxStatusFilter`)
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A page whose `data` holds the sandboxes and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

type SandboxStatusFilter = "live" | "starting" | "running" | "terminated" | "failed";
```

### Sandbox.exec

```typescript
exec(
  command: string,
  options: ExecOptions & { background: true },
): Promise<Operation<ExecResult>>
exec(
  command: string,
  options?: ExecOptions & { background?: false },
): Promise<ExecResult>
```

Run a bash command in `/workspace`; a non-zero exit is a normal result, not an error.
`{ background: true }` returns at once with an `Operation` whose `wait()` resolves to the
`ExecResult`: for commands longer than one request allows (`timeoutS` up to 3600, within the
sandbox's own lifetime).

Parameters:

- `command` (`string`, required)
- `options.background` (`boolean`, required): Return at once with an `Operation` whose `wait()` resolves to the `ExecResult`.
- `options.timeoutS` (`number`): Seconds before the command is stopped: 60 by default, at most 90, or 3600 with `background`.

Returns: What the command printed and how it exited: `stdout` and `stderr` (the last 64 KiB of each)
and `exit_code`. With `background=True`, an `Operation` at once, whose `wait()` gives that result.

### Sandbox.shell

```typescript
shell(): Promise<CodeSandboxShell>
```

Open an interactive shell (`bash -l` in `/workspace`, in a PTY) in this running sandbox: the websocket's `url`
and its single-use `token` (good for two minutes), for a browser terminal (xterm.js) or `TerminalConnection`.
`noclick shell <sandbox>` opens one in your own terminal.

Returns: The websocket's `url` and its single-use `token` (good for two minutes): hand them to a browser
terminal (xterm.js) from your server.

### Sandbox.terminate

```typescript
terminate(): Promise<void>
```

Stop the sandbox now (billing stops with it).

## CodeSandboxShell

```typescript
interface CodeSandboxShell
```

An interactive shell in a sandbox (`sandbox.shell()`): `url` is a websocket, opened once with `token` within a
minute. Its first message is `{"type": "auth", token, cols, rows}`; then binary messages carry what you type and
what it prints, a text `{"type": "resize", cols, rows}` sizes it, and it closes (code 4410) once bash exits (its
last `state` frame naming `exit_code`), after `idleLimitS` with nothing typed, or when the socket closes.

| Attribute | Type | Description |
| --- | --- | --- |
| `sandboxId` | `string` |  |
| `url` | `string` |  |
| `token` | `string` |  |
| `tokenExpiresAt` | `Date | null` |  |
| `idleLimitS` | `number` |  |

## SandboxFiles

```typescript
class SandboxFiles
```

`sb.files`: read and write files inside the sandbox.

### SandboxFiles.write

```typescript
write(
  path: string,
  data: string | Uint8Array | ArrayBuffer | Blob,
): Promise<void>
```

Write `data` (bytes, or text as UTF-8) to `path`, replacing it.

Parameters:

- `path` (`string`, required)
- `data` (`string | Uint8Array | ArrayBuffer | Blob`, required)

### SandboxFiles.read

```typescript
read(path: string): Promise<Uint8Array>
```

Read the file at `path`; a missing file raises `noclick.NotFound`.

Parameters:

- `path` (`string`, required)

Returns: The file's bytes, exactly as stored; decode text yourself.

### SandboxFiles.readText

```typescript
readText(path: string): Promise<string>
```

Parameters:

- `path` (`string`, required)

## ExecResult

```typescript
interface ExecResult
```

What a command printed and how it exited (a non-zero `exit_code` is a result, not an error).

| Attribute | Type | Description |
| --- | --- | --- |
| `stdout` | `string` |  |
| `stderr` | `string` |  |
| `exitCode` | `number | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `ok` | `boolean` | Whether the command exited 0. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```
