Skip to content
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ As an AI agent operating via non-interactive shell tools (`run_shell_command`),
- Specially crafted mock scripts that simulate timeouts or API calls.
- **I CANNOT Run (Requires User Assistance):**
- **`colab auth`**: This command relies on the traditional Gcloud fallback `input_request` (via `USE_AUTH_EPHEM='0'`), which prompts the user via Python's `input()` to click a URL, sign in, and paste back an authorization code. My shell tool will hang indefinitely on this `input()`.
- **`colab drivemount`**: This command prompts the user via `sys.stdin.readline()` (specifically querying `/dev/tty` to ensure input is captured) to press `Enter` after granting OAuth consent in the browser. My shell tool will timeout/hang waiting for `Enter`.
- **`colab drivemount`**: This command prompts the user to press `Enter` after granting OAuth consent in the browser. The prompt reads the controlling terminal (`/dev/tty` on POSIX, `CONIN$` on Windows), falling back to stdin. My shell tool will timeout/hang waiting for `Enter`. The consent URL is also opened in a GUI browser when one is available.
- **Interactive (TTY) `colab repl` / `colab console`**: When stdin is a real terminal these commands drop into interactive raw-TTY modes that require real-time keystroke streaming. My shell tools cannot support this. (Piped stdin is fine — see above.)

