google-colab-cli 0.7.6__tar.gz → 0.8.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/AGENTS.md +10 -7
  2. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/CHANGELOG.md +10 -0
  3. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/PKG-INFO +10 -6
  4. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/README.md +9 -5
  5. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/01_session_management.md +24 -3
  6. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/02_execution_and_interactive.md +16 -9
  7. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/03_file_management.md +1 -0
  8. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/04_automation_and_utility.md +104 -48
  9. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/05_run_command.md +4 -2
  10. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/06_ssh_access.md +26 -9
  11. google_colab_cli-0.8.1/docs/07_update_notices.md +169 -0
  12. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/demos.md +4 -12
  13. google_colab_cli-0.8.1/docs/public_api_migration_plan.md +145 -0
  14. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/examples/finetune_run.py +6 -5
  15. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/README.md +2 -2
  16. google_colab_cli-0.8.1/integration/repro_update_notices/test.sh +120 -0
  17. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/repro_windows_ssh/test.py +16 -3
  18. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/pyproject.toml +1 -0
  19. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/skills/colab-operator/SKILL.md +11 -13
  20. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/auth.py +143 -28
  21. google_colab_cli-0.8.1/src/colab_cli/auto_update.py +393 -0
  22. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/cli.py +21 -1
  23. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/client.py +174 -12
  24. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/automation.py +94 -16
  25. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/execution.py +76 -34
  26. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/run.py +28 -109
  27. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/session.py +119 -53
  28. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/ssh.py +77 -8
  29. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/utility.py +82 -8
  30. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/common.py +12 -1
  31. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/contents.py +8 -1
  32. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/converter.py +0 -2
  33. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/repl.py +0 -1
  34. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/state.py +16 -2
  35. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/conftest.py +16 -9
  36. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_auth.py +385 -27
  37. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_auth_adc.py +15 -6
  38. google_colab_cli-0.8.1/tests/test_automation.py +317 -0
  39. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_cli.py +378 -15
  40. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_client.py +148 -7
  41. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_common.py +23 -0
  42. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_contents.py +38 -1
  43. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_exec.py +158 -2
  44. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_ipynb_exec.py +46 -0
  45. google_colab_cli-0.8.1/tests/test_notices_tool.py +352 -0
  46. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_run.py +102 -0
  47. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_runtime_options.py +7 -4
  48. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_ssh.py +53 -4
  49. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_ssh_autocreate.py +4 -12
  50. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_ssh_lifecycle.py +7 -21
  51. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_ssh_wire_contract.py +7 -11
  52. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_state.py +31 -2
  53. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_update.py +609 -2
  54. google_colab_cli-0.8.1/tests/test_windows_ssh.py +314 -0
  55. google_colab_cli-0.8.1/tools/NOTICE.md +7 -0
  56. google_colab_cli-0.8.1/tools/notices.py +418 -0
  57. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/uv.lock +46 -46
  58. google_colab_cli-0.7.6/integration/repro_piped_console/test.sh +0 -96
  59. google_colab_cli-0.7.6/src/colab_cli/auto_update.py +0 -248
  60. google_colab_cli-0.7.6/src/colab_cli/console.py +0 -197
  61. google_colab_cli-0.7.6/tests/test_automation.py +0 -150
  62. google_colab_cli-0.7.6/tests/test_console.py +0 -261
  63. google_colab_cli-0.7.6/tests/test_windows_ssh.py +0 -165
  64. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/.githooks/pre-commit +0 -0
  65. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/.gitignore +0 -0
  66. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/.pre-commit-config.yaml +0 -0
  67. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/.python-version +0 -0
  68. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/CONTRIBUTING.md +0 -0
  69. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/LICENSE +0 -0
  70. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/cloudbuild.yaml +0 -0
  71. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/3042ab12-2026-05-07.png +0 -0
  72. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/docs/demo.webm +0 -0
  73. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/repro_bundled_oauth/test.sh +0 -0
  74. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/repro_legacy_token_migration/test.sh +0 -0
  75. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/repro_plot_redirection/test.sh +0 -0
  76. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/repro_run_command/test.sh +0 -0
  77. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/repro_ssh/test.sh +0 -0
  78. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/integration/repro_variable_persistence/test.sh +0 -0
  79. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/__init__.py +0 -0
  80. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/files.py +0 -0
  81. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/commands/usage.py +0 -0
  82. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/consumption.py +0 -0
  83. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/history.py +0 -0
  84. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/oauth_config.json +0 -0
  85. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/runtime.py +0 -0
  86. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/src/colab_cli/utils.py +0 -0
  87. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/mock_kernel.py +0 -0
  88. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_cli_log.py +0 -0
  89. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_consumption.py +0 -0
  90. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_consumption_client.py +0 -0
  91. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_history.py +0 -0
  92. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_local_credentials.py +0 -0
  93. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_log_export.py +0 -0
  94. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_pay.py +0 -0
  95. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_readme.py +0 -0
  96. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_repl.py +0 -0
  97. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_resolution_logic.py +0 -0
  98. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_runtime.py +0 -0
  99. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_ssh_cmd.py +0 -0
  100. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_ssh_workdir.py +0 -0
  101. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_streaming.py +0 -0
  102. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_url.py +0 -0
  103. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_utils.py +0 -0
  104. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_version.py +0 -0
  105. {google_colab_cli-0.7.6 → google_colab_cli-0.8.1}/tests/test_whoami.py +0 -0
@@ -6,9 +6,9 @@
6
6
  - **Client**: `ColabClient` handles API interactions (assignment, unassignment).
7
7
  - **Auth**: `auth.py` exposes a single `get_credentials(config_path, provider)` facade that dispatches on the `AuthProvider` enum. Two providers are supported, selected via the global `--auth=oauth2|adc` flag (default `oauth2`):
