# Sessions

> Run commands, stream stdin, send signals, transfer files, and end an interactive sandbox session.

This is the Markdown of https://docs.dvm.run/guides/sessions/. Every page of the dvm.run docs is served as Markdown at its address plus `.md`; the list of pages is https://docs.dvm.run/llms.txt.

A sandbox created without `command` or `entrypoint` is a session: an interactive sandbox that accepts commands and file operations until you end it. Its first process is the session server instead of the image’s default program. Pass a command or entrypoint to run a [one-program sandbox](/guides/programs/) instead.

## Run a command

Call `run` to start a command, send its input, and wait for it to finish.

* Python

  `python/examples/sessions.py`

  ```python
  result = sandbox.run(
      'echo "$GREETING from $(pwd) as $(whoami)"; cat',
      env={"GREETING": "hello"},
      cwd="/tmp",
      user="nobody",
      stdin=b"and this came in on stdin\n",
  )
  print(result.exit_code)
  print(result.stdout.decode(), end="")
  ```

* TypeScript

  `js/examples/sessions.ts`

  ```ts
  const result = await sandbox.run('echo "$GREETING from $(pwd) as $(whoami)"; cat', {
    env: { GREETING: "hello" },
    cwd: "/tmp",
    user: "nobody",
    stdin: bytes("and this came in on stdin\n"),
  });
  console.log(result.exitCode);
  console.log(text(result.stdout));
  ```

* Rust

  `rust/dvm-run/examples/sessions.rs`

  ```rust
  let result = sandbox
      .run(r#"echo "$GREETING from $(pwd) as $(whoami)"; cat"#)
      .env("GREETING", "hello")
      .cwd("/tmp")
      .user("nobody")
      .stdin(b"and this came in on stdin\n")
      .await?;
  println!("{}", result.exit_code);
  print!("{}", String::from_utf8_lossy(&result.stdout));
  ```

- **Shell vs. argv.** A string runs as a script via `/bin/bash -lc` if the image has `/bin/bash`, or `/bin/sh -c` otherwise. A list runs directly as argv with no shell, finding the executable on `PATH`.
- **Result.** Returns the exit code plus stdout and stderr as bytes. A nonzero exit code is a result, not an error. A signal-killed command exits with `128 + signal`, a missing executable exits 127, and a non-runnable one exits 126 with the reason on stderr.
- **Environment and directory.** Commands inherit the sandbox’s environment, with `env` overlaid. Without `cwd`, they run in the image’s working directory.
- **User.** Commands run as root unless `user` sets another (same format as `docker exec --user`: name or UID, optionally `:group` or `:gid`, from `/etc/passwd` and `/etc/group`). An unknown user still starts the command, which writes the error to stderr and exits 126.
- **Input.** `stdin` is sent and closed; without it, input is empty.

Multiple commands can run concurrently in one session.

## Start and interact with a command

Call `start` to launch a command and get a handle once it starts. Without `stdin`, input stays open so you can write and close it later.

* Python

  `python/examples/sessions.py`

  ```python
  cat = sandbox.start(["cat"])
  cat.write_stdin(b"one ")
  cat.write_stdin(b"two\n")
  cat.close_stdin()
  print(cat.wait().stdout)

  sleeper = sandbox.start(["sleep", "600"])
  sleeper.signal(15)
  print(sleeper.wait().exit_code)
  ```

* TypeScript

  `js/examples/sessions.ts`

  ```ts
  const cat = await sandbox.start(["cat"]);
  await cat.writeStdin(bytes("one "));
  await cat.writeStdin(bytes("two\n"));
  await cat.closeStdin();
  console.log(text((await cat.wait()).stdout));

  const sleeper = await sandbox.start(["sleep", "600"]);
  await sleeper.signal(15);
  console.log((await sleeper.wait()).exitCode);
  ```

