GoogleColabClient 0.1.0

dotnet add package GoogleColabClient --version 0.1.0
                    
NuGet\Install-Package GoogleColabClient -Version 0.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GoogleColabClient" Version="0.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GoogleColabClient" Version="0.1.0" />
                    
Directory.Packages.props
<PackageReference Include="GoogleColabClient" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GoogleColabClient --version 0.1.0
                    
#r "nuget: GoogleColabClient, 0.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GoogleColabClient@0.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GoogleColabClient&version=0.1.0
                    
Install as a Cake Addin
#tool nuget:?package=GoogleColabClient&version=0.1.0
                    
Install as a Cake Tool

GoogleColabClient

A .NET 10 client for Google Colab, a strict port of google-colab-cli 0.7.5 (Python, Apache-2.0).

Notice: this is an UNOFFICIAL client. This project is not affiliated with, endorsed by, or sponsored by Google LLC. Google and "Colab" are trademarks of their owners. Use it at your own risk and in compliance with the Google Colab terms of service.

What it is

A library (not a console application) that lets other .NET applications:

  • allocate and release Colab runtimes (CPU, GPU, TPU, high memory);
  • run code on the remote kernel and receive its output;
  • run a Python script on a short-lived VM;
  • manage remote files, local sessions, SSH and account utilities.

The library does not print, does not read the console and does not terminate the process: its methods return models or throw typed exceptions.

The netcolab project is only a standalone test tool that uses the public API.

Installation

dotnet add package GoogleColabClient

The package includes a .snupkg symbol package for debugging.

Profiles and several clients at once

The original stores its files in fixed user paths. Here, each client works with a profile (ColabProfile):

  • a validated id ([A-Za-z0-9._-], 1 to 64 characters, no ..);
  • a base directory of your choice (default: ~/.config/colab-cli).

The files of each profile live under <base>/<id>/:

File Content
token.json OAuth token (same format as the original).
oauth_config.json Optional OAuth client of your own application; without it, the library's default client is used.
sessions.json Local sessions.
settings.json Settings.
history/ Event history.

This lets you keep several Colab clients open at the same time, each with its own credentials, without sharing files or global state:

using GoogleColabCli.State;
using GoogleColabCli.Sessions;

var accountA = new ColabProfile("account-a", @"D:\secret\colab");
var accountB = new ColabProfile("account-b", @"D:\secret\colab");

Authentication

Sign-in works without configuration. The library embeds the public OAuth client of the original google-colab-cli (oauth_config.json, see NOTICE) and uses it when you do not pass another one. The flow is the original's remote copy-and-paste flow: the library builds the URL, your application shows it, the user pastes the code, and the token is saved in the profile. The next sign-in reuses the token and refreshes it when it expires.

Sign in with the profile work, with one call:

using GoogleColabCli.Auth;
using GoogleColabCli.State;

// Your IAuthorizationCodeProvider shows the URL to the user and returns the pasted code.
var session = await AuthService.SignInWithProfileAsync(
    new ColabProfile("work"),        // token stored in ~/.config/colab-cli/work/token.json
    http,
    codeProvider);
var colabHttp = new HttpClient(session);

To use your own OAuth client, pass it as the optional clientConfig argument (or build an AuthService yourself):

var config = OAuthClientConfig.FromFile(profile.OauthConfigPath);
var auth = new AuthService(http, config, new FileCredentialStore(profile.TokenPath), codeProvider);
var session = await auth.GetCredentialsAsync(AuthProvider.OAuth2);
  • User OAuth2: the default client, or yours (OAuthClientConfig); the token store is an ICredentialStore (by default FileCredentialStore, which writes the same JSON as the original).
  • Application Default Credentials: AuthProvider.Adc, using the usual environment variables.

The credential store is injectable: if you need to encrypt the token, implement ICredentialStore (LoadAsync, SaveAsync, DeleteAsync). Tokens are never written to logs.