8
8
  - `oauth2`: public `google-auth-oauthlib` `InstalledAppFlow`, token cached in the OS keyring via the Python `keyring` library (`service_name="google-colab-cli"`, `username="oauth_token"`), falling back to `_run_remote_flow` if the keyring is not accessible or locked (keyring failures are echoed to stderr; logs alone go to a file; on Linux, `_check_linux_keyring_locked` checks `secretstorage` beforehand and warns immediately when the `SecretService` collection is locked). A pre-keyring `~/.config/colab-cli/token.json` (`LEGACY_TOKEN_PATH`) is migrated into the keyring and deleted only after a successful keyring write, or immediately when the keyring already holds a token. Integration scripts assume no legacy file exists and detect OAuth2 availability via a keyring-only `has_oauth2_token` helper; the migration path is covered by `integration/repro_legacy_token_migration/test.sh` (isolated HOME + file-backed test keyring). Tests that must ignore the host keyring set `PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring`. Reads the client OAuth config from `-c/--client-oauth-config` (default `~/.colab-cli-oauth-config.json`), falling back to the **bundled** `src/colab_cli/oauth_config.json` resource (re-added in PR #41 / `9f44fe2`, 2026-05-29 — the earlier "removed in `20eb88e`" note was stale/incorrect; the file exists and `auth.py:_get_google_auth_credentials` loads it via `importlib.resources`). As of 2026-06-11 the flow is a **remote copy-paste flow**, not a localhost server: `_run_remote_flow` sets `redirect_uri=https://sdk.cloud.google.com/applicationdefaultauthcode.html` + `token_usage=remote`, prints the URL, and reads the pasted code via `input()`. NEVER revert to OOB (`urn:ietf:wg:oauth:2.0:oob`) — Google blocked it in 2022 ("OOB flow has been blocked"); the `sdk.cloud.google.com` redirect is registered only to the bundled cloud-SDK client (`764086051850-...`), so any other client id gets `redirect_uri_mismatch`. Server-side acceptance/rejection of these variants is verifiable GET-only by building the authorization URL and inspecting whether Google reaches sign-in vs. an OAuth error page (no resources allocated).
9
- - `adc`: Google Application Default Credentials via `google.auth.default()`. The CLI passes `scopes=PUBLIC_SCOPES` (which includes `colaboratory`) and re-applies via `creds.with_scopes()` for credential types that support it. **User credentials minted by `gcloud auth application-default login` ignore the `scopes=` kwarg AND raise `NotImplementedError` on `with_scopes`**: ADC users must explicitly re-authenticate with `gcloud auth application-default login --scopes=openid,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/colaboratory`. `userinfo.email` is required by the session backend at `colab.research.google.com` (assign/unassign/sessions return 401 without it); `colaboratory` is retained for forward compatibility and other Colab features; `openid` and `cloud-platform` are mandated by `gcloud` itself, which rejects scope lists that omit `cloud-platform` with `Invalid value for [--scopes]`. Service-account / GCE / GKE / impersonated creds get the right scopes transparently via `with_scopes`.
10
- - **Backend Hosts**: Two distinct backends with different requirements:
11
- - `colab.research.google.com` (session backend / `tun/m/...`): accepts the `userinfo.email` scope. Handles assign, unassign, CCU info, and the contents API.
9
+ - `adc`: Google Application Default Credentials via `google.auth.default()`. The CLI passes `scopes=PUBLIC_SCOPES` (which includes `colaboratory`) and re-applies via `creds.with_scopes()` for credential types that support it. **User credentials minted by `gcloud auth application-default login` ignore the `scopes=` kwarg AND raise `NotImplementedError` on `with_scopes`**: ADC users must explicitly re-authenticate with `gcloud auth application-default login --scopes=openid,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/colaboratory`. Both `colaboratory` and `userinfo.email` are required by the session backend at `colab.research.google.com` (assign/unassign/sessions return 401 without them); `openid` and `cloud-platform` are mandated by `gcloud` itself, which rejects scope lists that omit `cloud-platform` with `Invalid value for [--scopes]`. Service-account / GCE / GKE / impersonated creds get the right scopes transparently via `with_scopes`.
10
+ - **Backend Hosts**:
11
+ - `colab.research.google.com` (session backend / `tun/m/...`): requires the `colaboratory` and `userinfo.email` scopes. Handles assign, unassign, CCU info, and the contents API.
12
12
  - **Runtime**: `ColabRuntime` wraps `jupyter-kernel-client` for execution.
13
13
  - **State**:
14
14
  - `StateStore` persists session metadata in `~/.config/colab-cli/sessions.json`.
@@ -37,7 +37,7 @@
37
37
 
38
38
  ## Subcommand Workflows
39
39
  - **Session Management**: `new`, `sessions`, `status`, `stop`.
40
- - **Execution**: `repl`, `exec`, `console`.
40
+ - **Execution**: `repl`, `exec`, `ssh`.
41
41
  - **Files**: `ls`, `rm`, `upload`, `download`, `edit`.
42
42
  - **Automation**: `auth`, `drivemount`, `install`, `log`, `pay`, `version`, `update`.
43
43
 
@@ -69,7 +69,7 @@ The package version is derived from the git tag via `hatch-vcs` (see `pyproject.
69
69
  10. **Live Probes Allocate Real Resources**: Probing the Colab API to debug an issue creates real, billable assignments — every successful POST `/tun/m/assign` reserves a VM. Prefer GET-only (read) probes whenever possible. For any state-mutating call, (a) record every endpoint you create as you go, and (b) clean up via `client.unassign(endpoint)` (or `colab stop`) before declaring the investigation done. Then verify with `colab sessions` that nothing was orphaned.
70
70
  11. **Push Freshness**: The remote may have advanced during a session (other contributors land commits while you work). ALWAYS `git fetch <remote>` immediately before pushing or merging. If `git log main..<remote>/main` is non-empty, reset local `main` to the remote, rebase feature branches onto it, retest, then push. NEVER force-push `main` to recover from divergence.
71
71
  12. **Amend Safety**: Before `git commit --amend`, explicitly verify all three preconditions: (a) the user requested amend OR a pre-commit hook auto-modified files for an otherwise-successful commit, (b) HEAD was created by you in this conversation (`git log -1 --format='%an %ae'`), (c) the commit has not been pushed to a remote. If any precondition fails, create a new commit instead. NEVER amend a failed/rejected commit — fix the issue and create a new one.
72
- 13. **Run Integration Tests Yourself**: Re-read AGENTS.md "Agent Execution Limitations" before claiming you can't run a test. The CANNOT-run list is exclusively interactive commands (`colab auth`, `colab drivemount`, `colab repl`, `colab console`). Tests built on `colab new` / `colab stop` / `colab log` are non-interactive and you MUST run them yourself before declaring a fix complete. Encoded after running through a full implement-and-document cycle for a fix that the integration test would have falsified in 30 seconds — the cure was `uv run bash integration/repro_run_command/test.sh`.
72
+ 13. **Run Integration Tests Yourself**: Re-read AGENTS.md "Agent Execution Limitations" before claiming you can't run a test. The CANNOT-run list is exclusively interactive commands (`colab auth`, `colab drivemount`, unpiped `colab repl`, interactive `colab ssh`). Tests built on `colab new` / `colab stop` / `colab log` are non-interactive and you MUST run them yourself before declaring a fix complete. Encoded after running through a full implement-and-document cycle for a fix that the integration test would have falsified in 30 seconds — the cure was `uv run bash integration/repro_run_command/test.sh`.
73
73
  14. **Heed Research Caveats**: When a research subagent surfaces a caveat ("the proto allows it but the policy may reject"), treat it as a TODO to verify, not as a footnote. The validation pattern: shell out to the actual service with the proposed inputs and confirm the response matches expectations BEFORE writing the code that depends on it. For policy-gated paths, run a one-shot probe before committing to a design.
74
74
  15. **Two distinct auths — never confuse them**: This codebase has two unrelated authentication concerns: (a) **CLI-to-Colab-control-plane**: how `Client` authenticates HTTP requests to `colab.research.google.com` and `colab.pa.googleapis.com`. Driven by the global `--auth={oauth2,adc}` flag and `auth.py:get_credentials`. The OAuth2 path is bootstrapped automatically by `google_auth_oauthlib`'s `InstalledAppFlow` on first invocation when no token is stored in `keyring` (or `keyring` is inaccessible); **no separate command is needed** — any `--auth=oauth2` invocation (e.g. `colab --auth=oauth2 sessions`) triggers the browser consent flow. (b) **VM-side credentials**: how the `colab auth` subcommand injects user GCP credentials *into* the running Colab kernel so notebook code (e.g. `gcloud`, BigQuery client) can make authenticated calls from inside the VM. This uses the `USE_AUTH_EPHEM='0'` gcloud-fallback path executed on the kernel via `ColabRuntime`. **NEVER tell a user to "run `colab auth`" as a prerequisite for fixing CLI-side auth issues** — they're orthogonal layers and the suggestion misleads.
75
75
  16. **Pydantic validation requires a schema**: `_issue_request` accepts an optional `schema=` and historically called `TypeAdapter(schema).validate_python(...)` unconditionally. When `schema=None` (a caller that doesn't care about the response body — e.g. unassign or fire-and-forget endpoints that return `[]`), this raises `pydantic.ValidationError: Input should be None`. Always guard with `if schema is None: return` after the empty-body short-circuit.
@@ -77,17 +77,20 @@ The package version is derived from the git tag via `hatch-vcs` (see `pyproject.
77
77
  18. **Verify research-tool claims with primary sources**: Research tools and AI assistants can be confidently wrong, especially about edge cases or features outside their training corpus. When such a tool says "X is not used / not parsed / doesn't exist", treat it as a hypothesis to verify, not a fact. Always cross-check against the primary source (the actual code or config) — and when a tool names files, check whether the indirection chain it describes actually exists. The cost of believing the tool when it's wrong is shipping a non-functional feature; the cost of double-checking is small. Encoded 2026-05-05 after a `colab url` first-cut shipped the wrong URL format because of unverified output.
78
78
  19. **Clean up orphaned assignments before finishing live tests**: After running a live integration test, `colab sessions` may show server-side assignments that the local `colab stop` couldn't see (e.g. assignments leaked from earlier in the session, or from crashed prior runs). Always run `colab sessions` as the final cleanup step, and for any `[?]`-marked orphan, run `python -c "from colab_cli.common import state; state.client.unassign('<endpoint>')"` (the CLI doesn't expose a direct unassign-by-endpoint command). Re-verify with `colab sessions` returning "No active sessions". Encoded 2026-05-05 after the first `colab url` live test left an orphan from a prior conversation turn that would have idled-out and billed compute units.
79
79
  20. **Forward unknown args through Typer with `context_settings`**: Typer/Click consumes any token starting with `-`/`--` as a flag of the parent command unless told otherwise. For a subcommand like `colab run script.py --some-script-flag` (where `--some-script-flag` belongs to the user's script, not to `colab`), declare it with `app.command(name="run", context_settings={"allow_extra_args": True, "ignore_unknown_options": True})` and accept the positional with `Annotated[Optional[List[str]], typer.Argument(...)] = None`. Also use `repr()` (not f-string interpolation) when embedding those forwarded strings into kernel-side Python source — `repr()` produces a safe round-trippable literal regardless of the user's shell-passed quotes, backslashes, or non-ASCII bytes. Encoded 2026-05-12 while implementing `colab run`.
80
+ 21. **Break Work into Small PRs/Commits**: Decompose multi-step changes into small, self-contained PRs or commits so each step is easy to review and verify independently.
81
+ 22. **Concise Code & No One-Line Comments**: Write concise, self-explanatory code and do NOT write single-line comments. Use docstrings or multi-line explanations only when genuinely necessary to explain non-obvious invariants.
80
82
 
81
83
  ## Agent Execution Limitations (What I Can vs Cannot Run)
82
84
  As an AI agent operating via non-interactive shell tools (`run_shell_command`), there are strict limits on what I can test autonomously without human intervention:
83
85
  - **I CAN Run:**
84
86
  - Automated tests (`pytest`), linting (`ruff`), and headless execution scripts.
85
87
  - Subcommands that don't pause for user input (e.g., `colab new`, `colab status`, `colab stop`, `colab ls`, `colab install`, `colab exec <file.py>`).
86
- - **Piped `colab repl` and `colab console`**: as of 2026-05-07 both commands support piped stdin and exit cleanly on EOF (`echo 'cmd' | colab console -s s` returns in ~1.2s). The unpiped, interactive variants still cannot be run autonomously.
88
+ - **Piped `colab repl`**: as of 2026-05-07 it supports piped stdin and exits cleanly on EOF (`echo 'print(1)' | colab repl -s s`). The unpiped, interactive variant still cannot be run autonomously.
89
+ - **One-shot shell commands**: `colab ssh -s s -- cmd` runs `cmd` non-interactively and exits with its status (add `</dev/null` if my shell tool runs commands in a terminal); where ssh can't work, use `echo '!cmd' | colab exec -s s` (each `!` line is its own shell and IPython expands `{expr}` and `$name` in it).
87
90
  - Specially crafted mock scripts that simulate timeouts or API calls.
88
91
  - **I CANNOT Run (Requires User Assistance):**
89
92
  - **`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()`.
90
93
  - **`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`.
91
- - **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.)
94
+ - **Interactive (TTY) `colab repl` / `colab ssh`**: When stdin is a real terminal these commands open interactive sessions that require real-time keystroke streaming. My shell tools cannot support this. (Piped stdin to `colab repl` or `colab exec` is fine — see above.)
92
95
 
93
96
  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.
@@ -22,6 +22,16 @@ below corresponds to a tag of the same name.
22
22
 
23
23
  - **ssh:** `colab ssh [-s NAME] -- CMD` runs one command on an existing runtime and exits with its status. Output is byte-exact when piped (a PTY only when stdin and stdout are terminals), and it never creates a runtime. Its handshake is tagged `ssh-mode-cmd`.
24
24
 
25
+ ### Removed
26
+
27
+ - **console:** **BREAKING:** Remove the `colab console` subcommand. Use
28
+ `colab ssh -s NAME` for an interactive shell on the runtime and
29
+ `colab ssh -s NAME -- CMD` for one-shot commands; where ssh can't work, pipe
30
+ `!`-prefixed shell commands to `colab exec -s NAME`. Each `!` line is its own
31
+ shell and IPython expands `{expr}` and `$name` in it, so start a multi-line
32
+ script with `%%bash` and keep untrusted text out of `!` lines. Breaking, so
33
+ it ships in a new major version.
34
+
25
35
  ### Fixed
26
36
 
27
37
  - **ssh:** `colab --config FILE ssh` and `colab --auth adc ssh` now keep those options in the ProxyCommand that `colab ssh` starts, so it uses the same sessions file and auth provider instead of the defaults.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: google-colab-cli
3
- Version: 0.7.6
3
+ Version: 0.8.1
4
4
  Summary: CLI for interacting with Colab.
5
5
  Project-URL: Homepage, https://github.com/googlecolab/google-colab-cli
6
6
  Project-URL: Repository, https://github.com/googlecolab/google-colab-cli
@@ -54,7 +54,7 @@ Designed to support seamless developer productivity, headless automation, and AI
54
54
  ## Key Features
55
55
 
56
56
  * **Instant VM Provisioning:** Spin up CPU, GPU (T4, L4, G4, H100, A100), or TPU (v5e1, v6e1) runtimes in seconds.
57
- * **Robust Code Execution:** Run local Python scripts, Jupyter Notebooks (`.ipynb`), or piped `stdin` code; launch interactive REPLs or raw TTY console shells.
57
+ * **Robust Code Execution:** Run local Python scripts, Jupyter Notebooks (`.ipynb`), or piped `stdin` code; launch interactive REPLs or SSH shells (`colab ssh`).
58
58
  * **Ephemeral Job Runner (`colab run`):** Provision a fresh VM, execute a local script with forwarded arguments, retrieve output files, and automatically tear down the runtime in a single command.
59
59
  * **Activity-Based Liveness:** Sessions stay alive as long as the kernel is active, with the Colab backend automatically maintaining liveness.
60
60
  * **Seamless Workspace Automation:** Mount Google Drive, authenticate Google Cloud Platform (GCP) credentials, and install dependencies with high-performance `uv` package management.
@@ -118,8 +118,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
118
118
  | `colab run [--gpu GPU] [--tpu TPU] [--high-mem] [--keep] SCRIPT [ARGS...]` | Run a local script on a fresh VM, forwarding arguments, then release it |
119
119
  | `colab exec [-s NAME] [-f FILE] [--output-image PATH]` | Execute Python code from stdin, a local `.py` file, or a `.ipynb` notebook |
120
120
  | `colab repl [-s NAME] [--output-image PATH]` | Start an interactive Python REPL on the VM (exits cleanly on piped EOF) |
121
- | `colab console [-s NAME]` | Connect to a raw interactive TTY shell (tmux) on the remote VM |
122
- | `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 |
121
+ | `colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem] [-- CMD ...]` | Open an SSH shell to the runtime over WebSocket, run a one-shot remote command (`-- CMD`), or act as an OpenSSH `ProxyCommand` bridge for IDE remote-dev |
123
122
 
124
123
  ### File Operations
125
124
  | Command | Description |
@@ -134,6 +133,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
134
133
  | Command | Description |
135
134
  | --- | --- |
136
135
  | `colab auth [-s NAME]` | Authenticate the VM for GCP services (BigQuery, GCS, etc.) |
136
+ | `colab logout` | Clear local OAuth2 and cached runtime tokens to sign out or switch accounts |
137
137
  | `colab drivemount [-s NAME] [PATH]` | Mount Google Drive on the VM (default: `/content/drive`) |
138
138
  | `colab install [-s NAME] [-r FILE \| PKG...]` | Install packages on the VM using `uv` (falls back to `pip`) |
139
139
  | `colab log [-s NAME] [-n N] [-o FILE]` | View or export session history (`.ipynb`, `.md`, `.txt`, `.jsonl`) |
@@ -143,7 +143,11 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
143
143
  | `colab update [--install]` | Check for a newer release (and optionally upgrade the CLI in place) |
144
144
 
145
145
  ### Global Options
146
- * `--auth {oauth2,adc}` — Authentication strategy for the Colab API (default: `adc`).
146
+ * `--auth {oauth2,adc}` — Authentication strategy for the Colab API (default: `oauth2`). To authenticate with Application Default Credentials (`--auth adc`), run:
147
+ ```bash
148
+ gcloud auth application-default login \
149
+ --scopes=openid,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/colaboratory
150
+ ```
147
151
  * `-c, --client-oauth-config PATH` — Path to public OAuth client credentials configuration (default: `~/.colab-cli-oauth-config.json`).
148
152
  * `--config PATH` — Path to local session metadata storage (default: `~/.config/colab-cli/sessions.json`).
149
153
  * `--logtostderr` — Direct debug logging output to stderr.
@@ -181,7 +185,7 @@ colab stop -s analysis
181
185
  ## Usage Notes
182
186
 
183
187
  * **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`.