* Rust

  `rust/dvm-run/examples/sessions.rs`

  ```rust
  let cat = sandbox.start(["cat"]).await?;
  cat.write_stdin(b"one ").await?;
  cat.write_stdin(b"two\n").await?;
  cat.close_stdin().await?;
  println!("{:?}", String::from_utf8_lossy(&cat.wait().await?.stdout));

  let sleeper = sandbox.start(["sleep", "600"]).await?;
  sleeper.signal(15).await?;
  println!("{}", sleeper.wait().await?.exit_code);
  ```

- `write_stdin` queues bytes without waiting for the command to read them.
- `signal(n)` sends signal `n` (1 to 64) to the command’s process group. The server sends no response; check the exit code.
- `wait` returns the same result as `run`. Output is collected as it arrives, so a command that writes a lot holds it all in memory until then.

## Read and write files

Call `write_file` to write a whole file and `read_file` to read one, as bytes.

* Python

  `python/examples/sessions.py`

  ```python
  sandbox.write_file("/tmp/hello.sh", b"#!/bin/sh\necho hello from a file\n", mode=0o755)
  print(sandbox.run(["/tmp/hello.sh"]).stdout)
  print(sandbox.read_file("/etc/os-release").decode().splitlines()[0])
  ```

* TypeScript

  `js/examples/sessions.ts`

  ```ts
  await sandbox.writeFile("/tmp/hello.sh", bytes("#!/bin/sh\necho hello from a file\n"), { mode: 0o755 });
  console.log(text((await sandbox.run(["/tmp/hello.sh"])).stdout));
  console.log(text(await sandbox.readFile("/etc/os-release")).split("\n")[0]);
  ```

* Rust

  `rust/dvm-run/examples/sessions.rs`

  ```rust
  sandbox
      .write_file("/tmp/hello.sh", b"#!/bin/sh\necho hello from a file\n")
      .mode(0o755)
      .await?;
  let hello = sandbox.run(["/tmp/hello.sh"]).await?;
  println!("{:?}", String::from_utf8_lossy(&hello.stdout));
  let release = sandbox.read_file("/etc/os-release").await?;
  println!(
      "{}",
      String::from_utf8_lossy(&release)
          .lines()
          .next()
          .unwrap_or("")
  );
  ```

- New files get mode `0o644` minus the umask unless you pass a mode; existing files keep their mode.
- The parent directory must exist; none is created.
- Writes are not atomic; a failed write can leave a partial file.
- `read_file` reads regular files only; directories and missing files fail with the reason.
- Relative paths start from the image’s working directory.

To read files after exit, seek to a point (a recorded moment in the run) ([Inspecting a finished run](/guides/inspect/)).

## End the session

Call `end` to close session input and wait for exit. Running commands are killed. Returns the sandbox’s exit code (0 once the session server stops).

* Python

  `python/examples/sessions.py`

  ```python
  print(sandbox.end())
  ```

* TypeScript

  `js/examples/sessions.ts`

  ```ts
  console.log(await sandbox.end());
  ```

* Rust

  `rust/dvm-run/examples/sessions.rs`

  ```rust
  println!("{}", sandbox.end().await?);
  ```

Resume a paused sandbox before ending it, or stop it instead. A `with` block, `await using`, or `scope` handles cleanup automatically ([Python](/sdks/python/), [TypeScript](/sdks/typescript/), [Rust](/sdks/rust/)).

Only sandboxes that exited (as `end` makes them) can be inspected. Stopped sandboxes cannot.

Caution

A session’s input becomes part of its recording. Every command, its arguments, environment, stdin, and every file you write are stored in the recording and readable by anyone who can inspect it.

## Pause, resume, stop

These controls work on any sandbox; see [One-program sandboxes](/guides/programs/).

* `pause` freezes the sandbox; `resume` continues it.
* `stop` terminates it immediately. Stopped sandboxes cannot be inspected.
* `state` returns `queued`, `running`, or `paused`, then `exited` (with exit code), `stopped`, or `failed` (with reason).
