# Sessions (https://luxor.ai/docs/sandbox/sessions)

> For the complete documentation index, see [llms.txt](https://luxor.ai/llms.txt)

Create and drive Sandbox sessions covering lifecycle, command execution, file I/O, port exposure, and SSH access.

A session is a single running sandbox. This page covers the full session surface: lifecycle, command execution, file I/O, ports, socket bridging, and SSH. Pick your tool in any code block, and the selection syncs across the page.

## Create a session

**Python**
```python
from tenki import Sandbox

sb = Sandbox.create(
    name="demo",
    cpu_cores=4,
    memory_mb=8192,
    allow_inbound=True,
    allow_outbound=True,
    env={"APP_ENV": "dev"},
    metadata={"owner": "alice"},
)
```

`Sandbox.create` waits by default via a single server-held request and returns an exec-ready session with data-plane access primed. Pass `wait=False` to return immediately in `CREATING`. Use `Client().create(...)` instead when you want to manage the client lifecycle yourself.

**TypeScript**
```typescript
const session = await sandbox.create({
  name: "demo",
  cpuCores: 4,
  memoryMb: 8192,
  allowInbound: true,
  allowOutbound: true,
  env: { APP_ENV: "dev" },
  metadata: { owner: "alice" },
});
```

`create()` waits by default via a single server-held request and returns a run-ready session with data-plane access primed. Pass `waitReady: false` to return immediately in `CREATING`.

**Go**
```go
// Create waits by default and returns a RUNNING, exec-ready session.
session, err := client.Create(
  ctx,
  tenkisandbox.WithName("demo"),
  tenkisandbox.WithCPUCores(4),
  tenkisandbox.WithMemoryMB(8192),
  tenkisandbox.WithAllowInbound(true),
  tenkisandbox.WithAllowOutbound(true),
  tenkisandbox.WithEnvs(map[string]string{"APP_ENV": "dev"}),
  tenkisandbox.WithMetadata(map[string]string{"owner": "alice"}),
  tenkisandbox.WithWaitTimeout(3*time.Minute),
)

// Opt out when you want to orchestrate readiness separately.
session, err := client.Create(ctx, tenkisandbox.WithName("demo"), tenkisandbox.WithWaitReady(false))
// Later: session.WaitReady(ctx, 3*time.Minute)
```

**CLI**
```bash
luxor sandbox create \
  --name my-session \
  --cpu 4 \
  --memory-mb 8192 \
  --allow-inbound \
  --allow-outbound \
  --env APP_ENV=dev \
  --metadata owner=alice \
  --metadata purpose=review
```

By default, the CLI waits until the session is `RUNNING` and exec-ready before returning (a single server-held request). Pass `--no-wait` to return immediately.

Every create call takes the same options, named per tool:

| Option           | TypeScript                           | Python                            | Go                                      | CLI                                          |
| ---------------- | ------------------------------------ | --------------------------------- | --------------------------------------- | -------------------------------------------- |
| Name             | `name`                               | `name`                            | `WithName`                              | `--name`                                     |
| CPU / memory     | `cpuCores`, `memoryMb`               | `cpu_cores`, `memory_mb`          | `WithCPUCores`, `WithMemoryMB`          | `--cpu`, `--memory-mb`                       |
| Disk size        | `diskSizeGb`                         | `disk_size_gb`                    | `WithDiskSizeGB`                        | `--disk-size-gb`                             |
| Network          | `allowInbound`, `allowOutbound`      | `allow_inbound`, `allow_outbound` | `WithAllowInbound`, `WithAllowOutbound` | `--allow-inbound`, `--allow-outbound`        |
| Allowed domains  | `allowDomains`                       | `allow_domains`                   | `WithAllowDomains`                      | `--allow-domain`                             |
| Allowed CIDRs    | `allowCidrs`                         | `allow_cidrs`                     | `WithAllowCIDRs`                        | `--allow-cidr`                               |
| Metadata / env   | `metadata`, `env`                    | `metadata`, `env`                 | `WithMetadata`, `WithEnvs`              | `--metadata`, `--env`                        |
| Tags             | `tags`                               | `tags`                            | `WithTags`                              | `--tags`                                     |
| SSH keys         | `sshAuthorizedKeys`                  | `ssh_authorized_keys`             | `WithSSHKeys`                           | `--authorized-key`, `--authorized-keys-file` |
| Volumes          | `volumes`                            | `volumes`                         | `WithVolume`                            | `--volume`                                   |
| Snapshot / image | `snapshotId`, `image`                | `snapshot_id`, `image`            | `WithSnapshot`, `WithImage`             | `--snapshot`, `--image`                      |
| Max duration     | `maxDurationMs`                      | `max_duration`                    | `WithMaxDuration`                       | `--max-duration`                             |
| Pause retention  | `pauseRetentionMs`                   | `pause_retention`                 | `WithPauseRetention`                    | `--pause-retention`                          |
| Sticky           | `sticky`                             | `sticky`                          | `WithSticky`                            | `--sticky`                                   |
| OpenCode         | `enableOpenCode`, `openCodeProvider` | `enable_opencode`                 | `WithOpenCode`, `WithOpenCodeProvider`  | n/a                                          |
| Clone repo       | `cloneRepoUrl`, `githubToken`        | `clone_repo_url`, `github_token`  | `WithCloneRepo`, `WithGitHubToken`      | n/a                                          |
| Wait for ready   | `waitReady`, `waitTimeoutMs`         | `wait`, `timeout`                 | `WithWaitReady`, `WithWaitTimeout`      | `--no-wait`, `--wait-timeout`                |

Unset options fall back to service defaults of 2 vCPU, 4096 MB, and a 5 GiB root disk.
Set `diskSizeGb`, `disk_size_gb`, `WithDiskSizeGB`, or `--disk-size-gb` to 20 for coding agents that clone repositories and install dependencies.
Inbound and outbound networking are enabled by default in every SDK and the CLI.
Use the network options to disable either direction, or set an [outbound allowlist](#outbound-allowlists) to restrict destinations.

Environment variables are plaintext configuration, not a secret-management channel.
Do not pass long-lived credentials through `env`.

## Sticky sessions

`sticky` takes precedence over `maxDurationMs`, `max_duration`, `WithMaxDuration`, and `--max-duration`.
When both are set, Luxor Agent Cloud discards the requested maximum duration and returns a create-session warning.
A sticky session runs until you terminate it.
A manual pause stops compute but does not clear sticky, so the session is still sticky after resume.
Sticky is not fixed at create time; see [Updating a running session](#updating-a-running-session) to toggle it, and to trade sticky for a bounded lifetime on a session that is already running.

## Pausing and resuming

Pause and resume preserve the VM's memory and durable filesystem state, but active terminal, SSH, preview, and other TCP connections close when the session pauses.
Reconnect after the session returns to `RUNNING`.
`/tmp` is kept across a pause but cleared when you create a snapshot, so write logs and durable state under `/home/tenki` or on an attached volume.
A process you started over `exec` survives a pause with the same PID, but it runs inside the guest-agent's cgroup and does not survive a guest-agent restart, so start anything load-bearing from a template start command.

The SDK's synchronous `pause()` call waits for `PAUSED`.
By default, Luxor Agent Cloud commits that state once the memory checkpoint and root disk are ready on the source host.
Replication to shared storage continues in the background, so you can request a resume without waiting for those uploads.
Until replication finishes, resume depends on the source host remaining available.

To return once the pause request is accepted, use the asynchronous pause method, then wait for `PAUSED` before resuming:

| SDK        | Request pause                | Wait for `PAUSED`                        |
| ---------- | ---------------------------- | ---------------------------------------- |
| TypeScript | `await session.pauseAsync()` | `await session.waitPaused(300_000)`      |
| Python     | `sb.pause_async()`           | `sb.wait_paused(timeout=300)`            |
| Go         | `session.PauseAsync(ctx)`    | `session.WaitPaused(ctx, 5*time.Minute)` |

The CLI returns after acceptance by default.
Add `--wait` when the next command depends on the session being paused:

```bash
luxor sandbox pause --session <session-id> --wait
luxor sandbox resume --session <session-id>
```

To create independent copies while the source continues running, see [Fork a running session](https://luxor.ai/docs/sandbox/snapshots.md#fork-a-running-session).

## Create and wait

A waiting create can fail *after* the service has admitted the sandbox (3 minutes by default).

Each SDK reports this as a dedicated error that carries the sandbox handle, so you can close it, inspect it, or keep waiting:

| Meaning                                    | TypeScript                   | Python                       | Go                            |
| ------------------------------------------ | ---------------------------- | ---------------------------- | ----------------------------- |
| Admitted, not ready inside the wait budget | `WaitReadyFailedError`       | `WaitReadyFailedError`       | `*WaitReadyFailedError`       |
| Template runtime readiness failed          | `TemplateRuntimeFailedError` | `TemplateRuntimeFailedError` | `*TemplateRuntimeFailedError` |

**TypeScript**
```typescript
import { TenkiSandbox, WaitReadyFailedError } from "@tenkicloud/sandbox";

const sandbox = new TenkiSandbox();

try {
  const session = await sandbox.create({ name: "demo", waitTimeoutMs: 180_000 });
  // ... use the session
} catch (err) {
  if (err instanceof WaitReadyFailedError) {
    // The sandbox is up and billing. Close it, or keep waiting on `err.session`.
    await err.session.close();
  }
  throw err;
}
```

**Python**
```python
from tenki import Client, WaitReadyFailedError

client = Client()

try:
    sb = client.create(name="demo", timeout=180)
except WaitReadyFailedError as err:
    # The sandbox is up and billing. Close it, or keep waiting on `err.sandbox`.
    err.sandbox.close()
    raise
```

**Go**
```go
session, err := client.Create(ctx,
  tenkisandbox.WithName("demo"),
  tenkisandbox.WithWaitTimeout(3*time.Minute),
)
if err != nil {
  var waitErr *tenkisandbox.WaitReadyFailedError
  if errors.As(err, &waitErr) && waitErr.Session != nil {
    // The sandbox is up and billing. Close it, or keep waiting on waitErr.Session.
    _ = waitErr.Session.Close(ctx)
  }
  return err
}
```

`TemplateRuntimeFailedError` carries the handle on the same field, so the same branch covers both. In Go, `errors.Is(err, tenkisandbox.ErrWaitReadyFailed)` matches too when you only need to classify the failure.

Scope-based cleanup — `await using`, `with`, `defer session.Close(ctx)` — only runs once create has returned, so it cannot cover a create that throws. Handle these errors explicitly wherever you create with waiting enabled.

A sandbox that never leaves `CREATING` is reaped for you. The case worth closing yourself is the one that reaches `RUNNING` just after your wait expired: it keeps running, and billing, until its max duration.

> **Requires SDK 0.5.2 or newer:** @tenkicloud/sandbox 0.5.2+, tenki 0.5.2+ (PyPI), and tenki-sdk-go sandbox/v0.5.2+ return the handle. Earlier releases reject without one, leaving nothing to close. The legacy tenki-sandbox PyPI package stops at 0.4.0 and never received the fix — switch to tenki.

## Manage a session

`WaitReady`/`wait_ready` is only needed for sessions obtained via get/list or created with wait disabled; the create calls above already return ready sessions.

**TypeScript**
```typescript
await session.refresh();
await session.extend(600_000); // +10 minutes
await session.pause();
await session.resume();
await session.close(); // or session.closeIfOpen(), or Symbol.asyncDispose

// List and inspect
const sessions = await sandbox.list();
const s = await sandbox.get(sessionId);
```

**Python**
```python
sb.wait_ready(180)
sb.refresh()
sb.extend(1800)  # +30 minutes (seconds or a timedelta)
sb.pause()
sb.resume()
sb.close()  # or sb.close_if_open(); the context manager closes on exit

# List and inspect
sessions = client.list()
sb = client.get(session_id)
```

**Go**
```go
err = session.WaitReady(ctx, 3*time.Minute)
err = session.Refresh(ctx)
err = session.Extend(ctx, 30*time.Minute)
err = session.Pause(ctx)
err = session.Resume(ctx)
err = session.Close(ctx)
err = session.CloseIfOpen(ctx)

// List and inspect
sessions, err := client.List(ctx)
session, err := client.Get(ctx, sessionID)
```

**CLI**
```bash
# List and inspect
luxor sandbox list
luxor sandbox list --json
luxor sandbox get --session <session-id>

# Pause, resume, terminate
luxor sandbox pause --session <session-id> --wait
luxor sandbox resume --session <session-id>
luxor sandbox terminate --session <session-id>
```

### Filtering a session list

`list` returns every non-terminated session in the workspace unless you narrow it. Tag filtering is an AND: a session must carry every tag you pass to match. Tags are trimmed and lowercased on both write and read, so filter casing never has to match how the tags were set.

| Filter                   | TypeScript          | Python               | Go                      |
| ------------------------ | ------------------- | -------------------- | ----------------------- |
| Tags (AND)               | `tags`              | `tags`               | `WithTagFilter`         |
| Sticky only / non-sticky | `sticky`            | `sticky`             | `WithStickyFilter`      |
| Include terminated       | `includeTerminated` | `include_terminated` | `WithIncludeTerminated` |
| Explicit workspace scope | `workspaceId`       | `workspace_id`       | `WithWorkspaceID`       |

**TypeScript**
```typescript
const sessions = await sandbox.list({ tags: ["ci", "nightly"], sticky: true });
```

**Python**
```python
sessions = client.list(tags=["ci", "nightly"], sticky=True)
```

**Go**
```go
sessions, err := client.List(ctx,
  tenkisandbox.WithTagFilter("ci", "nightly"),
  tenkisandbox.WithStickyFilter(true),
)
```

Terminated sessions are omitted by default. Ask for them explicitly when you are reconciling against your own records, since a session you cannot find is otherwise indistinguishable from one that has been cleaned up.

Workspace API keys infer their workspace server-side; the explicit workspace scope is for service tokens that can see more than one.

### Updating a running session

Name, tags, and sticky are mutable after create. Only the fields you pass change.

| Field        | TypeScript               | Python                    | Go                           |
| ------------ | ------------------------ | ------------------------- | ---------------------------- |
| Name         | `name`                   | `name`                    | `WithName`                   |
| Tags         | `tags` (or `updateTags`) | `tags` (or `update_tags`) | `WithTags` (or `UpdateTags`) |
| Sticky       | `sticky`                 | `sticky`                  | `WithSetSticky`              |
| Max duration | `maxDurationMs`          | `max_duration`            | `WithSetMaxDuration`         |

**TypeScript**
```typescript
await session.update({ name: "review-42", tags: ["ci", "pr-42"] });

// Un-stick and give the session a bounded lifetime.
await session.update({ sticky: false, maxDurationMs: 3_600_000 });

await session.update({ tags: [] }); // clears every tag
```

**Python**
```python
sb.update(name="review-42", tags=["ci", "pr-42"])

# Un-stick and give the session a bounded lifetime.
sb.update(sticky=False, max_duration=3600)

sb.update(tags=[])  # clears every tag
```

**Go**
```go
err = session.Update(ctx,
  tenkisandbox.WithName("review-42"),
  tenkisandbox.WithTags("ci", "pr-42"),
)

// Un-stick and give the session a bounded lifetime.
err = session.Update(ctx,
  tenkisandbox.WithSetSticky(false),
  tenkisandbox.WithSetMaxDuration(time.Hour),
)

err = session.Update(ctx, tenkisandbox.WithTags()) // clears every tag
```

Tags replace rather than merge, so pass the full set you want; an empty list clears them.

Setting a max duration requires passing sticky in the same call, and every SDK rejects the call locally when you omit it. Sticky still wins when both are set, so setting sticky true alongside a duration discards the duration and returns a warning. Pass `sticky: false` when the point is to give the session a lifetime. Update returns warnings the same way create does, so read them instead of assuming a field took effect.

## When a sandbox stops responding

Luxor Agent Cloud checks that the agent inside each sandbox answers.
When it stops answering, Luxor Agent Cloud recovers the sandbox before it terminates it:

1. A watchdog inside the sandbox restarts a hung agent, usually within about a minute.
   This stops processes the agent started, so restart them afterwards.
2. If the agent is still silent after two minutes, Luxor Agent Cloud reboots the sandbox and waits another two minutes.
   The disk, network, CPU, memory, and attached volumes come back, but running processes and memory do not.
   Secrets delivered to the sandbox are delivered again.
3. If the reboot fails, or the agent stays silent after it, Luxor Agent Cloud terminates the sandbox.

The sandbox stays `RUNNING` through steps 1 and 2 and keeps running if the agent comes back.
A hypervisor crash still terminates the sandbox at once.
Watchdog restarts apply to sandboxes created from a rebuilt base image.

When Luxor Agent Cloud terminates a sandbox, commands that were running on it end with the reason `session_terminated:<cause>: <detail>`.
The SDKs raise `SessionTerminatedError` with the cause in `terminationCause` (TypeScript), `termination_cause` (Python), or `Cause` (Go).
The cause tells you which step failed:

| Cause                               | Meaning                                                                        |
| ----------------------------------- | ------------------------------------------------------------------------------ |
| `guest_agent_liveness`              | The agent stopped answering and the sandbox could not be rebooted.             |
| `guest_agent_reboot_failed`         | The reboot request failed.                                                     |
| `guest_agent_liveness_after_reboot` | The agent stayed silent for two minutes after the reboot.                      |
| `guest_reactivation_failed`         | The agent answered after the reboot, but restoring the sandbox's setup failed. |

If a sandbox is terminated this way, you can often [recover its disk](#recover-a-terminated-sandbox).

## Recover a terminated sandbox

When Luxor Agent Cloud terminates a sandbox, for example after a crash, a failed health check, or a timeout, it keeps the sandbox's disk for 7 days.
Turn that disk into a snapshot with `recover` (the `luxor` CLI **2.10.0 or later**):

```bash
luxor sandbox recover <session-id>
```

The command waits for the snapshot, then prints a `restore` line with the command that starts a sandbox from it:

```bash
luxor sandbox create --snapshot <snapshot-id>
```

Add `--start` to create the sandbox right away.
It becomes your active session:

```bash
luxor sandbox recover <session-id> --start
```

You can pass the sandbox name instead of its ID when exactly one terminated sandbox has that name.
`--name` names the snapshot, `--expires-in 24h` or `--expires-at <RFC3339 time>` sets when it expires, and `--wait-timeout` (default `10m`) limits how long the command waits.
Add `--json` for machine-readable output with the snapshot and the restore command.

The recovered sandbox starts from the disk alone: your files are there, but memory and running processes are not.
If the sandbox had [volumes](https://luxor.ai/docs/sandbox/volumes.md) attached, attach them again.

The disk is kept only when Luxor Agent Cloud terminated the sandbox.
Sandboxes you terminated yourself, and sandboxes of a deleted workspace, keep nothing.
Recovery can fail with:

| Error                                                                                              | What to do                                                                       |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `session disk was not retained: only sessions the platform terminated keep their disk, for 7 days` | Nothing to recover. You terminated it, or the host had no disk space to keep it. |
| `session disk retention expired at <time>`                                                         | The 7 days passed. The disk is gone.                                             |
| `the host that ran this session is offline; retry once it reconnects`                              | Retry later.                                                                     |
| `the host that ran this session cannot recover its disk until its node-agent is updated`           | Contact support.                                                                 |

## Command execution

There are three ways to run a command, from least to most control:

* **One-shot** (`exec`): starts the process, buffers its output, and returns a single result when it exits. Use it for short commands where you only need the outcome.
* **Output streaming** (`session.stream()` in TypeScript, `session.Stream()` in Go, iterating `proc.stdout` in Python): incremental stdout/stderr chunks as the command produces them. Use it for output-heavy or long commands you want to follow live.
* **Process handle** (`sb.start()` in Python, `session.run()` in TypeScript, `session.Command(...).Stream()` in Go): the running process itself — pid, writable stdin, signals, and kill. Use it for interactive processes and anything you may need to stop early.

All three report the same [command result](#command-results) when the process exits.

For `git`, prefer the structured helpers over shelling out: `clone`, `checkout`, `diff`, `log`, and `fetchPR` are available on the session as `git` in every SDK, and return the raw `git` output. See [Git helpers](https://luxor.ai/docs/sandbox/sdk.md#git-helpers).

**Python**
```python
# One-shot: collects stdout/stderr and returns a result
result = sb.exec("bash", "-lc", "echo $APP_ENV && make test", env={"APP_ENV": "ci"}, timeout=120)
if not result.ok:
    raise RuntimeError(f"failed: exit={result.exit_code} stderr={result.stderr_text}")

# Or start a live process and stream output
proc = sb.start("npm", "test")
proc.close_stdin()
for chunk in proc.stdout:
    print(chunk.decode(), end="")
proc.wait().check()
```

`exec` accepts `cwd`, `env`, `timeout`, `input`, and `check=True` (raises `CommandFailedError` on a non-zero exit). Use `sb.shell("...")` for shell parsing.

`start` takes the same options (with `stdin` in place of `input`, and no `check`) and returns a `Process` handle: `proc.pid`, iterable `proc.stdout` / `proc.stderr` (bytes chunks), `proc.close_stdin()`, `proc.signal("TERM")`, `proc.kill()`, and `proc.wait()`, which returns the same `CommandResult` as `exec`.

**TypeScript**
```typescript
// One-shot
const result = await session.exec("npm", {
  args: ["test"],
  timeoutMs: 60_000,
  onOutput: (chunk) => process.stdout.write(chunk.data),
});

// Or stream explicitly
const stream = await session.stream("npm", { args: ["test"] });
for (;;) {
  const chunk = await stream.next();
  if (!chunk) break;
  process.stdout.write(chunk.data);
}
await stream.wait();

// Or take a process handle: stdin, signals, kill
const proc = session.run(["python3", "worker.py"], { cwd: "/home/tenki/app" });
console.log(await proc.pid);

const writer = proc.stdin.getWriter();
await writer.write(new TextEncoder().encode("job-1\n"));
await writer.close();

await proc.signal("TERM"); // or proc.kill()
const runResult = await proc; // the handle is awaitable
```

`exec` accepts `args`, `cwd`, `env`, `timeoutMs`, `onOutput`, and an `AbortSignal`; `stream` takes the same options and returns a `Stream` with `next()`, `wait()`, and `cancel()`.

`run` takes a full argv array plus `cwd`, `env`, `stdin`, and `privileged`. The `ProcessRunHandle` exposes `pid` (a promise), `stdout` / `stderr` (`ReadableStream<Uint8Array>`), a writable `stdin`, `signal()`, and `kill()`; awaiting the handle returns `{ exitCode, stdout, stderr, signal?, durationMs?, reason?, errno? }`.

**Go**
```go
result, err := session.Exec(
  ctx,
  "bash",
  tenkisandbox.WithArgs("-lc", "echo $APP_ENV && make test"),
  tenkisandbox.WithEnv("APP_ENV", "ci"),
  tenkisandbox.WithTimeout(2*time.Minute),
)
if err != nil {
  log.Fatal(err)
}

if !result.Status.IsSuccess() {
  log.Fatalf("failed: exit=%d stderr=%s", result.ExitCode, result.StderrString())
}
```

Stream incremental output instead of buffering it:

```go
stream, err := session.Stream(ctx, "npm", tenkisandbox.WithArgs("test"))
for {
  chunk, err := stream.Next()
  if errors.Is(err, io.EOF) {
    break
  }
  os.Stdout.Write(chunk.Data)
}
result, err := stream.Wait()
```

Or take a process handle — stdin, signals, kill — via `Command`:

```go
cmd := session.Command([]string{"python3", "worker.py"}, tenkisandbox.RunOptions{Dir: "/home/tenki/app"})
proc, err := cmd.Stream(ctx)

fmt.Fprintln(proc.Stdin, "job-1")
proc.Stdin.Close()
go io.Copy(os.Stdout, proc.Stdout)

err = proc.Signal(syscall.SIGTERM) // or proc.Kill()
result, err = proc.Wait()
```

Exec options: `WithArgs`, `WithTimeout`, `WithEnv`, `WithEnvs`; `Stream` takes the same options, and its handle adds `Cancel()`. `Command` takes a full argv slice plus `RunOptions` (`Env`, `Dir`, `Stdin`, `Timeout`, `Privileged`); `cmd.Exec(ctx)` runs it one-shot, `cmd.Stream(ctx)` returns a `RunHandle` with `PID`, `Stdin`, `Stdout`, `Stderr`, `Signal()`, `Kill()`, and `Wait()`.

Result helpers: `result.StdoutString()`, `result.StderrString()`, `result.Status.IsSuccess()`, `IsFailed()`, `IsTimedOut()`.

**CLI**
```bash
luxor sandbox exec --session <session-id> -c 'go test ./...'
luxor sandbox exec --session <session-id> --timeout 2m -c 'npm ci && npm test'
```

`-c` (short for `--shell`) runs the line through a shell so `&&`, pipes, redirects and globs work. Without it, `exec` runs the program directly with no shell; to pass flags straight to a program, put them after `--` (for example `luxor sandbox exec -- bash -lc '...'`).

CLI output includes:

* streamed stdout and stderr
* final status, exit code, and duration

### Command results

Every execution path reports the same result object when the process exits — `ExecResult` in TypeScript, `CommandResult` in Python, `Result` in Go. Captured `stdout` / `stderr` are raw bytes in all three; use the decoding helpers for text.

| Field          | TypeScript `ExecResult`                          | Python `CommandResult`                     | Go `Result`                                                 |
| -------------- | ------------------------------------------------ | ------------------------------------------ | ----------------------------------------------------------- |
| Exit code      | `exitCode`                                       | `exit_code`                                | `ExitCode`                                                  |
| Output (bytes) | `stdout`, `stderr` (`Uint8Array`)                | `stdout`, `stderr` (`bytes`)               | `Stdout`, `Stderr` (`[]byte`)                               |
| Output (text)  | `stdoutText(result)`, `stderrText(result)`       | `result.stdout_text`, `result.stderr_text` | `result.StdoutString()`, `result.StderrString()`            |
| Success check  | `isSuccess(result.status)`                       | `result.ok`, `result.check()`              | `result.Status.IsSuccess()`, `.IsFailed()`, `.IsTimedOut()` |
| Status         | `status` (`SUCCEEDED`, `FAILED`, `TIMED_OUT`, …) | derived from `exit_code` + `signal`        | `Status`                                                    |
| Duration       | `durationMs`                                     | `duration_ms`                              | `Duration`                                                  |
| Timing         | `startedAt`, `endedAt`                           | —                                          | `StartedAt`, `EndedAt`                                      |
| Failure detail | —                                                | `signal`, `reason`, `errno`                | —                                                           |
| Invocation     | `sessionId`, `command`, `args`                   | `argv`                                     | `SessionID`, `Command`, `Args`                              |

TypeScript's `run()` handle resolves to a slimmer `ProcessRunResult` instead: `exitCode`, `stdout`, `stderr`, plus `signal`, `durationMs`, `reason`, and `errno` (the raw errno on fork/exec failures such as `ENOENT` or `EACCES`).

## File operations

File operations are rooted in the session's working directory, `/home/tenki`. Relative paths resolve from there; absolute paths outside it (including `/tmp`) are rejected with a permission error.

Every SDK covers the same surface: read and write, directory listing, metadata (`stat`), directory creation, and deletes. `mkdir` creates missing parent directories and `remove` deletes recursively. For large files, the streaming variants transfer data in chunks instead of buffering the whole file in memory.

A single non-streaming read or write handles at most 32 MiB.
A larger file fails with `file too large for ReadFile: size_bytes=<n> max_bytes=<m>; use ReadFileStream` (or `WriteFile` and `WriteFileStream`) instead of loading the file into the sandbox's memory.
The SDKs raise `FileTooLargeError` (Go also matches `ErrFileTooLarge`), and the error carries the operation, the file size, and the limit.
Use the streaming calls for anything that may pass 32 MiB.
The `luxor` CLI **2.10.0 or later** streams on its own.

**Python**
```python
sb.fs.write_text("/home/tenki/config.json", '{"key": "value"}')
data = sb.fs.read_text("/home/tenki/config.json")

# Bytes, directory listing, and local <-> guest transfers
sb.fs.write_bytes("/home/tenki/blob.bin", b"\x00\x01")
entries = sb.fs.list("/home/tenki", include_hidden=True)
sb.fs.upload("./local.tar", "/home/tenki/local.tar")
sb.fs.download("/home/tenki/build.log", "./build.log")

# Metadata and directories
info = sb.fs.stat("/home/tenki/config.json")  # path, size, mode, is_dir, modified_unix_ns
sb.fs.mkdir("/home/tenki/data/raw")
sb.fs.remove("/home/tenki/data")

# Stream large files in chunks, or only a byte range (length 0 reads to the end)
for chunk in sb.fs.read_stream("/home/tenki/build.log"):
    handle(chunk)
for chunk in sb.fs.read_stream("/home/tenki/build.log", offset=1_048_576, length=4096):
    handle(chunk)
sb.fs.write_stream("/home/tenki/dump.bin", chunks)
```

**TypeScript**
```typescript
import { createReadStream } from "node:fs";
import { Readable } from "node:stream";

await session.writeFile("/home/tenki/config.json", '{"key": "value"}');
const data = await session.readFile("/home/tenki/config.json"); // Uint8Array

// Directory listing, metadata, and directories
const entries = await session.list("/home/tenki", { includeHidden: true });
const info = await session.stat("/home/tenki/config.json"); // path, size, mode, isDir, modifiedUnixNs
await session.mkdir("/home/tenki/data/raw");
await session.remove("/home/tenki/data");

// Stream large files in chunks
const stream = await session.readFileStream("/home/tenki/build.log"); // ReadableStream<Uint8Array>
const range = await session.readFileStream("/home/tenki/build.log", { offset: 1_048_576, length: 4096 }); // length 0 reads to the end
const fileStream = Readable.toWeb(createReadStream("./local.tar"));
await session.writeFileStream("/home/tenki/local.tar", fileStream);
```

**Go**
```go
err = session.WriteFile(ctx, "/home/tenki/hello.txt", []byte("hello"))
data, err := session.ReadFile(ctx, "/home/tenki/hello.txt")

// Directory listing, metadata, and directories
entries, err := session.List(ctx, "/home/tenki", tenkisandbox.ListOptions{IncludeHidden: true})
info, err := session.Stat(ctx, "/home/tenki/hello.txt") // Path, Size, Mode, IsDir, ModifiedUnixNs
err = session.Mkdir(ctx, "/home/tenki/data/raw")
err = session.Remove(ctx, "/home/tenki/data")

// Stream large files in chunks
r, err := session.ReadFileStream(ctx, "/home/tenki/build.log") // io.ReadCloser
defer r.Close()

// A byte range: offset, then length (0 reads to the end)
part, err := session.ReadStream(ctx, "/home/tenki/build.log", 1048576, 4096)
defer part.Close()

f, err := os.Open("./local.tar")
err = session.WriteFileStream(ctx, "/home/tenki/local.tar", f)
```

**CLI**
```bash
# inline
luxor sandbox write --session <session-id> --path /home/tenki/app.env --data 'PORT=3000'

# from a local file
luxor sandbox write --session <session-id> --path /home/tenki/config.json --data-file ./config.json

# from stdin
cat ./local-file.txt | luxor sandbox write --session <session-id> --path /home/tenki/input.txt

# read to stdout
luxor sandbox read --session <session-id> --path /home/tenki/config.json

# read into a local file
luxor sandbox read --session <session-id> --path /home/tenki/build.log --out ./build.log
```

The CLI covers `write` and `read`; use the SDKs for directory listing, metadata, and deletes.
With the `luxor` CLI **2.10.0 or later**, `read` and `write` stream, so file size is not a limit, and `read` takes a byte range and resumes.

To read part of a file, pass a byte range:

```bash
luxor sandbox read --session <session-id> --path /home/tenki/build.log --offset 1048576 --limit 4096 --out ./part.log
```

`--offset` is where to start and `--limit` is the most bytes to read; `0` or no `--limit` reads to the end.
An `--offset` past the end of the file is an error, and an `--offset` equal to the file size reads nothing.

If a read stops early, the command fails and prints where to continue:

```text
read stopped at byte 524288000 of 1181116006; rerun with --offset 524288000 and the same --out to append the rest
```

Rerun with that `--offset` and the same `--out` to append to the partial file.
Appending works only when the file is exactly `--offset` bytes long; any other size is an error.
An existing `--out` file is replaced only when the read succeeds.
If `--out` did not exist, a failed read keeps the bytes it already wrote, so you can resume.
With `--json` or `--output json`, the result includes `size`, `offset`, `bytes`, and `truncated`, plus `resume_offset` when bytes remain.

## Outbound allowlists

Requires the `luxor` CLI **1.7.0 or later**, or SDK **1.1.0 or later** for TypeScript, Python, or Go.

Set allowed domains or IPv4 CIDRs when you create a session to restrict its outbound destinations.
Session egress policies must be enabled for your workspace first.
If creation returns `failed_precondition` with `session egress policy is not enabled for this workspace`, contact support to request enablement.

This example allows access to PyPI and its package download host:

**TypeScript**
```typescript
const session = await sandbox.create({
  allowDomains: ["pypi.org", "*.pypi.org", "files.pythonhosted.org"],
});

console.log(session.egress.allowDomains, session.egress.allowCidrs);
```

**Python**
```python
from tenki import Sandbox

with Sandbox.create(
    allow_domains=["pypi.org", "*.pypi.org", "files.pythonhosted.org"],
) as sb:
    print(sb.egress.allow_domains, sb.egress.allow_cidrs)
```

`sb.info.egress` exposes the same policy.
`AsyncClient.create` and `AsyncSandbox.create` accept the same `allow_domains` and `allow_cidrs` arguments.

**Go**
```go
session, err := client.Create(ctx,
  tenkisandbox.WithAllowDomains("pypi.org", "*.pypi.org", "files.pythonhosted.org"),
)
if err != nil {
  log.Fatal(err)
}
defer session.Close(ctx)

policy := session.Egress()
fmt.Println(policy.AllowDomains, policy.AllowCIDRs)
```

**CLI**
```bash
luxor sandbox create \
  --allow-domain pypi.org \
  --allow-domain '*.pypi.org' \
  --allow-domain files.pythonhosted.org

luxor sandbox get --session <session-id> --json
```

Quote wildcard domains so your shell passes them unchanged.
The JSON response includes top-level `allow_domains` and `allow_cidrs` fields when the respective lists are non-empty.

### Policy rules

* Domains must be hostnames such as `pypi.org`, without a URL scheme, path, or port.
  A leading `*.` matches exactly one label: `*.example.com` matches `api.example.com`, but does not match `example.com` or `a.b.example.com`.
  A leading `**.` matches one or more labels, so `**.example.com` matches `api.example.com` and `a.b.example.com`, but not `example.com`.
  Use `**.` for hosts that sit several labels deep, such as `s3.us-east-1.amazonaws.com`, which `*.amazonaws.com` does not match.
  To allow the bare domain too, list it separately.
* CIDRs must be IPv4 prefixes, such as `203.0.113.10/32` for one address.
  IPv6, bare IP addresses without a prefix, and the default route `0.0.0.0/0` are rejected.
  A CIDR permits destinations in that range without requiring a matching domain, subject to workspace restrictions.
* The service accepts up to 256 unique domains and 64 unique CIDRs.
  It lowercases domains, removes trailing dots, masks CIDR host bits, and sorts and deduplicates both lists before returning the policy.
* Omitting both lists, or passing two empty lists through the SDKs, adds no session allowlist.
  An explicitly empty `egress` object in a raw API request is rejected.
  To block all outbound traffic, use `allowOutbound: false`, `allow_outbound=False`, `WithAllowOutbound(false)`, or `--allow-outbound=false`.
* The policy is fixed at create time; create a new session to change it.
  An allowlist cannot override disabled outbound access or widen workspace network permissions.
  Supplied allowlists still require valid input and workspace enablement even when outbound access is disabled.

A session that uses `**.` can only be placed on hosts that support it.
If no host in the region does yet, create fails at placement and names the missing capability; retry later or list explicit hostnames.
The `luxor` CLI **2.10.0 or later** prints a warning for `*.sb.tenki.sh` and `*.<region>.sb.tenki.sh`, which cannot match preview hostnames like `app--demo.us.sb.tenki.sh`, and suggests `**.sb.tenki.sh`.

The returned policy describes the session allowlist, not the combined workspace restrictions.
Empty returned lists mean no session allowlist; outbound access can still be disabled or restricted by the workspace.
The [SDK reference](https://luxor.ai/docs/sandbox/sdk.md#outbound-allowlist-options) lists the option and readback names for each language.

### HTTPS request rules and saved policies

Use HTTPS interception to restrict HTTP methods and paths as well as destinations.
Luxor Agent Cloud terminates HTTPS on port 443 at its egress proxy and checks each request before forwarding it.
The base image trusts our managed CA and sets `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, and `NODE_EXTRA_CA_CERTS`, so curl, git, pip, and npm work without extra setup.
Clients that pin the upstream certificate are incompatible.
HTTP rules require HTTPS interception and an allowed-domain list.

Create a named workspace policy once, then reuse it when creating sessions.
With the CLI, save the policy as JSON:

```json title="registries.json"
{
  "allow_domains": [
    "github.com",
    "api.github.com",
    "codeload.github.com",
    "raw.githubusercontent.com",
    "pypi.org",
    "pythonhosted.org",
    "files.pythonhosted.org",
    "npmjs.com",
    "npmjs.org",
    "www.npmjs.com",
    "www.npmjs.org",
    "registry.npmjs.org",
    "yarnpkg.com",
    "registry.yarnpkg.com",
    "crates.io",
    "index.crates.io",
    "static.crates.io",
    "proxy.golang.org",
    "sum.golang.org",
    "repo1.maven.org",
    "repo.maven.apache.org",
    "archive.ubuntu.com",
    "security.ubuntu.com"
  ],
  "intercept_https": true,
  "http_rules": [
    { "domains": ["*"], "methods": ["GET", "HEAD"] },
    {
      "domains": ["github.com"],
      "methods": ["POST"],
      "path_regex": "^/[^/]+/[^/]+(\\.git)?/git-upload-pack$"
    }
  ]
}
```

Then create it:

```bash
luxor sandbox egress-policies create --file registries.json registries
```

With the Go SDK, install it from `main` for the APIs below, then initialize an authenticated `client` and `ctx` as shown in the [SDK reference](https://luxor.ai/docs/sandbox/sdk.md):

```bash
go get github.com/LuxorLabs/tenki-sdk-go/sandbox@main
```

```go
_, err = client.CreateEgressPolicy(ctx, "registries", tenkisandbox.SessionEgressPolicy{
	AllowDomains: []string{
		"github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com",
		"pypi.org", "pythonhosted.org", "files.pythonhosted.org",
		"npmjs.com", "npmjs.org", "www.npmjs.com", "www.npmjs.org", "registry.npmjs.org",
		"yarnpkg.com", "registry.yarnpkg.com",
		"crates.io", "index.crates.io", "static.crates.io",
		"proxy.golang.org", "sum.golang.org", "repo1.maven.org", "repo.maven.apache.org",
		"archive.ubuntu.com", "security.ubuntu.com",
	},
	InterceptHTTPS: true,
	HTTPRules: []tenkisandbox.EgressHTTPRule{
		{Domains: []string{"*"}, Methods: []string{"GET", "HEAD"}},
		{
			Domains: []string{"github.com"}, Methods: []string{"POST"},
			PathRegex: `^/[^/]+/[^/]+(\.git)?/git-upload-pack$`,
		},
	},
})
if err != nil {
	panic(err)
}

s, err := client.Create(ctx, tenkisandbox.WithEgressPolicies("registries"))
if err != nil {
	panic(err)
}
defer s.Close(ctx)
fmt.Println(s.ID)
```

The SDK reference imports `github.com/LuxorLabs/tenki-sdk-go/sandbox` as `tenkisandbox`.
The policy allows `GET` and `HEAD` to the listed hosts, plus Git smart-HTTP `POST` requests to GitHub's `git-upload-pack` endpoint for clone and fetch operations.
Other requests must match a rule to pass; a rejected HTTP request returns `403` with the body `egress_http_rule_denied`.
This example does not permit Git pushes or package publishing.
It also does not cover GitHub release downloads, which redirect to `release-assets.githubusercontent.com`, or Git LFS, whose batch API is a `POST` to `/<owner>/<repo>.git/info/lfs/objects/batch`.

`Domains: []string{"*"}` matches only destinations already admitted by the domain allowlist and workspace restrictions.
It does not allow every internet host.
`PathRegex` uses RE2 syntax and matches the entire escaped request path, excluding the query string.
Rules are alternatives: a request passes if any rule matches its domain, method, and optional path constraint.
An empty `Methods` list matches every method, and omitting `HTTPRules` adds no method or path restriction.

Keep HTTPS certificate verification enabled in the guest.
Managed interception supports HTTP/1.1 upstreams on public IPv4 addresses; certificate pinning, client-certificate authentication, HTTP/2-only upstreams, WebSocket upgrades, and CONNECT tunnels are unsupported.
The registry list is a starting point: add the download or mirror hosts your dependencies actually use, and allow additional methods only when your workflow needs them.

A session pins the named policy's contents at create time.
Updating or deleting the saved policy does not change existing sessions; create a new session to use the updated policy.
The policy must belong to the workspace where you create the session.
Pin the saved policy when you create a session from the CLI:

```bash
luxor sandbox create --egress-policy registries
```

### Additional outbound TCP ports

With HTTPS interception enabled, public outbound TCP is limited to ports 80 and 443 unless you add ports explicitly.
Use `WithAllowedPorts` when a service on an allowed destination needs another TCP port:

```go
s, err := client.Create(ctx,
	tenkisandbox.WithEgressPolicies("registries"),
	tenkisandbox.WithAllowedPorts(8443),
)
if err != nil {
	panic(err)
}
defer s.Close(ctx)
```

Omit `WithAllowedPorts` to keep only TCP 80 and 443.
Additional ports still require an allowed destination, but their traffic bypasses HTTP inspection and the method/path rules above.
Adding port 8443 does not apply HTTPS interception to that port or expose an inbound sandbox port.

### Egress connection limit

When a sandbox has a domain allowlist, its outbound connections on ports 80 and 443 go through the sandbox egress proxy, which holds up to 1024 of them at once per sandbox.
Past that, new connections are refused with an error that names the limit:

* Plain HTTP on port 80 gets `HTTP/1.1 503` with `Retry-After: 1` and the body `egress connection limit reached: session_conn_cap, 1024 per sandbox`.
* HTTPS that Luxor Agent Cloud intercepts completes the handshake, then every request gets the same 503.
* Other TLS connections get a fatal `internal_error` alert, which clients report as an internal error such as `TLSV1_ALERT_INTERNAL_ERROR`.
  This used to show as `unrecognized name`, which looked like an allowlist problem.

It is a capacity limit, not a policy decision.
Reuse connections, or close idle ones, and retry after a moment.

### Link-local addresses

A sandbox cannot reach link-local addresses (`169.254.0.0/16`), such as the cloud metadata address `169.254.169.254`.
This applies to every sandbox, with or without an allowlist.
TCP connections are refused at once instead of timing out, other traffic gets an ICMP error, and the egress proxy denies them too.
The platform's own address, `169.254.100.1`, stays reachable, so features that depend on it, such as the CI cache, keep working.

## Port exposure and networking

Each session has independent inbound and outbound settings. Every SDK and the CLI request both at create
time, so both are enabled by default:

* `allow_outbound` lets the guest make outbound network calls, subject to workspace restrictions and any [session allowlist](#outbound-allowlists)
* `allow_inbound` enables inbound exposure workflows; with `allow_inbound=false`, port exposure is rejected

Both are create-time settings; you cannot toggle them afterwards. Each tool reports what a session was
created with:

| Setting    | TypeScript                | Python                          | Go                        | CLI                                        |
| ---------- | ------------------------- | ------------------------------- | ------------------------- | ------------------------------------------ |
| `inbound`  | `session.inboundEnabled`  | `sandbox.info.inbound_enabled`  | `session.InboundEnabled`  | `luxor sandbox get --session <session-id>` |
| `outbound` | `session.outboundEnabled` | `sandbox.info.outbound_enabled` | `session.OutboundEnabled` | `luxor sandbox get --session <session-id>` |

**Python**
```python
preview = sb.expose_port(3000, ttl=3600)  # ttl in seconds
print(preview.url)

ports = sb.list_exposed_ports()
sb.unexpose_port(3000)
```

**TypeScript**
```typescript
const port = await session.exposePort(3000, { ttlMs: 3600_000 });
console.log(port.previewUrl);
```

**Go**
```go
port, err := session.ExposePort(ctx, 3000)
ports, err := session.ListExposedPorts(ctx)
err = session.UnexposePort(ctx, 3000)
```

**CLI**
```bash
luxor sandbox preview-url create --slug my-app --session <session-id> --port 3000 --ttl 1h
luxor sandbox preview-url list --session <session-id>
luxor sandbox preview-url delete <preview-url-id>
```

The CLI's `expose`, `ports`, and `unexpose` commands still work but are deprecated; see [`preview-url`](https://luxor.ai/docs/sandbox/cli.md#preview-url).

When you expose a long-running server you started with `exec`, background it and detach its streams (`>/home/tenki/server.log 2>&1 </dev/null &`).
`exec` streams the command's output until it closes, so a server that keeps the output stream open leaves `exec` waiting forever.

Use the `previewUrl` returned by each expose call rather than constructing hostnames yourself; the host pattern is not a stable contract.

For Tailscale-attached sessions, a preview URL and a tailnet port are independent inbound paths; see [Preview URLs and tailnet access](https://luxor.ai/docs/sandbox/tailscale.md#preview-urls-and-tailnet-access).

Every exposure is a preview URL in your workspace, and each workspace has a limit on how many it can hold.
Terminating a session deletes the preview URLs bound to it, and a preview URL with a TTL is deleted when the TTL passes.
Unexposing a port, from an SDK or with `luxor sandbox preview-url unbind`, only takes the URL offline.
It stays in the workspace and counts toward the limit until you delete it with the CLI's `luxor sandbox preview-url delete <preview-url-id>`, `client.previewUrls.delete(id)` in TypeScript, `client.preview_urls.delete(id)` in Python, or `client.DeletePreviewURL` in Go.
If you are about to terminate the session, skip unexposing and let terminate clean up.

### Preview capacity errors

When a preview URL request hits a capacity limit at the edge, the response is `503` with a `Retry-After: 1` header and a body that names the limit:

```text
proxy capacity exhausted: requests_per_route
```

The name after the colon is one of `websocket_per_route`, `ssh`, `requests_per_route`, `requests_per_backend`, `requests_global`, `backend_pools`, `dials`, or `tls_handshakes`.
Retry after a moment, and include the name if you contact support.
Running out of dial or handshake capacity used to return `502 bad gateway`; it now returns this `503`.

A preview port accepts up to 256 concurrent HTTP/1 connections, so about that many Server-Sent Events streams can stay open at once.
Earlier the limit was 32 and the extra streams hung.
Requests over the limit now fail at once with a `503`.
The edge allows the same 256 concurrent requests per preview URL, so you usually see `proxy capacity exhausted: requests_per_route`; the sandbox's host answers `preview connection limit reached: per_port`.

### Keep a preview URL across sessions

To hand out one URL that keeps working as you replace sessions, create a preview URL with a slug and move it from session to session.
Unbind it before you terminate the old session; otherwise terminate deletes it.

```bash
luxor sandbox preview-url create --slug my-app --session <session-id> --port 3000

# Before you terminate the session
luxor sandbox preview-url unbind <preview-url-id>
luxor sandbox terminate --session <session-id>

# On the next session
luxor sandbox preview-url bind --session <new-session-id> --port 3000 <preview-url-id>
```

A preview URL bound to one session must be unbound before you bind it to another.
Binding can change the hostname, for example when an unbound preview URL is first bound to a session, so use the `preview_url` printed by the latest `create` or `bind`.
The SDK clients have the same operations: `create`, `bind`, `unbind`, `list`, `get`, and `delete` on `client.previewUrls` in TypeScript and `client.preview_urls` in Python, and `CreatePreviewURL`, `BindPreviewURL`, `UnbindPreviewURL`, `ListPreviewURLs`, `GetPreviewURL`, and `DeletePreviewURL` in Go.

### Named exposures

By default an exposure gets a generated hostname that changes from session to session. Pass a slug to ask for a named exposure instead, which is what you want when the URL has to be written into something that cannot be updated per session: an OAuth callback, a webhook registration, a config file baked into an image.

**TypeScript**
```typescript
const port = await session.exposePort(3000, { slug: "my-app", ttlMs: 3600_000 });
console.log(port.previewUrl, port.slug);
```

**Python**
```python
preview = sb.expose_port(3000, slug="my-app", ttl=3600)
print(preview.url, preview.slug)
```

**Go**
```go
port, err := session.ExposePort(ctx, 3000, tenkisandbox.WithSlug("my-app"))
```

A slug names the exposure; it does not by itself decide how the URL is served. Some exposures are served through a workspace wildcard domain, and the returned exposure reports that separately, along with the readiness of the backing certificate:

| Field                | TypeScript             | Python                   | Go                     |
| -------------------- | ---------------------- | ------------------------ | ---------------------- |
| Requested slug       | `slug`                 | `slug`                   | `Slug`                 |
| Wildcard scheme used | `wildcard`             | `wildcard`               | `Wildcard`             |
| Readiness            | `wildcardStatus`       | `wildcard_status`        | `WildcardStatus`       |
| Failure reason       | `wildcardStatusReason` | `wildcard_status_reason` | `WildcardStatusReason` |

Readiness is one of `UNSPECIFIED`, `PENDING`, `READY`, `FAILED`, or `DISABLED`, and is only meaningful when the wildcard field is true. A wildcard-served preview URL comes back from `expose` immediately, but it does not serve traffic until its workspace domain reaches `READY`. Check readiness before handing the URL to a caller that fails closed on an error response, and read the reason field when it is `FAILED`.

Even with a slug, use the returned preview URL rather than assembling a hostname from the slug yourself.

### Workspace preview slug

Wildcard-served exposures live under a preview slug reserved at the workspace level. Team-plan workspaces can reserve one slug (one per workspace) from **Settings**, using the slug input in the first card. It is shared across every session in the workspace, which is what keeps named exposures stable from one session to the next.

Once reserved, named exposures are served under that slug. A workspace slug of `acme-studio` produces preview URLs of the form `https://<exposure>--acme-studio.sb.tenki.sh/`, for example `https://landing-preview--acme-studio.sb.tenki.sh/`. Reserving a slug is a Team-plan feature; Starter workspaces get generated per-session hostnames instead. As above, treat the example as illustrative and hand callers the returned preview URL rather than assembling one from the slug yourself.

## Unix socket bridging (dial)

`dial` opens a byte-stream connection from your local code to a Unix socket inside the guest. It is the private counterpart to port exposure: nothing is published on the internet — the connection rides the session's authenticated data plane. Use it to talk to guest services that listen on a socket rather than a TCP port (a language server, an agent's control socket, `docker.sock`).

`dial` is SDK-only; there is no CLI equivalent. The optional connect timeout bounds how long the guest waits for the socket to accept.

**TypeScript**
```typescript
const conn = await session.dial("/home/tenki/app.sock", { connectTimeoutMs: 5_000 });

const writer = conn.writable.getWriter();
await writer.write(new TextEncoder().encode("PING\n"));
await writer.close();

for await (const chunk of conn.readable) {
  process.stdout.write(chunk);
}
```

`dial` returns `{ readable, writable }` web streams. Closing the writable half-closes the connection; the readable ends when the guest side closes.

**Python**
```python
conn = sb.dial("/home/tenki/app.sock", connect_timeout=5)
conn.write(b"PING\n")
print(conn.read(4096))
conn.close()
```

`dial` returns a raw IO connection (an `io.RawIOBase`), the same shape as `sb.ssh()`.

**Go**
```go
conn, err := session.Dial(ctx, "/home/tenki/app.sock", tenkisandbox.DialOptions{ConnectTimeout: 5 * time.Second})
if err != nil {
  log.Fatal(err)
}
defer conn.Close()

fmt.Fprint(conn, "PING\n")
buf := make([]byte, 4096)
n, _ := conn.Read(buf)
fmt.Print(string(buf[:n]))
```

`Dial` returns a `net.Conn`, so it plugs into anything that speaks the interface — for example an `http.Transport` whose `DialContext` returns it, to talk HTTP over the guest socket.

## SSH access

Connect to a session over SSH. The CLI gives you an interactive shell, managed local config, and key management; the SDKs expose a raw byte-stream transport for wiring into your own SSH tooling. (Set keys at create time with the `sshAuthorizedKeys` option in the table above.)

**TypeScript**
Raw byte-stream transport for your own SSH tooling, plus replacing the authorized keys on a running session:

```typescript
const conn = await session.ssh();
await conn.write(new TextEncoder().encode("ls -la\n"));
const chunk = await conn.read(); // Uint8Array | null
if (chunk) process.stdout.write(chunk);
conn.close();

// Replace the authorized keys
await session.updateSshAuthorizedKeys(["ssh-ed25519 AAAA..."]);
```

**Python**
Raw byte-stream transport (an `io.RawIOBase`), plus replacing the authorized keys on a running session:

```python
conn = sb.ssh()
conn.write(b"ls -la\n")
print(conn.recv(4096).decode())
conn.close()

# Replace the authorized keys
sb.update_ssh_authorized_keys(["ssh-ed25519 AAAA..."])
```

**Go**
Raw byte-stream transport for your own SSH tooling, plus replacing the authorized keys on a running session:

```go
conn, err := session.SSH(ctx)
defer conn.Close()

// Replace the authorized keys
err = session.UpdateSSHAuthorizedKeys(ctx, []string{"ssh-ed25519 AAAA..."})
```

**CLI**
Open an interactive shell:

```bash
luxor sandbox ssh --session <session-id>
```

Useful flags: `--user` (default `tenki`), `--identity-file`, `--batch-mode`, `--connect-timeout`, `--strict-host-key-checking`. Pass standard SSH arguments after the session ID:

```bash
luxor sandbox ssh <session-id> -L 8080:127.0.0.1:8080
```

Install a managed entry in your local SSH config so you can use friendly aliases:

```bash
luxor sandbox ssh config install
luxor sandbox ssh config status
luxor sandbox ssh config uninstall
ssh sbx-<session-uuid>
```

Replace the authorized keys on a running session:

```bash
luxor sandbox ssh-keys set --session <session-id> --keys-file ~/.ssh/authorized_keys
```

## Session metadata

Metadata tags a session with arbitrary string key-value pairs (`metadata` in the SDKs, `--metadata key=value` on the CLI, both shown above). Use it to filter sessions in dashboards, attribute billing, or tie a session to an upstream job ID. Metadata is opaque to the service; it is for your bookkeeping.