184
- * **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.
188
+ * **TTY Requirements:** `colab repl` and interactive `colab ssh` expect a local TTY. When running inside automated scripts or pipelines, pipe stdin to `colab repl` (e.g., `echo "print(1)" | colab repl`) to trigger its non-interactive mode, or run one-shot shell commands with `colab ssh -s NAME -- CMD` (e.g., `colab ssh -s NAME -- ls /content`); pass untrusted values as separate arguments (after `--` where the program accepts it), since a single argument is a remote shell line. `colab ssh` needs a local `ssh` client and key, so where it can't work (no client or key, a tool not on the minimal ssh environment's `PATH`, or the runtime's concurrent SSH connections in use), pipe the commands to `colab exec` with IPython's `!` prefix (e.g., `echo '!ls /content' | colab exec`); each `!` line is its own shell and IPython expands `{expr}` and `$name` in it, so start a multi-line script with `%%bash` and keep untrusted text out of `!` lines.
185
189
  * **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.
186
190
  * **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.
187
191
 
@@ -17,7 +17,7 @@ Designed to support seamless developer productivity, headless automation, and AI
17
17
  ## Key Features
18
18
 
19
19
  * **Instant VM Provisioning:** Spin up CPU, GPU (T4, L4, G4, H100, A100), or TPU (v5e1, v6e1) runtimes in seconds.