This client is unofficial and is not affiliated with Google. Use it in compliance with the Google Colab terms of service.

Colab client (Client)

Client is the runtime assignment API (client.py). It takes the environment (Prod for the production Colab), an authenticated HttpClient and, optionally, ClientOptions (by default, the original's settings read from COLAB_CLI_*):

using GoogleColabCli.Client;
using GoogleColabCli.Client.Models;

var colab = new Client(new Prod(), colabHttp);

var assignment = await colab.AssignAsync(notebookHash, Variant.Default, Accelerator.T4);
var account = await colab.GetConsumptionUserInfoAsync();
var active = await colab.ListAssignmentsAsync();
await colab.UnassignAsync(assignment.Endpoint);

AssignAsync retries on 502, 503, 504 or timeout. On 412 it throws TooManyAssignmentsError; other Colab errors throw ColabRequestError.

Session state (ColabState)

ColabState groups what the original calls State (common.py): sessions, settings, history and the Colab client. It is built from a profile and from a function that creates the Client the first time it is needed, so authentication stays in your code:

using GoogleColabCli.Kernel;
using GoogleColabCli.Sessions;

var state = new ColabState(
    profile,
    (_, _) => Task.FromResult(colab),     // your authentication goes here
    colabHttp,
    new WebSocketClientFactory());

var options = RuntimeOptionsResolver.Resolve(gpu: null, tpu: null, highMem: false);
var session = await state.NewAsync(options, "my-session");
var list = await state.StatusAsync();
await state.StopAsync("my-session");

Operations: NewAsync, StatusAsync, SessionsAsync, SyncSessionsAsync, ResolveSessionAsync, GetSessionAsync, StopAsync, RestartKernelAsync, PruneSessionAsync. Session errors throw SessionNotFoundException or SessionResolutionException.

Code execution (ExecCommand)

Runs code in an existing session and returns the output per block. If the input is a notebook, it writes <name>_output.ipynb, as the original does.

using GoogleColabCli.Execution;

var executor = new ExecCommand(state.Store, state.History, colabHttp, new WebSocketClientFactory());
var localSession = await state.GetSessionAsync("my-session");

var result = await executor.ExecuteAsync(localSession!, new ExecRequest
{
    InputCode = "print('hello')",
    Env = ["MODE=test"],
    Timeout = TimeSpan.FromSeconds(60),
    OutputHook = output => Console.WriteLine(output), // output as it arrives
});

ExecRequest accepts FilePath (.py or .ipynb) or InputCode; the library does not read stdin. ExecutionUtils exposes the parsing of KEY=VALUE pairs and the environment prelude.

Run a script on a new VM (RunCommand)

Assigns a VM, runs the script with python script.py semantics and releases the VM afterwards (unless Keep is set):

using GoogleColabCli.Run;

var run = new RunCommand(state, colabHttp, new WebSocketClientFactory());
var runResult = await run.RunAsync(new RunRequest
{
    ScriptPath = @"C:\scripts\train.py",
    Arguments = ["--epochs", "3"],
    Options = options,
});
// runResult.SessionName, runResult.ExitCode

Files (FileOperations)

using GoogleColabCli.Files;

// contents: GoogleColabCli.Contents.ContentsClient already built for the session.
var files = new FileOperations(contents, "my-session", state.History);
var entries = await files.LsAsync("content");
await files.UploadAsync(@"C:\data\x.csv", "content/x.csv");
await files.DownloadAsync("content/result.txt", @"C:\data\result.txt");
await files.RmAsync("content/x.csv");

Errors are thrown as exceptions; every successful operation is recorded in the history, as in the original.

Runtime and kernel (ColabRuntime, KernelWebSocketClient)

ColabRuntime manages a session's runtime (proxy, kernel, stop and restart). KernelWebSocketClient speaks the Jupyter protocol over WebSocket (WsDefaultProtocol and WsV1Protocol); ExecuteAsync returns the output text, and ExecuteInteractiveAsync lets you answer input() with InputAsync.

SSH (SshService)

Prepares a session with SSH access (PrepareSessionProxyAsync, PrepareInteractiveSessionAsync) and opens a proxy bridge between a Stream and the tunnel WebSocket (OpenProxyAsync). The public key comes from PublicKeyResolver (by default derived with ssh-keygen; the consumer can inject IPublicKeyDeriver). Errors are SshKeyError and SshConnectionError.

Automation (AutomationCommand)

Mounts Google Drive (MountDriveAsync), installs packages (InstallPackagesAsync) and authenticates the runtime (AuthenticateAsync) in a session, returning the outputs as JsonObject. Failures throw AutomationException.

Utilities

  • Consumption and NumericFormat: account balance and consumption formatting.
  • AccountUsage.GetStatusAsync: account status as text.
  • Identity: user lookup for the token.
  • SessionLog: sessions with history and events.
  • ConnectionUrl: URL to connect to a session.
  • HistoryConverter: exports the history to .ipynb.
  • PyJson and PyText: serialization and text with the same format as Python.

Module map: Python → C#

Names follow the original in PascalCase. Each type cites the source file and function in its documentation.

Python module (colab_cli) C# type
client.py GoogleColabCli.Client.Client
auth.py GoogleColabCli.Auth.AuthService and Auth/*
state.py GoogleColabCli.State (ColabProfile, StateStore, SettingsStore)
common.py GoogleColabCli.Sessions.ColabState
runtime.py GoogleColabCli.Runtime.ColabRuntime
contents.py GoogleColabCli.Contents.ContentsClient
converter.py GoogleColabCli.Converter (HistoryConverter, PyJson, PyText)
history.py GoogleColabCli.History.HistoryLogger
consumption.py GoogleColabCli.Consumption
utils.py GoogleColabCli.Utils.Utils
commands/automation.py GoogleColabCli.Automation.AutomationCommand
commands/execution.py GoogleColabCli.Execution.ExecCommand
commands/files.py GoogleColabCli.Files.FileOperations
commands/run.py GoogleColabCli.Run.RunCommand
commands/session.py GoogleColabCli.Sessions.ColabState
commands/ssh.py GoogleColabCli.Ssh.SshService
commands/usage.py GoogleColabCli.Utility.AccountUsage
commands/utility.py GoogleColabCli.Utility (Identity, SessionLog, ConnectionUrl)
cli.py, console.py, repl.py, auto_update.py Not ported (command-line interface, rich, prompt-toolkit)
oauth_config.json Embedded as the default OAuth client (public Google Cloud SDK client, see NOTICE)

The CLI dependencies (typer, rich, prompt-toolkit, click) are not part of the library.

Test console (netcolab)

A standalone tool, only for testing the library. It accepts the same arguments as the colab command of google-colab-cli 0.7.5: the same global options, commands, short and long options, arguments and defaults. Global options go before the command:

dotnet run --project netcolab -- usage
dotnet run --project netcolab -- new --name test
dotnet run --project netcolab -- exec -s test -f script.py

After dotnet build -c Release, the executable is netcolab/bin/Release/net10.0/netcolab.exe; netcolab --help (or netcolab help <command>) shows the usage.

Global options:

  • -c, --client-oauth-config <path>: client OAuth configuration (default: ~/.colab-cli-oauth-config.json). If that file does not exist, the embedded default client is used, so --auth oauth2 works without configuration.
  • --config <path>: session state file (sessions.json). Without it, the sessions of the default profile are used.
  • --logtostderr: accepted; the console always writes its progress to stderr.
  • --auth oauth2|adc: authentication strategy, case-insensitive (default: oauth2).
  • --show-completion [bash|powershell|pwsh]: print the completion script of the shell and exit. Without a shell, PowerShell is used on Windows and bash elsewhere.
  • --install-completion [bash|powershell|pwsh]: add the completion script to the profile of the shell (~/.bashrc, or the PowerShell profile) and exit. It is added once.

Credentials and sessions are stored by the library in the default profile default, under ~/.config/colab-cli/default/ (token.json, sessions.json, history/). The console never asks for a path to them. The --profile, --directory and --oauth options of earlier versions were removed.

Update check: netcolab update looks for a newer GoogleColabClient on NuGet (the original looks on PyPI). Once a day the check also runs in the background before the commands that are not silent, and it prints the banner when a newer version exists; "enable_update_check": false in ~/.config/colab-cli/default/settings.json turns it off. update --install does not upgrade netcolab in place (it is built from this repository); it prints the dotnet add package GoogleColabClient --version <latest> command for projects that reference the library.

Commands. "Supported" commands run; the others are accepted with the same options and then exit with code 2 and the message <command> is not supported by netcolab:

Command (colab) Options and arguments (colab) netcolab
new -s/--session, --tpu, --gpu, --high-mem Supported
sessions none Supported
status -s/--session Supported
restart-kernel -s/--session Supported
stop -s/--session Supported
exec -s/--session, -f/--file, --output-image, --timeout (default 30.0), --env (repeatable); code on stdin when no file Supported; --output-image is ignored with a warning
run SCRIPT [SCRIPT_ARGS...], -s/--session, --tpu, --gpu, --high-mem, --keep, --timeout, --env Supported
ls -s/--session, [PATH] (default content) Supported
rm -s/--session, PATH Supported
upload -s/--session, LOCAL_PATH REMOTE_PATH Supported
download -s/--session, REMOTE_PATH LOCAL_PATH Supported
drivemount -s/--session, [PATH] (default /content/drive) Supported
install -s/--session, [PACKAGES...], -r/--requirement Supported
auth (hidden) -s/--session Supported
usage none Supported
url -s/--session, --host (default https://colab.research.google.com), --open Supported
log -s/--session, -n/--lines, -t/--type, -o/--output Supported; --output is not supported
ssh -s/--session, --proxy-mode, -i/--identity, --gpu, --tpu, --high-mem, --rm Only --proxy-mode; interactive mode is not supported
help [COMMAND] Supported
edit, repl, console as in colab Supported in the terminal: they read their input from the console (repl and console also accept piped input)
pay none Supported: prints the signup URL and opens the browser
version none Supported: prints the library version and the original version (0.7.5)
update --install Supported: checks NuGet; --install does not upgrade in place (see above)
readme, skill none Supported: print the README and the SKILL of netcolab (embedded in the executable)
whoami (hidden) none Supported: prints the provider, email, audience, expiry and scopes of the active credentials (tokeninfo of Google; the token itself is never printed)
README, SKILL (hidden) as in colab Supported: same as readme and skill

Exit codes: 0 on success, 1 on a runtime error, 2 on a usage error or an unsupported command.

License and attribution

Apache-2.0. See LICENSE and NOTICE: the original code is by Google LLC and this port modifies it.

Development

dotnet build GoogleColabCli.slnx -c Release -warnaserror
dotnet format GoogleColabCli.slnx --verify-no-changes
dotnet test GoogleColabCli.slnx -c Release --filter Category!=Live

The default tests use no network: the harness simulates HTTP and WebSocket.

Tests marked Category=Live contact the real Colab and are skipped when their configuration is missing. Use a profile that already has token.json (an oauth_config.json is needed only if you use your own client):

$env:COLAB_LIVE_PROFILE = "my-account"
$env:COLAB_LIVE_DIRECTORY = "D:\secret\colab"   # optional
dotnet test GoogleColabCli.slnx -c Release --filter Category=Live

Credentials never go into the repository or the tests.

Local packaging

dotnet pack GoogleColabCli/GoogleColabCli.csproj -c Release -o <folder-outside-the-repo>
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 58 11/23/2026