Whenever working on interactive commands, I must build the core logic, write mock tests, and explicitly ask the user to run the live test in their terminal to verify success.
23 changes: 19 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Designed to support seamless developer productivity, headless automation, and AI
[Demo](https://github.com/user-attachments/assets/656226a9-af13-4fdb-8eda-d7de747336a2)

> [!NOTE]
> **Platform support:** the Colab CLI currently supports **Linux and macOS** only. Windows is not supported at this time.
> **Platform support:** Linux, macOS, and Windows (PowerShell and cmd.exe). Interactive `colab console` uses the Windows console API on Windows (raw keystrokes and ANSI color). `colab ssh --proxy-mode` reads stdin with a blocking read so it works as an OpenSSH ProxyCommand under Windows OpenSSH.

> [!TIP]
> Looking for in-notebook, interactive agent-assisted coding instead of a terminal workflow? See the [Colab MCP Server](https://github.com/googlecolab/colab-mcp).
Expand Down Expand Up @@ -79,7 +79,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
| Command | Description |
| --- | --- |
| `colab run [--gpu GPU] [--tpu TPU] [--high-mem] [--keep] SCRIPT [ARGS...]` | Run a local script on a fresh VM, forwarding arguments, then release it |
| `colab exec [-s NAME] [-f FILE] [--output-image PATH]` | Execute Python code from stdin, a local `.py` file, or a `.ipynb` notebook |
| `colab exec [-s NAME] [-f FILE] [--output-image PATH] [--cells SPEC] [--stop-on-error] [--check \| --check-only]` | Execute Python code from stdin, a local `.py` file, or a `.ipynb` notebook (exits 1 if the code or any cell raised an error) |
| `colab repl [-s NAME] [--output-image PATH]` | Start an interactive Python REPL on the VM (exits cleanly on piped EOF) |
| `colab console [-s NAME]` | Connect to a raw interactive TTY shell (tmux) on the remote VM |
| `colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem]` | Open an SSH shell to the runtime over WebSocket, or act as an OpenSSH `ProxyCommand` bridge for IDE remote-dev |
Expand All @@ -97,7 +97,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
| Command | Description |
| --- | --- |
| `colab auth [-s NAME]` | Authenticate the VM for GCP services (BigQuery, GCS, etc.) |
| `colab drivemount [-s NAME] [PATH]` | Mount Google Drive on the VM (default: `/content/drive`) |
| `colab drivemount [-s NAME] [--authuser N] [PATH]` | Mount Google Drive on the VM (default: `/content/drive`) |
| `colab install [-s NAME] [-r FILE \| PKG...]` | Install packages on the VM using `uv` (falls back to `pip`) |
| `colab log [-s NAME] [-n N] [-o FILE]` | View or export session history (`.ipynb`, `.md`, `.txt`, `.jsonl`) |
| `colab usage` | Show account compute-unit usage rate and balance |
Expand Down Expand Up @@ -139,12 +139,27 @@ colab log -s analysis -o execution_log.md
colab stop -s analysis
```

### Choosing Notebook Cells, and Checking Before Running

`colab exec` runs every code cell top to bottom by default. A cell that raises an error does not stop the run, but the command exits with code 1 and lists the failed cells. You can change this with the following options:

* `--cells SPEC`: run only some cells, in the order given. `SPEC` is a comma-separated list of code-cell numbers (counted from 1, without markdown cells), ranges such as `2-5`, `#@title` values or cell ids. An entry that looks like a number or range is always read as one, so select a cell whose title or id is numeric by its number.
* `--stop-on-error`: stop at the first failing cell.
* `--check`: check the selected cells locally before anything runs: the notebook structure, `--cells`, and Python syntax (IPython `!cmd`, `%magic`, `x = !cmd` and top-level `await` are accepted; `%%` cell magics are skipped). If a check fails, nothing runs.
* `--check-only`: run the same checks and print which cells would run, without a session.

```bash
colab exec -f report.ipynb --check-only --cells "Setup,4-6"
colab exec -s analysis -f report.ipynb --check --cells "Setup,4-6" --stop-on-error
```

---

## Usage Notes

* **Machine shape:** Use `--high-mem` with `colab new`, `colab run`, or `colab ssh` (when auto-creating a runtime) to request a high-RAM machine shape. Requires Colab Pro or Pro+ entitlement for supported accelerators (CPU, T4, A100, etc.). L4 and TPU runtimes ignore this flag because they only offer one shape. Machine shape is shown in `colab sessions` and `colab status`.
* **TTY Requirements:** The interactive commands `repl` and `console` require a local TTY. When running inside automated scripts or pipelines, make sure to pipe stdin (e.g., `echo "print(1)" | colab repl`) to trigger non-interactive execution modes.
* **TTY Requirements:** The interactive commands `repl` and `console` require a local TTY. When running inside automated scripts or pipelines, make sure to pipe stdin (e.g., `echo "print(1)" | colab repl`) to trigger non-interactive execution modes. On Windows, `colab console` switches the console out of line-editing mode so arrow keys and Ctrl-C reach the remote shell; colors need virtual-terminal processing, which the CLI turns on for cmd.exe and Windows PowerShell.
* **Drive mount and multiple Google accounts:** `colab drivemount` prints a consent URL (and opens it in the browser when it can) and waits up to 10 minutes. On the account chooser, select the same account the CLI authenticated as (`colab whoami` / the `login_hint` in the URL). A browser that is signed into several accounts otherwise attributes the Drive session to the active account, and Colab rejects the mount with HTTP 400. `--authuser N` appends that index to the consent URL when the chooser keeps opening the wrong account.
* **Transparent Code Execution:** When calling `colab exec -f file.py`, the CLI reads the file locally and transmits its content to the remote kernel. You do not need to manually upload files before execution.
* **Storage & State Paths:** Session tokens and metadata are stored at `~/.config/colab-cli/sessions.json`. Global CLI settings are located at `~/.config/colab-cli/settings.json`. These can be customized or isolated via the global `--config` flag.

Expand Down
12 changes: 10 additions & 2 deletions docs/02_execution_and_interactive.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
---
log:
2026-10-07: `colab exec` notebook control and exit codes. `--cells SPEC` runs only the selected code cells, in the given order. SPEC accepts code-cell numbers (counted from 1, markdown cells not counted), ranges, `#@title` values and cell ids. Entries that look like numbers or ranges are always read as such: nbformat's random cell ids are sometimes all digits, so those cells are selected by number. `--stop-on-error` stops at the first cell with an error output. Without it every cell still runs, as before. `exec` now exits with code 1 when the code, or any notebook cell, produced an error output; it used to exit 0, so scripts could not tell. `--check` runs a local pre-flight (`colab_cli/notebook.py`) before anything is sent: notebook validation, `--cells` resolution, and a syntax check of each selected cell, compiled with `PyCF_ALLOW_TOP_LEVEL_AWAIT`. IPython `!cmd`, `%magic` and `x = !cmd` lines become `pass`/`None` with their indentation kept, so line numbers match, and `%%` cell magics are skipped. If any check fails, nothing runs and exec exits 2. `--check-only` does the same checks and prints the plan without resolving a session. A missing file or an unreadable notebook now prints one line instead of a traceback.

2026-10-07: Piped `colab console` no longer cuts off its own output on a fresh runtime, and no longer leaks terminal replies. The EOF handler used to close the websocket a fixed 0.5s (`PIPED_EOF_GRACE_SECONDS`) after sending `exit\n`. On a freshly started runtime the first attach often needs 0.5-1s before the shell answers, so the client closed first and nothing came back (2 of 3 fresh-VM runs, traced with timestamps). The backend closes the websocket itself once bash and tmux exit, after the last output, so the handler now waits for that close (`_closed`, set by `on_close`). It only closes from the client side after `PIPED_EOF_CLOSE_TIMEOUT_SECONDS` (30s), as a fallback for a backend that never closes. With a 5s wait, 3 of 3 fresh-VM runs got their output and the backend closed every time, 0.1-1s after `exit`. Separately, tmux sends terminal queries when it attaches (DA1, DA2, XTVERSION, OSC 10/11). With piped stdin the local terminal's replies can never reach the remote side and were left in the terminal's input for the next command. When stdin is not a TTY, `TerminalQueryFilter` now drops those queries from the output.

2026-10-07: Windows console support for `colab console`. cmd.exe and PowerShell have no `termios`, `/dev/tty`, or `SIGWINCH`, so interactive console used to stay line-buffered (arrow keys never left the local line editor, Ctrl-C killed the CLI, ANSI from the remote PTY rendered as garbage in conhost). `console.py` now enables virtual-terminal processing and UTF-8, switches the input handle to raw mode via `SetConsoleMode`, reads keys with `msvcrt.getwch`, translates scan codes to ANSI, and polls the window size. POSIX raw mode and piped stdin are unchanged. `colab ssh --proxy-mode` reads stdin with a blocking `os.read` (Windows `select()` cannot wait on a pipe) and quotes the ProxyCommand with the MSVCRT rules, because OpenSSH for Windows passes it to `CreateProcess` (not `cmd.exe`, as this entry first said).

2026-05-07: Fixed `colab console` piped-stdin handling. Previously a piped invocation (e.g. `echo 'cmd' | colab console -s s`) sent the command and then hung indefinitely because the previous EOF handler emitted a bare `\x04` (Ctrl-D), which the remote `tmux`-wrapped bash treats as a literal character rather than a session terminator. The new handler sends `exit\n` (which bash actually exits on) and then closes the websocket from the client side after a short grace period (`PIPED_EOF_GRACE_SECONDS = 0.5s`) so any tail output (bash `logout`, tmux `[exited]`) makes it back to the user. TTY mode is unchanged: real-terminal EOF is left to the remote shell. Verified live: `echo 'echo HELLO' | colab console -s s` now exits in ~1.2s instead of hanging.

2026-05-07: Fixed `print_kitty` (used by `colab exec --output-image` and any image-producing exec) to no-op when `sys.stdout.isatty()` is false. The Kitty Graphics Protocol escape sequence is meaningless when stdout is a file or pipe and was visually corrupting captured output (a multi-KB base64 PNG blob would land in log files, grep targets, or showboat captures). Image bytes are still saved to disk via `handle_image`'s file-write path; only the inline-render attempt is suppressed.
Expand Down Expand Up @@ -33,8 +39,8 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel
### 3. Console (`colab console`)
- **Implementation**: Connects directly to the backend terminal endpoint (`/colab/tty`) via WebSockets using `websocket-client`.
- **Interactive**: Bypasses the Jupyter kernel entirely to provide a raw, PTY-backed bash session on the Colab VM.
- **Terminal Management**: Configures `sys.stdin` to raw mode using `termios` and `tty`, passing single characters to the socket and writing raw ANSI escape sequences directly to `sys.stdout.buffer`. Hooks into `SIGWINCH` to communicate local terminal dimensions (`cols`/`rows`) to the remote bash environment so output rendering works perfectly during resizing.
- **Piped stdin**: Detected via `sys.stdin.isatty()`. When piped, the input characters are forwarded one at a time to the remote pty, and on EOF the client sends `exit\n` and then closes the websocket itself after `PIPED_EOF_GRACE_SECONDS` (0.5s) so the user's shell goodbye text drains back. The remote `/colab/tty` endpoint wraps bash in tmux, which intercepts a bare `\x04` as a literal character — that is why we send `exit\n` rather than Ctrl-D.
- **Terminal Management**: On Linux and macOS, configures `sys.stdin` to raw mode using `termios` and `tty`, passing single characters to the socket and writing raw ANSI escape sequences directly to `sys.stdout.buffer`. Hooks into `SIGWINCH` to communicate local terminal dimensions (`cols`/`rows`) to the remote bash environment so output rendering works perfectly during resizing. On Windows (cmd.exe and PowerShell), `termios` does not exist: the CLI enables `ENABLE_VIRTUAL_TERMINAL_PROCESSING` and UTF-8 on the console, sets raw input mode with `SetConsoleMode` (so the local line editor and Ctrl-C handler get out of the way), reads keys with `msvcrt.getwch`, maps scan codes to ANSI sequences, and polls `os.get_terminal_size` because there is no `SIGWINCH`.
- **Piped stdin**: Detected via `sys.stdin.isatty()`. When piped, the input characters are forwarded one at a time to the remote pty, and on EOF the client sends `exit\n` and waits for the backend to close the websocket. The backend does that once bash and tmux exit, after the last output, so the user's shell goodbye text drains back. The client only closes the websocket itself if that has not happened after `PIPED_EOF_CLOSE_TIMEOUT_SECONDS` (30s), so a piped command running longer than that is cut off. Terminal queries from tmux (DA1/DA2, XTVERSION, OSC colour queries) are dropped from the output in this mode, because the terminal's replies could not reach the remote side. The remote `/colab/tty` endpoint wraps bash in tmux, which intercepts a bare `\x04` as a literal character — that is why we send `exit\n` rather than Ctrl-D.

## Implementation Details
- **Kernel Management**: `ColabRuntime` (from `colab-agent`) already handles message signing and message types.
Expand All @@ -54,4 +60,6 @@ TDD is mandatory for all execution features.
- **Test Case**: Verify large piped inputs are handled without buffer overflow or truncation.
- **Test Case**: `colab console` with piped stdin sends `exit\n` and calls `ws.close()` on EOF (regression: previously sent `\x04` only and hung).
- **Test Case**: `colab console` in TTY mode does not synthesize an exit on EOF (the user owns the session lifecycle).
- **Test Case**: With `termios` unavailable and `os.name == "nt"`, `connect_console` enters the Windows raw-console context manager and does not call `tty.setraw`.
- **Test Case**: Windows key translation maps scan codes to ANSI and the stdin thread forwards those characters one at a time.
- **Test Case**: `print_kitty` is a no-op when `sys.stdout.isatty()` is false (regression: previously emitted ANSI/base64 into pipes and files).
Loading
Loading