20
- * **Robust Code Execution:** Run local Python scripts, Jupyter Notebooks (`.ipynb`), or piped `stdin` code; launch interactive REPLs or raw TTY console shells.
20
+ * **Robust Code Execution:** Run local Python scripts, Jupyter Notebooks (`.ipynb`), or piped `stdin` code; launch interactive REPLs or SSH shells (`colab ssh`).
21
21
  * **Ephemeral Job Runner (`colab run`):** Provision a fresh VM, execute a local script with forwarded arguments, retrieve output files, and automatically tear down the runtime in a single command.
22
22
  * **Activity-Based Liveness:** Sessions stay alive as long as the kernel is active, with the Colab backend automatically maintaining liveness.
23
23
  * **Seamless Workspace Automation:** Mount Google Drive, authenticate Google Cloud Platform (GCP) credentials, and install dependencies with high-performance `uv` package management.
@@ -81,8 +81,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
81
81
  | `colab run [--gpu GPU] [--tpu TPU] [--high-mem] [--keep] SCRIPT [ARGS...]` | Run a local script on a fresh VM, forwarding arguments, then release it |
82
82
  | `colab exec [-s NAME] [-f FILE] [--output-image PATH]` | Execute Python code from stdin, a local `.py` file, or a `.ipynb` notebook |
83
83
  | `colab repl [-s NAME] [--output-image PATH]` | Start an interactive Python REPL on the VM (exits cleanly on piped EOF) |
84
- | `colab console [-s NAME]` | Connect to a raw interactive TTY shell (tmux) on the remote VM |
85
- | `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 |
84
+ | `colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem] [-- CMD ...]` | Open an SSH shell to the runtime over WebSocket, run a one-shot remote command (`-- CMD`), or act as an OpenSSH `ProxyCommand` bridge for IDE remote-dev |
86
85
 
87
86
  ### File Operations
88
87
  | Command | Description |
@@ -97,6 +96,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
97
96
  | Command | Description |
98
97
  | --- | --- |
99
98
  | `colab auth [-s NAME]` | Authenticate the VM for GCP services (BigQuery, GCS, etc.) |
99
+ | `colab logout` | Clear local OAuth2 and cached runtime tokens to sign out or switch accounts |
100
100
  | `colab drivemount [-s NAME] [PATH]` | Mount Google Drive on the VM (default: `/content/drive`) |
101
101
  | `colab install [-s NAME] [-r FILE \| PKG...]` | Install packages on the VM using `uv` (falls back to `pip`) |
102
102
  | `colab log [-s NAME] [-n N] [-o FILE]` | View or export session history (`.ipynb`, `.md`, `.txt`, `.jsonl`) |
@@ -106,7 +106,11 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
106
106
  | `colab update [--install]` | Check for a newer release (and optionally upgrade the CLI in place) |
107
107
 
108
108
  ### Global Options
109
- * `--auth {oauth2,adc}` — Authentication strategy for the Colab API (default: `adc`).
109
+ * `--auth {oauth2,adc}` — Authentication strategy for the Colab API (default: `oauth2`). To authenticate with Application Default Credentials (`--auth adc`), run:
110
+ ```bash
111
+ gcloud auth application-default login \
112
+ --scopes=openid,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/colaboratory
113
+ ```
110
114
  * `-c, --client-oauth-config PATH` — Path to public OAuth client credentials configuration (default: `~/.colab-cli-oauth-config.json`).
111
115
  * `--config PATH` — Path to local session metadata storage (default: `~/.config/colab-cli/sessions.json`).
112
116
  * `--logtostderr` — Direct debug logging output to stderr.
@@ -144,7 +148,7 @@ colab stop -s analysis
144
148
  ## Usage Notes
145
149
 
146
150
  * **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`.
147
- * **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.
151
+ * **TTY Requirements:** `colab repl` and interactive `colab ssh` expect a local TTY. When running inside automated scripts or pipelines, pipe stdin to `colab repl` (e.g., `echo "print(1)" | colab repl`) to trigger its non-interactive mode, or run one-shot shell commands with `colab ssh -s NAME -- CMD` (e.g., `colab ssh -s NAME -- ls /content`); pass untrusted values as separate arguments (after `--` where the program accepts it), since a single argument is a remote shell line. `colab ssh` needs a local `ssh` client and key, so where it can't work (no client or key, a tool not on the minimal ssh environment's `PATH`, or the runtime's concurrent SSH connections in use), pipe the commands to `colab exec` with IPython's `!` prefix (e.g., `echo '!ls /content' | colab exec`); each `!` line is its own shell and IPython expands `{expr}` and `$name` in it, so start a multi-line script with `%%bash` and keep untrusted text out of `!` lines.
148
152
  * **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.
149
153
  * **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.
150
154
 
@@ -1,9 +1,17 @@
1
1
  ---
2
2
  log:
3
+ 2026-12-04: Changed global `--public-api/--no-public-api` CLI option in `cli.py` to `Optional[bool] = None` so `settings.json`'s `use_public_api` takes effect whenever the flag and `COLAB_CLI_PUBLIC_API` are omitted (instead of being overridden to `False`).
4
+ 2026-12-04: `colab stop` now rejects combining `-s/--session` with `--all` (printing an error to stderr and exiting with status 2 before syncing or unassigning sessions).
5
+ 2026-12-02: `colab stop -s <target>` now falls back to `list_assignments()` and matches by server endpoint when `<target>` is not found in local state, allowing orphaned (`[?]`) assignments to be stopped directly (discussion #309).
6
+ 2026-12-01: Extracted `assign_runtime` in `session.py` (shared by `colab new` and `colab run`) to translate exhausted `HTTP 502/503/504` and `ReadTimeout` allocation failures into actionable CLI messages (including the browser Colab Terms of Service acceptance hint for first-time/newly entitled accounts, `colab sessions`, and `COLAB_CLI_REQUEST_TIMEOUT`) with exit code 1 instead of raw tracebacks (#273).
7
+ 2026-11-23: `colab stop -s <name>` now exits 1 when the named session does not exist (or has already vanished from the backend), delegating missing-session handling to `State.get_session` (#251).
8
+ 2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags.
3
9
  2026-11-04: `--gpu` and `--tpu` now reject unknown values instead of silently selecting `A100` (GPU) or `v6e1` (TPU). `resolve_runtime_options()` uses the new `GPU_ACCELERATORS` / `TPU_ACCELERATORS` maps and raises a `typer.BadParameter` that names the flag and the supported list; `--help` is generated from the same maps so it cannot drift. Validation runs before any assignment request, in both `colab new` and `colab run`.
4
10
  2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to check if the active Linux `SecretService` keyring collection is locked via `secretstorage` before reading or writing OAuth tokens, logging and printing an immediate warning with the collection label, timeout, and `--auth=adc` hint while still attempting the keyring operation.
11
+ 2026-10-29: Removed the `colab console` subcommand; the long-lived connections that skip mid-session token refresh are now `repl` and `ssh`.
5
12
  2026-10-29: The debug log (`colab.log` and `--logtostderr`) masks access tokens, runtime proxy tokens, OAuth codes, client secrets, auth headers and cookies, including in percent-encoded URLs; `jupyter_kernel_client` logs at INFO so kernel stdin replies are not recorded.
6
13
  2026-10-29: `sessions.json`, `settings.json`, `colab.log` and session history files are created with mode 0600, and existing copies are tightened to 0600 the next time the CLI uses them (history files whenever the history logger starts).
14
+ 2026-10-22: Added global `--public-api/--no-public-api` toggle (`COLAB_CLI_PUBLIC_API`, `Settings.use_public_api`, default `False`), dual `Client.list_assignments()` dispatch (`/v1beta/runtimes` vs `/tun/m/assignments`), `Operation`/`Status` models, and cached auth capability hints on HTTP 401/403.
7
15
  2026-10-21: Stored OAuth2 credentials in the OS native keyring via the `keyring` library instead of `~/.config/colab-cli/token.json`, falling back to `_run_remote_flow` if keyring is inaccessible. Keyring failures are reported on stderr, and an existing `token.json` is migrated into the keyring and then deleted (or deleted outright if the keyring already has a token).
8
16
  2026-10-14: Added configurable HTTP request timeouts and bounded allocation retries. Uncertain allocation POSTs are reconciled by GET using the same notebook hash before resubmission.
9
17
  2026-09-25: Runtime proxy tokens are now refreshed before expiry. `SessionState` persists `token_expires_at`, and `State.get_session` re-fetches the token via `GET /tun/m/assignments` when it's within 5 minutes of expiring.
@@ -79,7 +87,13 @@ the client waits `COLAB_CLI_RETRY_BACKOFF * 2**attempt` seconds (default 10, 20,
79
87
  It then queries the same notebook hash: an existing allocation is returned directly;
80
88
  otherwise the refreshed XSRF token is used for the next POST. HTTP 412 still raises
81
89
  `TooManyAssignmentsError`; other errors are not retried. Failed initial/recovery
82
- GETs and exhausted POST retries propagate to the caller. There is no unlimited wait.
90
+ GETs and exhausted POST retries propagate from `Client.assign()` to the caller.
91
+ At the CLI layer (`assign_runtime`, shared by `colab new` and `colab run`),
92
+ exhausted `502`/`503`/`504` responses and `ReadTimeout` errors are translated into
93
+ actionable stderr diagnostics (including accepting Colab Terms of Service at
94
+ `https://colab.research.google.com/`, checking `colab sessions`, and
95
+ `COLAB_CLI_REQUEST_TIMEOUT`) and exit code `1` instead of raw tracebacks. There
96
+ is no unlimited wait.
83
97
 
84
98
  ```bash
85
99
  COLAB_CLI_REQUEST_TIMEOUT=300 COLAB_CLI_ASSIGN_RETRIES=3 COLAB_CLI_RETRY_BACKOFF=10 \
@@ -114,6 +128,8 @@ end to end; mocked timeouts alone do not establish backend compatibility.
114
128
  - `authuser`: 0.
115
129
  - `<endpoint>`: The unique session identifier returned during assignment (e.g., `tpu-v5e1-s-kkb-...`).
116
130
  - **Cleanup**: Remove the session from the local state file upon successful 204 response.
131
+ - **Endpoint fallback**: If `-s <target>` does not match a local session name, `colab stop` queries `list_assignments()` and matches by server endpoint ID (as shown in `colab sessions`), unassigning the matching runtime and removing any local entry referencing that endpoint.
132
+ - **Missing sessions**: Stopping a specific session (`colab stop` or `colab stop -s <name>`) exits with code 1 if no matching local session or server endpoint exists. `colab stop --all` exits 0 when no sessions are active. Combining `-s/--session` with `--all` exits with code 2 (stderr) without modifying any sessions.
117
133
 
118
134
  ### 4. Session Listing (`colab sessions`)
119
135
  - **API**: `GET https://colab.research.google.com/tun/m/assignments` (based on `colab-agent` implementation).
@@ -123,17 +139,19 @@ end to end; mocked timeouts alone do not establish backend compatibility.
123
139
  VM liveness is automatically maintained by the Colab backend based on active kernel executions and interactions. The CLI runs no keep-alive daemon. A session persists until explicitly terminated via `colab stop` or until the backend reclaims it due to inactivity.
124
140
 
125
141
  ### 6. Runtime Proxy Token Refresh
126
- The runtime proxy token (`runtimeProxyInfo.token`) authenticates every request to the VM and expires after `tokenExpiresInSeconds` (1 hour). `SessionState.token_expires_at` stores the absolute expiry, computed when the token is received. Commands that talk to the VM load their session through `State.get_session(name)`, which, when the token is missing an expiry or is within 5 minutes of it, calls `GET /tun/m/assignments`, takes the fresh token/URL for the matching endpoint, and persists it. If the endpoint is no longer assigned, the session is pruned. `sync_sessions` also writes back the fresh tokens it already fetches. Long-lived connections (`repl`, `console`, `ssh`) only present the token on initial connect and aren't refreshed mid-session.
142
+ The runtime proxy token (`runtimeProxyInfo.token`) authenticates every request to the VM and expires after `tokenExpiresInSeconds` (1 hour). `SessionState.token_expires_at` stores the absolute expiry, computed when the token is received. Commands that talk to the VM load their session through `State.get_session(name)`, which, when the token is missing an expiry or is within 5 minutes of it, calls `GET /tun/m/assignments`, takes the fresh token/URL for the matching endpoint, and persists it. If the endpoint is no longer assigned, the session is pruned. `sync_sessions` also writes back the fresh tokens it already fetches. Long-lived connections (`repl`, `ssh`) only present the token on initial connect and aren't refreshed mid-session.
127
143
 
128
144
  ## TODO / Future Work
129
145
  - **Backend Sync**: Implement a way to reconcile the local `sessions.json` with the output of `colab sessions`.
130
146
  - **VM Resource Usage**: Add real-time resource usage (CPU/RAM/GPU) to the `status` output by executing a diagnostic snippet on the VM (distinct from account-level CU info, which is available via `colab usage`).
131
147
 
132
148
  ## Implementation Details
133
- - **Authentication**: Uses `google-auth-oauthlib` to perform a local server OAuth flow.
149
+ - **Authentication**: Uses `google-auth-oauthlib` (`InstalledAppFlow` remote copy-paste flow, default `--auth oauth2`) or Application Default Credentials (`--auth adc`).
134
150
  - **Global Flags**:
151
+ - `--auth`: Authentication strategy (`oauth2` or `adc`, default: `oauth2`). User ADC credentials require `gcloud auth application-default login --scopes=openid,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/colaboratory`.
135
152
  - `-c`, `--client-oauth-config`: Path to the client secrets JSON file (default: `~/.colab-cli-oauth-config.json`).
136
153
  - `--config`: Path to the session state JSON file (default: `~/.config/colab-cli/sessions.json`).
154
+ - `--public-api/--no-public-api`: Select the Colab Public API (`colaboratory.googleapis.com`) vs. the legacy tunnel API (`COLAB_CLI_PUBLIC_API` env var; defaults to `None` so `~/.config/colab-cli/settings.json`'s `use_public_api` applies when unset, which itself defaults to `False`).
137
155
  - **Token Storage**: Credentials are persisted to the OS native keyring via the `keyring` library (`service_name="google-colab-cli"`, `username="oauth_token"`) after the initial flow. If the keyring is inaccessible or locked, `_run_remote_flow` is invoked for the current run and a warning is printed to stderr. A legacy `~/.config/colab-cli/token.json` is migrated into the keyring on first use and deleted after a successful keyring write, or immediately if the keyring already holds a token.
138
156
  - Use `requests` for robust HTTP interactions and `pydantic` for schema validation.
139
157
  - Handle authentication headers (likely `Authorization: Bearer <token>` or cookies).
@@ -150,6 +168,9 @@ TDD is mandatory for all session management features.
150
168
  ### 1. Mock Assignment API
151
169
  - **Test Case**: Verify `colab new` correctly parses a `PostAssignmentResponse` and stores it in the local `StateStore`.
152
170
  - **Test Case**: Verify `colab stop` sends a `POST` request with the correct XSRF token to the unassign endpoint.
171
+ - **Test Case**: Verify `colab stop -s <endpoint>` unassigns an orphaned server-side assignment matched via `list_assignments()` (and removes any local record pointing to that endpoint).
172
+ - **Test Case**: Verify `colab stop -s <missing>` prints a not-found error and exits with status 1 without calling unassign.
173
+ - **Test Case**: Verify `colab stop -s <name> --all` prints an error to stderr and exits with status 2 without syncing or unassigning sessions.
153
174
  - **Test Case**: Verify that the path provided via `-c` is correctly passed to the authentication flow.
154
175
  - **Mocking**: Use `unittest.mock` to intercept `requests.Session.request` and return simulated XSSI-prefixed JSON payloads matching the HAR traces.
155
176
 
@@ -1,5 +1,11 @@
1
1
  ---
2
2
  log:
3
+ 2026-11-27: Fixed `colab exec` exiting 1 after `sys.exit()` / `sys.exit(None)` / `sys.exit(0)`. A leftover `any(output_type == "error")` check after `_exit_code_from_outputs` re-flagged the `SystemExit` error output as a failure, overriding the CPython mapping; `_exit_code_from_outputs` already returns 1 for every non-`SystemExit` error, so the check was removed. `test_cli_exec_systemexit_zero_exits_zero_silently` now passes.
4
+
5
+ 2026-11-23: Shared `colab run`'s CPython `SystemExit` handling (`_exit_code_from_outputs`, `_make_script_output_hook`) with `colab exec` and muted IPython's `"To exit: use ..."` warning during `exec` setup. Because a persistent IPython kernel catches `SystemExit` and emits it as `output_type == "error"` to avoid killing the kernel process, treating every kernel error output as exit 1 wrongly failed scripts that call `sys.exit(0)` (e.g. `argparse --help`, `unittest.main()`) and collapsed `sys.exit(N)` codes into 1.
6
+
7
+ 2026-11-23: `colab exec` now exits 1 when executed code produces a kernel `error` output (after recording history and saving `*_output.ipynb` for notebooks, stopping further notebook cells) (#250).
8
+
3
9
  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.
4
10
 
5
11
  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.
@@ -7,9 +13,11 @@ log:
7
13
  2026-06-04: Bumped the default `--timeout` for `colab exec` from 10s to 30s (and the matching `colab run` default) so brief silent tasks are less likely to hit a premature `TimeoutError`. Explicit `--timeout` overrides are unaffected.
8
14
 
9
15
  2026-10-24: `--timeout` for `colab exec` (and `colab run`) is now an idle limit: execution fails only after that many seconds without output, so code that keeps printing is never cut off, and `--timeout 0` means no limit. On 0.8.0/0.9.0 the old deadline was never enforced, so code that is silent for longer than `--timeout` now fails where it used to complete. `colab repl` and `colab install`, which pass no timeout, wait until execution finishes, or until the kernel dies or restarts. None of them busy-loop while waiting. `colab auth` and `colab drivemount` are unchanged. See #183.
16
+
17
+ 2026-10-29: Removed the `colab console` subcommand and its `/colab/tty` transport (`console.py`, its tests, and `integration/repro_piped_console/`). Use `colab ssh -s NAME` for an interactive shell and `colab ssh -s NAME -- CMD` for one-shot commands, or pipe `!`-prefixed shell commands to `colab exec` where ssh can't work.
10
18
  ---
11
19
 
12
- # Design: Execution and Interactive Interaction (`repl`, `exec`, `console`)
20
+ # Design: Execution and Interactive Interaction (`repl`, `exec`)
13
21
 
14
22
  ## Overview
15
23
  Execution involves sending Python code (or shell commands) to the Jupyter kernel running on the Colab VM and processing the stream of output messages.
@@ -31,12 +39,11 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel
31
39
  - If file path is remote: Execute `!python <path>`.
32
40
  - **Multi-Modal Output**: Handle `display_data` messages (e.g., `image/png`, `text/html`). For the CLI, we'll save images to temporary files and print their paths, or if the terminal supports it (e.g., iTerm2), inline them.
33
41
  - **Timeout Configuration**: Exposes a `--timeout` flag (default 30s): the longest silence allowed before execution fails. Raise it so long-running silent tasks (like model compilation or data downloading) are not prematurely killed; `0` means no limit.
34
-
35
- ### 3. Console (`colab console`)
36
- - **Implementation**: Connects directly to the backend terminal endpoint (`/colab/tty`) via WebSockets using `websocket-client`.
37
- - **Interactive**: Bypasses the Jupyter kernel entirely to provide a raw, PTY-backed bash session on the Colab VM.
38
- - **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.
39
- - **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.
42
+ - **Error & `SystemExit` Semantics**:
43
+ - Any uncaught exception (`ValueError`, `SyntaxError`, etc.) causes `colab exec` to exit with status `1`
44
+ - Any executed code block that returns an `output_type == "error"` causes colab to exit with status `11
45
+ - Any exit code stops remaining cells in a `.ipynb` notebook while still writing `*_output.ipynb`.
46
+ - **Why `SystemExit` is handled specially**: Unlike CPython—where `sys.exit(...)` terminates the process directly—an IPython/Jupyter kernel must stay alive across executions, so it catches `SystemExit` and reports it as `output_type == "error"` (`ename == "SystemExit"`), accompanied by an interactive `"An exception has occurred, use %tb..."` banner and `"To exit: use 'exit', 'quit', or Ctrl-D."` `UserWarning`. Treating `SystemExit` like an uncaught exception breaks well-formed scripts passed to `colab exec -f script.py` (such as `argparse --help`, `unittest.main()`, or early-exit guards calling `sys.exit(0)`) and loses custom integer exit codes (`sys.exit(N)`). `colab exec` therefore shares `colab run`'s CPython mapping: `sys.exit()` / `sys.exit(None)` / `sys.exit(0)` exit `0` silently, `sys.exit(N)` exits `N` silently, and `sys.exit("msg")` prints `msg` to `stderr` and exits `1`.
40
47
 
41
48
  ## Implementation Details
42
49
  - **Kernel Management**: `ColabRuntime` (from `colab-agent`) already handles message signing and message types.
@@ -50,10 +57,10 @@ TDD is mandatory for all execution features.
50
57
  - **Test Case**: Verify `ColabRuntime` correctly sends an `execute_request` message over the websocket.
51
58
  - **Test Case**: Verify `iopub.stream` messages are correctly handled and printed to `stdout` in real-time.
52
59
  - **Test Case**: Verify `display_data` (specifically `image/png`) triggers the correct local handling (saving or display).
60
+ - **Test Case**: Verify `colab exec` exits with status 1 when the kernel emits an `error` output, and halts multi-cell `.ipynb` execution at the failing cell while still saving `*_output.ipynb`.
61
+ - **Test Case**: Verify `colab exec` applies CPython `SystemExit` semantics (`sys.exit(0)`/`None` → `0` silently, `sys.exit(N)` → `N`, `sys.exit("msg")` → prints `msg` to `stderr` and exits `1`) without IPython `%tb` or exit-warning noise.
53
62
 
54
63
  ### 2. TTY and Piping
55
64
  - **Test Case**: Mock `sys.stdin.isatty()` to verify `colab repl` correctly switches between interactive mode and one-shot piped execution.
56
65
  - **Test Case**: Verify large piped inputs are handled without buffer overflow or truncation.
57
- - **Test Case**: `colab console` with piped stdin sends `exit\n` and calls `ws.close()` on EOF (regression: previously sent `\x04` only and hung).
58
- - **Test Case**: `colab console` in TTY mode does not synthesize an exit on EOF (the user owns the session lifecycle).
59
66
  - **Test Case**: `print_kitty` is a no-op when `sys.stdout.isatty()` is false (regression: previously emitted ANSI/base64 into pipes and files).
@@ -32,6 +32,7 @@ File management on the Colab VM will be implemented using the Jupyter Contents A
32
32
  - **API**: `GET /api/contents/<remote_path>?content=1` (as seen in HAR).
33
33
  - **Response**: JSON with `content` field.
34
34
  - **Handling**: Decodes content based on `format` (`base64`, `json`, or plain `text`) and saves it locally.
35
+ - **Timeouts**: Every Contents API request uses a `(connect, read)` timeout of `(30, 300)` seconds. The read timeout bounds the wait between bytes, not the whole transfer, so large files still finish while a dropped connection fails with an error instead of hanging `ls`, `rm`, `upload`, `download`, or `edit` forever.
35
36
 
36
37
  ### 4. Deleting Files (`colab rm`)
37
38
  - **API**: `DELETE /api/contents/<remote_path>`.
@@ -1,9 +1,15 @@
1
1
  ---
2
2
  log:
3
+ 2026-11-30: `_run_with_timeout` in `auth.py` now sets a `cancel_event` on timeout so keyring worker threads that unblock from `_check_linux_keyring_locked` after timing out skip stale lock warnings and abort before calling `get_password`/`set_password`/`delete_password`. Unit tests now enforce `keyring.backends.null.Keyring` (and `PYTHON_KEYRING_BACKEND`) for the entire pytest process via `pytest_configure` in `tests/conftest.py` instead of restoring the host OS keyring between tests, and timeout tests in `tests/test_auth.py` join spawned daemon threads before fixture teardown.
4
+ 2026-11-23: Added standalone version-gated update notices fetched from a movable GitHub tag (`notices_url`, defaulting to `https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json`) and cached as `update_notices` in `Settings`. Matching PEP 440 `affects` rules display via `announce_notices` independently of whether PyPI reports a newer version, HTTP 404 silently clears retracted notices without warning, transient errors preserve cached notices, and ANSI/control sequences are stripped.
5
+ 2026-11-19: Added `colab logout` to clear stored OAuth2 credentials across all chained OS keyring backends (disambiguating missing entries from real keychain/KWallet failures and warning on `NoKeyringError`) and legacy `~/.config/colab-cli/token.json` without revoking Google Cloud SDK's shared OAuth client grant. Under `--auth=adc`, prints `gcloud auth application-default revoke`. Also invalidates cached runtime proxy tokens in `sessions.json` (warning if local sessions remain), resets cached API capability flags in `settings.json`, and suppresses the daily auto-update banner.
6
+ 2026-11-13: `_get_adc_credentials` in `auth.py` now catches `DefaultCredentialsError` from `google.auth.default()` so missing local ADC prints the 4-scope `gcloud auth application-default login` command and exits 1 instead of surfacing `google-auth`'s stock unscoped setup message. Updated scope documentation to clarify that both `colaboratory` and `userinfo.email` are required by `colab.research.google.com`.
3
7
  2026-11-07: Optimized `_get_adc_credentials` in `auth.py` to stub `google.auth._cloud_sdk.get_project_id` around `google.auth.default()`. When ADC user credentials lack a `quota_project_id`, `google-auth` otherwise spawns `gcloud config get-value project` on every CLI invocation to resolve a `project_id` that `_get_adc_credentials` immediately discards (`_`).
4
8
  2026-11-04: `colab drivemount` now opens the Drive consent URL in the system browser (`utils.open_url_in_browser`, also used by `colab pay`/`colab url --open`) instead of only printing it. The URL is still printed first, and a missing browser opener (SSH, containers, CI) is treated as normal: the flow keeps waiting for the user exactly as before. The prompt moved into `commands/automation.py::show_drive_auth_url` so it can be unit-tested.
9
+ 2026-11-04: `colab drivemount` now handles credentials-propagation failures instead of dumping the HTTP body. Responses are parsed defensively (HTML/empty bodies no longer raise out of the websocket hook), an authentication prompt is only shown when the server actually returns an `unauthorized_redirect_uri`, and failures print the status plus the multi-account guidance (select the account from `colab whoami`) while logging the raw body to history. The intercepted kernel request is answered on failure too, so the command exits promptly instead of hanging until its 600s timeout.
5
10
  2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to inspect the active Linux `SecretService` collection via `secretstorage` before `get_password`/`set_password`, warning immediately when the keyring is locked so users know why the CLI is waiting on an unlock prompt (and suggesting `--auth=adc`).
6
11
  2026-10-29: Session history files are created readable only by the owner (0600), and existing ones are tightened to 0600 whenever the history logger starts.
12
+ 2026-10-22: Added hidden `colab test-public-api` subcommand and `Client.check_api_access()` to probe both `colaboratory.googleapis.com/v1beta/runtimes` and `colab.research.google.com/tun/m/assignments`, caching `public_api_supported` and `tunnel_api_supported` in `Settings` for targeted HTTP 401/403 error hints.
7
13
  2026-10-21: Migrated OAuth2 token persistence in `auth.py` from `~/.config/colab-cli/token.json` to the OS native password storage via the `keyring` library (`KEYRING_SERVICE_NAME = "google-colab-cli"`, `KEYRING_USERNAME = "oauth_token"`). When the keyring is empty, locked, or inaccessible, `_run_remote_flow` is invoked; keyring read/write failures print a warning to stderr without failing the command. An existing `~/.config/colab-cli/token.json` (`LEGACY_TOKEN_PATH`) is used when the keyring has no token, copied into the keyring, and deleted only after the keyring write succeeds; it is also deleted when the keyring already holds a token.
8
14
  2026-09-25: Cleaned up references to keep-alive background daemon and pre-flight pings. VM liveness is automatically maintained by the Colab backend based on active kernel activity.
9
15
  2026-08-10: Added `colab usage` for account-level compute-unit rate/balance via `GET /tun/m/ccu-info` on the session backend (same bearer token as `colab new`).
@@ -75,15 +81,15 @@ allowing the core `Client` to remain authentication-agnostic — it only sees a
75
81
  ### Required Scopes
76
82
 
77
83
  The CLI talks to the Colab session backend at `colab.research.google.com`
78
- for assignment, unassignment, CCU info, and the contents API. The `userinfo.email` scope is
79
- sufficient for this host.
84
+ for assignment, unassignment, CCU info, and the contents API. Both the
85
+ `colaboratory` and `userinfo.email` scopes are required for this host.
80
86
 
81
- How each provider supplies the scope:
87
+ How each provider supplies the scopes:
82
88
 
83
- - **`oauth2`**: `PUBLIC_SCOPES` already includes `colaboratory`, so the
84
- InstalledAppFlow consent screen lists it. Existing cached tokens in the
85
- keyring that were minted before a scope change must be cleared to trigger a
86
- fresh consent flow.
89
+ - **`oauth2`**: `PUBLIC_SCOPES` includes both `colaboratory` and
90
+ `userinfo.email`, so the InstalledAppFlow consent screen lists them.
91
+ Existing cached tokens in the keyring that were minted before a scope
92
+ change must be cleared to trigger a fresh consent flow.
87
93
  - **`adc`**: `google.auth.default(scopes=PUBLIC_SCOPES)` is called, and for
88
94
  credential subclasses that support `with_scopes` (service accounts,
89
95
  GCE/GKE metadata, impersonated) we re-apply via `creds.with_scopes(...)`.
@@ -91,20 +97,16 @@ How each provider supplies the scope:
91
97
  `scopes=` kwarg AND raise `NotImplementedError` on `with_scopes`; those
92
98
  users must explicitly re-authenticate:
93
99
 
94
- ```
100
+ ```bash
95
101
  gcloud auth application-default login \
96
- --scopes=openid,\
97
- https://www.googleapis.com/auth/cloud-platform,\
98
- https://www.googleapis.com/auth/userinfo.email,\
99
- https://www.googleapis.com/auth/colaboratory
102
+ --scopes=openid,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/colaboratory
100
103
  ```
101
104
 
102
- `userinfo.email` is required for the session backend at
103
- `colab.research.google.com` (otherwise assign/unassign/sessions
104
- return HTTP 401); `colaboratory` is retained for forward compatibility and
105
- other Colab features; `openid` and `cloud-platform` are mandated by
106
- `gcloud` itself (`gcloud auth application-default login` rejects scope
107
- lists that omit `cloud-platform` with `Invalid value for [--scopes]`).
105
+ `colaboratory` and `userinfo.email` are required for the session backend at
106
+ `colab.research.google.com` (otherwise assign/unassign/sessions return HTTP
107
+ 401); `openid` and `cloud-platform` are mandated by `gcloud` itself
108
+ (`gcloud auth application-default login` rejects scope lists that omit
109
+ `cloud-platform` with `Invalid value for [--scopes]`).
108
110
 
109
111
  ## Approach
110
112
 
@@ -148,6 +150,16 @@ How each provider supplies the scope:
148
150
  `jupyter_kernel_client` default raising `TimeoutError` mid-flow, this
149
151
  subcommand passes `timeout=INTERACTIVE_AUTOMATION_TIMEOUT_SEC` (600s) to
150
152
  `ColabRuntime.execute_code`. Same applies to `colab auth`.
153
+ - **Multi-account browsers**: Drive propagation is attributed to the Google
154
+ account that approves the consent page, which may not be the account the
155
+ CLI authenticated as. If the browser shows an account chooser, select the
156
+ account reported by `colab whoami`; approving with another account fails
157
+ with HTTP 400 even though the consent itself succeeded. A private window
158
+ only helps if it is already signed in to that account.
159
+ - **Failure reporting**: errors from the propagation endpoint never echo the
160
+ raw response body (often HTML). The CLI prints the status, points at
161
+ `colab whoami`, logs the body to the history file, and answers the waiting
162
+ kernel request so `drivemount` exits instead of hanging until its timeout.
151
163
 
152
164
  ### 4. Logging and Notebook Capture (`colab log`)
153
165
 
@@ -185,48 +197,70 @@ How each provider supplies the scope:
185
197
  Git commit hash using `git rev-parse --short HEAD`.
186
198
  - Dynamic versioning is supported in the build system via `hatch-vcs`.
187
199
 
188
- ### 8. Auto-Update (`colab update`)
200
+ ### 8. Auto-Update & Standalone Notices (`colab update`)
189
201
 
190
- - **Action**: Check if a new version of the Colab CLI is available.
191
- - **Auto-check**: The CLI automatically checks for updates once every 24 hours
192
- during the execution of any command. Independently, the cached
193
- `latest_version` (see below) is consulted on **every** invocation so the
194
- upgrade banner remains visible between fetches without requiring a network
202
+ - **Action**: Check if a new version of the Colab CLI or any standalone
203
+ version-gated advisory notice is available.
204
+ - **Auto-check**: The CLI automatically fetches PyPI and the standalone
205
+ notices feed once every 24 hours during the execution of any non-suppressed
206
+ command. Independently, the cached `latest_version` and `update_notices`
207
+ are consulted on **every** invocation so upgrade and standalone notice
208
+ banners remain visible between fetches without requiring a network
195
209
  round-trip.
196
210
  - **Suppressed subcommands**: To keep machine-parseable output clean, the
197
- daily fetch and the cached banner are suppressed for `update` (which
198
- runs its own check), `version`, `log`, `pay`, `url`, `help`, and
199
- `whoami`. The list lives as `_AUTO_UPDATE_SUPPRESSED` in the global
200
- Typer callback in `cli.py`.
201
- - **Manual-check**: `colab update` forces a check and prints the status.
211
+ daily fetch and the cached banners are suppressed for subcommands listed in
212
+ `_AUTO_UPDATE_SUPPRESSED` (and non-TTY `ssh`) in the global Typer callback
213
+ in `cli.py`.
214
+ - **Manual-check**: `colab update` forces a check and prints the status plus
215
+ any matching standalone notices.
202
216
  - **Implementation**:
203
217
  - Fetches a PyPI-style JSON document from a configurable `update_url`
204
- (default: `https://pypi.org/pypi/google-colab-cli/json`) and reads
205
- `info.version`.
206
- - Compares the fetched version with the current CLI version using
207
- PEP 440 / semantic versioning, falling back to string equality when a
208
- version is unparseable.
218
+ (default: `https://pypi.org/pypi/google-colab-cli/json`).
219
+ - Selects latest stable public releases (`_parse_stable_version`) from
220
+ `releases` with fallback to `info`.
221
+ - Compares the candidate with the current CLI version.
222
+ - Independently fetches standalone notices from `notices_url` (default:
223
+ `https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json`;
224
+ managed via `tools/notices.py`, see [07_update_notices.md](07_update_notices.md)).
225
+ - Notice payload schema: a JSON array `[{"affects": "<1.0.0", "message": "..."}]`
226
+ (or `{"notices": [...]}`). Each entry's `affects` is evaluated against
227
+ the installed version with `packaging.specifiers.SpecifierSet(..., prereleases=True)`.
228
+ ANSI escape codes and control characters are stripped, messages are
229
+ truncated to 500 characters, and at most 3 deduplicated notices are
230
+ printed.
209
231
  - Persists the following fields in `~/.config/colab-cli/settings.json`:
210
- - `update_url`: source configuration.
232
+ - `update_url`: PyPI JSON source configuration.
233
+ - `notices_url`: standalone notices JSON source configuration.
211
234
  - `last_check`: timestamp of the last fetch (drives the daily
212
235
  throttle).
213
236
  - `enable_update_check`: master switch for both the daily fetch and
214
- the cached banner.
215
- - `latest_version`: highest version observed during the most
216
- recent successful check. Updated whenever a strictly-newer
217
- version is observed (never downgraded), and preserved verbatim
218
- across failed checks so transient network issues do not erase
219
- the cache.
220
- - **Notification**: If a new version is found, a non-intrusive message is
221
- printed to the console with a `Run 'pip install --upgrade google-colab-cli' to
222
- update.` hint. On Linux and macOS platforms where `--install` self-update is supported,
223
- an additional hint `You can run 'colab update --install' to upgrade in place.`
224
- is displayed above the pip/uv install command. The cached banner shown between
225
- fetches uses the generic `Run 'colab update' to update.` hint.
237
+ cached upgrade/notice banners.
238
+ - `latest_version`: highest stable version observed during the most
239
+ recent successful check. Updated whenever a strictly-newer stable
240
+ version is observed (never downgraded), preserved across failed
241
+ checks when valid, and self-healed (cleared or replaced) if a stale
242
+ prerelease or invalid string is present.
243
+ - `update_notices`: list of `{affects, message}` entries from the
244
+ most recent successful notices fetch. Overwritten on HTTP 200 or
245
+ cleared to `[]` on HTTP 404 (absent/deleted `notices` tag, with no
246
+ warning printed), and preserved across transient network failures.
247
+ `affects` is re-evaluated on every invocation so cached notices
248
+ stop appearing immediately once the user upgrades past the range.
249
+ - **Notification**:
250
+ - If a new stable version is found, a non-intrusive banner is printed with a
251
+ `Run 'pip install --upgrade google-colab-cli' to update.` (or `uv tool
252
+ install -U`) hint, plus `You can run 'colab update --install' to upgrade
253
+ in place.` on Linux and macOS. Cached banners between fetches use the
254
+ generic `Run 'colab update' to update.` hint.
255
+ - Any matching standalone notices are printed via `announce_notices` as
256
+ `[colab] Notice: <message>`, **even when the CLI is already on the
257
+ latest PyPI version**. When both an upgrade banner and notices are
258
+ shown unsolicited, the `"enable_update_check": false` silence hint is
259
+ printed only once at the bottom.
226
260
  - **Self-install (`--install`)**: An opt-in `--install` flag (default
227
261
  `False`) makes `colab update` upgrade the CLI in place (**Linux and macOS**).
228
262
  It detects how the CLI was installed:
229
- - If `sys.executable` contains `/uv/tools` (indicating it was installed via
263
+ - If `sys.executable` contains `/uv/tools/` (indicating it was installed via
230
264
  `uv tool install`), it runs `uv tool install -U google-colab-cli`.
231
265
  - Otherwise, runs `pip install -U google-colab-cli` using `sys.executable`
232
266
  to ensure the upgrade lands in the same interpreter.
@@ -291,6 +325,23 @@ How each provider supplies the scope:
291
325
  installed), it falls back to reading the files from the project root.
292
326
  - Prints the content to stdout.
293
327
 
328
+ ### 11. Public & Tunnel API Probe (`colab test-public-api`)
329
+
330
+ - **Action**: Hidden diagnostic command (`hidden=True`, suppressed from auto-update banner) that runs `state.client.check_api_access()`.
331
+ - **Implementation**:
332
+ - Issues read-only GET probes to `https://colaboratory.googleapis.com/v1beta/runtimes` and `https://colab.research.google.com/tun/m/assignments`.
333
+ - Persists `public_api_supported` and `tunnel_api_supported` booleans in `~/.config/colab-cli/settings.json` and prints `OK` or `FAILED` for each backend.
334
+ - When `Client._issue_request` receives HTTP 401/403, it updates the failed backend's cached flag and appends a targeted remediation hint (`--no-public-api` or `--public-api`) if the alternate backend is cached as supported.
335
+
336
+ ### 12. Sign Out (`colab logout`)
337
+
338
+ - **Action**: Clear locally cached OAuth2 credentials and cached runtime proxy tokens so the user can sign out or switch accounts on the next command.
339
+ - **Implementation**:
340
+ - Under `--auth=oauth2` (default), deletes `(google-colab-cli, oauth_token)` across all chained keyring backends (disambiguating missing entries from real keychain/KWallet errors and warning on stderr on `NoKeyringError`) and removes any leftover `~/.config/colab-cli/token.json`, attempting both stores even if one errors. Does not call Google's `/revoke` endpoint because the bundled OAuth client is shared with Google Cloud SDK.
341
+ - Under `--auth=adc`, leaves local ADC untouched and directs the user to `gcloud auth application-default revoke`.
342
+ - Blanks cached `token` and `token_expires_at` on local `sessions.json` entries (so `-s NAME` cannot bypass re-auth with stale proxy tokens), resets cached `public_api_supported`/`tunnel_api_supported` flags in `settings.json`, and warns on stderr if local sessions exist.
343
+ - Suppressed from the daily auto-update banner (`_AUTO_UPDATE_SUPPRESSED`).
344
+
294
345
  ## Implementation Details
295
346
 
296
347
  - **Code Injection**: Use a standard `run_code(session, code)` helper via
@@ -343,3 +394,8 @@ TDD is mandatory for all automation features.
343
394
  - **Test Case**: Verify `colab AGENT` prints the same content.
344
395
  - **Test Case**: Verify fallback to local `README.md` file when metadata is not available.
345
396
  - **Test Case**: Verify error exit when both metadata and local file are unavailable.
397
+
398
+ ### 5. `logout` Account Sign-Out
399
+
400
+ - **Test Case**: Verify `clear_oauth_token()` removes both keyring entries (including across `ChainerBackend` backends) and `LEGACY_TOKEN_PATH`, handles concurrent `FileNotFoundError` and macOS `NotFound` cleanly, and re-raises locked/denied/cancelled `PasswordDeleteError` and `OSError` without skipping the remaining store.
401
+ - **Test Case**: Verify `colab logout` invalidates cached runtime tokens in `sessions.json`, resets cached capability flags in `settings.json`, suppresses auto-update checks, emits warnings/errors to stderr, and prints the `gcloud` hint under `--auth=adc`.