colab-cli

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Colab CLI

Colab CLI

Use the
colab
command to run local Python work on remote Google Colab runtimes. Prefer this skill when the user wants Colab compute, GPUs, TPUs, notebook logs, remote execution, or agent-driven ML jobs.
使用
colab
命令在远程 Google Colab runtime 上运行本地 Python 任务。 当用户需要 Colab 算力、GPU、TPU、notebook 日志、 远程执行或 Agent 驱动的 ML 任务时,优先使用此 skill。

Install And Verify

安装与验证

Check the local tool first:
bash
colab version
colab --help
If missing, install it with
uv
:
bash
uv tool install google-colab-cli
先检查本地工具:
bash
colab version
colab --help
如果尚未安装,请使用
uv
进行安装:
bash
uv tool install google-colab-cli

Current release and remaining hardening caveats

当前版本与尚存的加固注意事项

Guidance was revalidated on 2026-10-01 against upstream
main
and the user fork branch
all-fixes/persistent-drive-2026-10-01
. That branch is based on current upstream
a84e094
and adds the remaining hardening plus persistent DriveFS. If
colab drive-mount --help
succeeds, prefer the fork workflow below and do not apply stock-only caveats as if they were unfixed.
Upgrade old 0.7.2 installs before troubleshooting their known dependency and runtime-token failures:
bash
colab update --install
colab version
Version 0.7.4 fixes the 0.7.2
jupyter-kernel-client==0.8
execution breakage and adds automatic runtime-proxy token refresh. Do not keep the old
jupyter-kernel-client>=0.9,<1
workaround or the old "~1 hour proxy token expiry" recovery procedure once 0.7.4+ is installed.
Current upstream
main
also pins
websocket-client>=1.6
; the v0.7.4 tag still declared
>=1.0
. If an exact 0.7.4 environment resolves an older WebSocket client and
colab ssh
loses the server's HTTP 400 reason, upgrade that dependency inside the same environment as the
colab
executable:
bash
uv pip install --python ~/.local/share/uv/tools/google-colab-cli/bin/python \
  "websocket-client>=1.6"
Several local-security and reliability findings remain in current upstream. Treat
~/.config/colab-cli/token.json
,
sessions.json
,
colab.log
, and
history/*.jsonl
as sensitive and never publish them unredacted. On multi-user machines, restrict them to the current user:
bash
chmod 700 ~/.config/colab-cli ~/.config/colab-cli/history 2>/dev/null || true
chmod 600 ~/.config/colab-cli/{token.json,sessions.json,colab.log,settings.json} 2>/dev/null || true
chmod 600 ~/.config/colab-cli/history/*.jsonl 2>/dev/null || true
Do not use
--env
for secrets on stock upstream: environment values can be embedded in executed Python/history. Interactive stdin replies are also stored in history. Use proper remote secret-loading mechanisms and review history before sharing it.
The CLI bundles
colab skill
and
colab readme
, but version-sensitive behavior should be verified against the installed binary and exact source.
oauth2
remains the parser default in v0.7.4/current main.
本指南于 2026-10-01 基于上游
main
和用户 fork 分支
all-fixes/persistent-drive-2026-10-01
重新验证。该分支基于当前上游
a84e094
,补充了其余加固措施及持久化 DriveFS。如果
colab drive-mount --help
成功,请优先采用下述 fork 工作流,不要把仅适用于原版上游的注意事项当作尚未修复的问题来套用。
在排查旧版 0.7.2 安装的已知依赖和 runtime-token 故障之前,请先升级:
bash
colab update --install
colab version
0.7.4 版本修复了 0.7.2 中
jupyter-kernel-client==0.8
导致的执行中断,并增加了 runtime proxy token 自动刷新。安装 0.7.4+ 后,不要再使用旧的
jupyter-kernel-client>=0.9,<1
变通方案,也不要继续沿用旧的“约 1 小时 proxy token 过期”恢复流程。
当前上游
main
还会锁定
websocket-client>=1.6
;v0.7.4 tag 仍声明为
>=1.0
。如果精确使用 0.7.4 的环境解析到了较旧的 WebSocket client,且
colab ssh
丢失服务器的 HTTP 400 reason,请在
colab
可执行文件所在的同一环境中升级该依赖:
bash
uv pip install --python ~/.local/share/uv/tools/google-colab-cli/bin/python \
  "websocket-client>=1.6"
当前上游仍存在若干本地安全性和可靠性问题。请将
~/.config/colab-cli/token.json
、
sessions.json
、
colab.log
和
history/*.jsonl
视为敏感文件,绝不要未经脱敏就发布它们。在多用户机器上,应将其权限限制为仅当前用户可访问:
bash
chmod 700 ~/.config/colab-cli ~/.config/colab-cli/history 2>/dev/null || true
chmod 600 ~/.config/colab-cli/{token.json,sessions.json,colab.log,settings.json} 2>/dev/null || true
chmod 600 ~/.config/colab-cli/history/*.jsonl 2>/dev/null || true
在原版上游中,不要使用
--env
传递 secret:环境变量值可能会嵌入已执行 Python 或 history 中。交互式 stdin 回复也会存储在 history 中。请使用恰当的远程 secret 加载机制,并在共享 history 前进行检查。
CLI 内置了
colab skill
和
colab readme
,但对版本敏感的行为应根据已安装的 binary 和确切源码进行验证。在 v0.7.4 和当前 main 中,
oauth2
仍是 parser 默认值。

Mental Model

心智模型

  • A session is a live Jupyter kernel on a rented Colab VM.
    colab new
    allocates compute;
    colab stop
    releases it.
  • Kernel state persists across
    colab exec
    and piped
    colab repl
    calls in the same session. Imports, variables, and functions remain until
    colab restart-kernel
    or
    colab stop
    .
  • Execution starts in
    /content
    . Prefer absolute
    /content/...
    paths for remote files so later
    ls
    ,
    download
    , and cleanup commands are unambiguous.
  • Commands that access the Colab control plane authenticate on demand, perform their operation, and exit. Pure informational commands such as
    version
    ,
    help
    , and
    readme
    do not need control-plane authentication. Current upstream runs no client-side keep-alive daemon; backend liveness depends on kernel activity and Colab policy.
  • session 是租用 Colab VM 上正在运行的 Jupyter kernel。
    colab new
    分配算力;
    colab stop
    释放算力。
  • 在同一个 session 中,kernel 状态会在
    colab exec
    和通过管道输入的
    colab repl
    调用之间持续保留。import、变量和函数会一直存在,直到执行
    colab restart-kernel
    或
    colab stop
    。
  • 执行工作目录从
    /content
    开始。远程文件优先使用绝对路径
    /content/...
    ,以确保后续
    ls
    、
    download
    和清理命令的路径明确无歧义。
  • 访问 Colab control plane 的命令会按需进行身份验证、执行相应操作后退出。
    version
    、
    help
    和
    readme
    等纯信息命令不需要 control plane 身份验证。当前上游不会在客户端运行 keep-alive daemon;后端存活性取决于 kernel 活跃度和 Colab 策略。

Agent Rules

Agent 规则

  • Always make a lifecycle plan before allocating compute: session name, hardware, commands to run, artifacts to retrieve, and cleanup command.
  • Use an explicit session name with
    -s <name>
    for
    colab new
    , multi-step sessions, and
    colab run --keep
    . Plain one-shot
    colab run
    may safely use its generated ephemeral name because it tears the runtime down itself.
  • Prefer
    colab run
    for one-shot jobs because it provisions, executes, and stops the runtime automatically.
  • Use a named session for multi-step work:
    colab new -s <name>
    , then
    colab install
    ,
    colab exec
    ,
    colab download
    ,
    colab log
    ,
    colab stop
    .
  • colab run -s <name>
    does not attach to an existing session:
    -s
    only labels the fresh ephemeral VM that
    run
    provisions and releases. To execute code on an existing session, use
    colab exec -s <name>
    .
  • Do not leave paid resources running. Run
    colab stop -s <name>
    when done, then verify with
    colab sessions
    .
  • Never start unpiped
    colab repl
    or
    colab console
    from a non-interactive agent shell. They are TTY-oriented. Use
    colab exec
    ,
    colab run
    , or pipe stdin into the interactive command.
  • Treat unpiped
    colab repl
    , unpiped
    colab console
    ,
    colab auth
    , and stock interactive
    colab drivemount
    as user-interactive. On the unified fork,
    colab drive-mount login
    needs the user once; subsequent
    colab drive-mount -s NAME
    and
    colab drivemount -s NAME
    are agent-runnable when persistent credentials are configured.
  • Do not edit
    ~/.config/colab-cli/sessions.json
    by hand. Use CLI commands. A missing local name does not prove its VM stopped: before reallocating after
    Session not found
    , reconcile server-side assignments with
    colab sessions
    ; an orphan can remain allocated and billable.
  • Do not upgrade/reinstall/switch Colab CLI or change Drive transport underneath a valuable live job. Prefer checkpoint -> collect -> stop/verify -> upgrade -> new session. If unavoidable, preserve a private name-to-endpoint recovery record first. See
    references/session-resilience-2026-10-01.md
    .
  • For live probes, remember that
    colab new
    and
    colab run
    can allocate real compute units. Clean up even after failed jobs.
  • For parallel agents or risky probes, isolate session state with
    --config /tmp/<name>.json
    .
  • 分配算力前,务必制定生命周期计划:session 名称、硬件、要运行的命令、要取回的产物以及清理命令。
  • 对于
    colab new
    、多步骤 session 和
    colab run --keep
    ,使用
    -s <name>
    指定明确的 session 名称。普通的一次性
    colab run
    可以安全使用自动生成的临时名称,因为它会自行释放 runtime。
  • 对于一次性任务,优先使用
    colab run
    ,因为它会自动配置、执行并停止 runtime。
  • 多步骤工作使用命名 session:
    colab new -s <name>
    ,然后依次使用
    colab install
    、
    colab exec
    、
    colab download
    、
    colab log
    、
    colab stop
    。
  • colab run -s <name>
    不会附加到已有 session:
    -s
    只会为
    run
    创建并释放的临时 VM 命名。要在已有 session 上执行代码,请使用
    colab exec -s <name>
    。
  • 不要让付费资源持续运行。完成工作后运行
    colab stop -s <name>
    ,再通过
    colab sessions
    进行验证。
  • 在非交互式 Agent shell 中,绝不要启动未通过管道提供 stdin 的
    colab repl
    或
    colab console
    。它们面向 TTY。请使用
    colab exec
    、
    colab run
    ,或通过管道将 stdin 输入交互式命令。
  • 将未通过管道提供 stdin 的
    colab repl
    、
    colab console
    、
    colab auth
    和原版上游的交互式
    colab drivemount
    视为用户交互操作。在统一 fork 上,
    colab drive-mount login
    需要用户操作一次;配置好持久化凭据后,后续的
    colab drive-mount -s NAME
    和
    colab drivemount -s NAME
    可由 Agent 运行。
  • 不要手动编辑
    ~/.config/colab-cli/sessions.json
    。应使用 CLI 命令。本地缺少某个名称并不能证明其 VM 已停止:遇到
    Session not found
    后,在重新分配资源之前,先使用
    colab sessions
    核对服务器端分配记录;孤立 session 可能仍占用资源并产生费用。
  • 不要在 valuable 活跃任务运行期间升级、重新安装或切换 Colab CLI,也不要在任务下方更改 Drive transport。优先执行 checkpoint -> collect -> stop/verify -> upgrade -> new session。如果无法避免,请先保存一份私密的 session 名称到 endpoint 映射恢复记录。参见
    references/session-resilience-2026-10-01.md
    。
  • 进行实际探测时,请记住
    colab new
    和
    colab run
    可能会分配真实的算力单元。即使任务失败,也要执行清理。
  • 对于并行 Agent 或高风险探测,使用
    --config /tmp/<name>.json
    隔离 session 状态。

Runtime Cost And Duration Best Practices

Runtime 成本与时长最佳实践

  • Treat every allocated Colab session as potentially credit-consuming until it is explicitly stopped.
  • End every persistent-session workflow with
    colab stop -s <name>
    , then run
    colab sessions
    to confirm there are no leftover active sessions. Plain
    colab run
    stops its own runtime unless
    --keep
    is set.
  • Prefer
    colab run
    for one-shot work because it stops the runtime automatically unless
    --keep
    is set.
  • Avoid
    --keep
    unless the user needs post-run inspection. If
    --keep
    is used, report the session name and stop it as soon as inspection is finished.
  • Colab runtime availability, maximum lifetime, idle timeout, accelerator access, and compute-unit consumption vary by account, subscription tier, current demand, and hardware choice. Do not promise a fixed runtime duration.
  • For long jobs, write checkpoints and logs to retrievable paths such as
    /content/outputs
    or Google Drive, and download/export artifacts before cleanup.
  • For current compute-unit consumption, run
    colab usage
    : it reads
    GET /tun/m/ccu-info
    and prints current balance, hourly usage rate, and active assignment count. Treat the numbers as point-in-time account data, not a guaranteed rate table; availability, maximum lifetime, idle timeout, and accelerator access still vary by tier, demand, and hardware. Do not hardcode old web/forum CU/hour tables as truth. A dated measured snapshot lives at
    references/cu-rate-card-2026-09-24.md
    (rates + provisioned hardware per backend, account/region-specific).
  • When the account runs out of compute units,
    colab pay
    opens the Colab subscription page to top up. It launches a browser, so treat it as user-interactive and suggest it rather than running it blindly.
  • --high-mem
    is accepted by
    colab new
    ,
    colab run
    , and
    colab ssh
    when SSH creates a runtime:
    colab new -s trainer --gpu A100 --high-mem
    . Current upstream sends
    shape=hm
    for CPU, T4, G4, H100, and A100, while L4 and TPU (
    v5e1
    ,
    v6e1
    ) omit the shape and print an ignored-flag warning because they are treated as single-shape accelerators. The binary help says high-RAM requests require "Colab Pro or Pro+ entitlement"; actual backend entitlement and availability remain account-dependent. Verify assigned shape with
    colab sessions
    . Current upstream
    colab status -s <name>
    still renders the locally cached requested shape rather than preferring backend
    machineShape
    ; the fork hardening branch fixes this.
  • 将每个已分配的 Colab session 视为可能消耗算力额度的资源,直至明确停止它。
  • 每个持久 session 工作流都以
    colab stop -s <name>
    结束,然后运行
    colab sessions
    ,确认没有遗留的活跃 session。除非设置了
    --keep
    ,普通
    colab run
    会自动停止自己的 runtime。
  • 对于一次性任务,优先使用
    colab run
    ,因为除非设置
    --keep
    ,它会自动停止 runtime。
  • 除非用户需要检查运行结果,否则避免使用
    --keep
    。如果使用了
    --keep
    ,请报告 session 名称,并在检查完成后立即停止它。
  • Colab runtime 的可用性、最长存活时间、空闲超时、accelerator 访问权限和 compute unit 消耗会因账户、订阅层级、当前需求和硬件选择而异。不要承诺固定的 runtime 时长。
  • 对于长时间任务,请将 checkpoint 和日志写入
    /content/outputs
    或 Google Drive 等可取回路径,并在清理前下载或导出产物。
  • 如需查看当前 compute unit 消耗情况,运行
    colab usage
    :它会读取
    GET /tun/m/ccu-info
    并打印当前余额、每小时使用率和活跃分配数量。请将这些数字视为某一时间点的账户数据,而不是有保证的费率表;可用性、最长存活时间、空闲超时以及 accelerator 访问权限仍会随套餐层级、需求和硬件而变化。不要将旧网站或论坛中的 CU/hour 表当作事实依据。按日期记录的实测快照位于
    references/cu-rate-card-2026-09-24.md
    (费率 + 各后端已配置的硬件,因账户或地区而异)。
  • 当账户的 compute unit 用尽时,
    colab pay
    会打开 Colab 订阅页面进行充值。它会启动浏览器,因此应将其视为用户交互操作;建议用户执行,不要盲目运行。
  • colab new
    、
    colab run
    和
    colab ssh
    均支持
    --high-mem
    (当 SSH 创建 runtime 时):
    colab new -s trainer --gpu A100 --high-mem
    。当前上游会为 CPU、T4、G4、H100 和 A100 发送
    shape=hm
    ,而 L4 和 TPU(
    v5e1
    、
    v6e1
    )不会发送该 shape,并打印“已忽略该标志”的警告,因为它们被视为单 shape accelerator。binary help 指出,高 RAM 请求需要“Colab Pro 或 Pro+ entitlement”;实际的后端 entitlement 和可用性仍取决于账户。请使用
    colab sessions
    验证分配的 shape。当前上游的
    colab status -s <name>
    仍会呈现本地缓存的请求 shape,而不会优先采用后端
    machineShape
    ;fork 加固分支修复了这一点。

Long-Running Unattended Jobs (Agent Best Practice)

长时间无人值守任务(Agent 最佳实践)

Field lessons from multi-hour, multi-session GPU benchmark campaigns. Each rule exists because skipping it cost a session setup or a silent stall.
  • Smoke before the long run, in the same session. Make the job script run a tiny end-to-end pass first (one input, one repeat, every output-writing step, including result packaging) and exit non-zero before the long part if it fails. Setup (venv, model download) is shared, so the check is nearly free.
    bash -n
    and local unit tests do not catch runtime-only failures.
  • Smoke every mode, not a sample. If the long part runs a tool in several modes or with extra flags (
    fuzz
    then
    pipeline
    ,
    --evaluate-x
    ), each one needs its own smoke twin with the same subcommand and flags; only size flags (cases, repeats, limit, output paths) may differ. A mode that was never smoked can still hit a gate or import path the smoked one skips. Enforce it mechanically (a small lint over job scripts run in CI and before launch) rather than by memory; context resets and compaction forget checklists.
  • Admit each paid job against the whole plan. Before every allocation, read
    colab usage
    fresh and start the job only if balance minus account floor, safety guard, and the caps still reserved for later mandatory jobs covers this job's cap. A per-job cap alone lets early jobs eat budget later gates need.
  • Ship an exact code snapshot and pin the runtime. Upload one
    git bundle
    (not a working-tree tar), clone it remotely, and log the commit; record
    /proc/sys/kernel/random/boot_id
    at job start and compare it when collecting, so outputs from a restarted or replaced VM (empty
    /content
    , stale markers) are detected instead of trusted.
  • Assume nothing about the image. Probe tools you call (
    command -v
    ) in the smoke step. Colab has no GNU
    /usr/bin/time
    ; time with bash
    $SECONDS
    or Python. Application safety guards (for example a "refusing full run without approval" flag) also fire at runtime: pass the intended subset flag explicitly, never disable the guard.
  • Detach, mark completion, poll the marker. Launch with
    setsid nohup bash job.sh
    from a tiny
    colab exec
    script, redirect all output to a log file, and write the exit code with
    trap 'echo "exit=$?" > $OUT/done' EXIT
    . Poll for
    $OUT/done
    at most once a minute; never hold a
    colab exec
    open for the job's whole duration.
  • Bound every poll. A
    colab exec
    call can hang for tens of minutes. Wrap pollers in
    timeout 120 colab exec ...
    (or kill the stuck call by PID) so one hung call cannot stall collection of the other sessions.
  • Collect, verify, then stop. When the marker appears, tar the output directory remotely (exclude large media), download one archive, check it exists locally, then
    colab stop
    immediately so no GPU idles.
  • Upload size. Large single uploads fail with
    400 Bad Request
    (seen at about 120 MB). Split into parts of about 40 MB (
    split -b 40M
    ), upload them, and
    cat
    them back together inside the job before verifying hashes.
  • Concurrency. GPU allocations beyond the account's concurrent limit fail with
    Allocation refused (precondition failed)
    (three G4 sessions were the limit in one account; CPU runtimes did not count). Queue the extra job and backfill it when a collector frees a slot, instead of retrying in a loop.
  • Parallel only where it is valid. Independent correctness runs can use separate sessions of the same accelerator type; A/B timing belongs in one session with interleaved arms, because separate VMs add hardware noise.
  • Hermetic Python on Colab. Preinstalled local-version wheels (for example
    torchaudio 2.11.0+cu128
    ) break
    --require-hashes
    installs and leftover packages (for example
    torchvision
    ) break imports; install locked dependencies into a fresh
    uv venv
    . The kernel exports
    MPLBACKEND=module://matplotlib_inline...
    , which a fresh venv lacks: set
    MPLBACKEND=Agg
    .
    COLAB_LANGUAGE_SERVER_PROXY
    looks like a proxy to urllib (NLTK 3.10 refuses downloads): unset it for that one command instead of disabling the library's guard.
  • Kill by PID, not pattern, locally.
    pkill -f <pattern>
    can match the agent's own shell command line and kill it.
以下经验来自多小时、多 session 的 GPU benchmark campaign。跳过其中任何规则都曾导致 session 设置失败或静默停滞。
  • 在长任务之前,于同一 session 中进行 smoke test。 让 job script 先运行一个微型端到端测试(一个输入、一次重复、每个输出写入步骤,包括结果打包),如果失败则在长任务部分开始前以非零状态退出。环境准备(venv、模型下载)可以共享,因此该检查几乎不产生额外成本。
    bash -n
    和本地 unit test 无法发现仅在 runtime 中出现的故障。
  • 测试每种模式,而不只是抽样。 如果长任务部分会以多种模式或额外 flags(
    fuzz
    后运行
    pipeline
    、
    --evaluate-x
    )运行某个工具,每种模式都需要一个使用相同子命令和 flags 的 smoke twin;只有大小相关参数(cases、repeats、limit、output paths)可以不同。未经过 smoke 的模式仍可能触发已 smoke 模式会跳过的 gate 或 import 路径。应通过机制强制执行(在 CI 中以及启动前,对 job scripts 运行一个小型 lint),而不是依靠记忆;context 重置和压缩会让人忘记 checklist。
  • 根据整个计划判断是否接纳每个付费任务。 在每次分配资源前,读取最新的
    colab usage
    ,仅当余额扣除账户余额下限(floor)、安全 guard 以及为后续必需任务预留的 cap 后,仍能覆盖本任务的 cap,才启动任务。仅设置每个任务的 cap 会让早期任务消耗掉后续 gate 所需的预算。
  • 提供精确的代码快照并固定 runtime。 上传一个
    git bundle
    (不要使用 working-tree tar),在远端 clone,并记录 commit;在任务开始时记录
    /proc/sys/kernel/random/boot_id
    并在收集结果时比较,以便检测输出是否来自已重启或被替换的 VM(
    /content
    为空、标记过期),而不是盲目信任结果。
  • 不要对镜像做任何假设。 在 smoke 步骤中探测你要调用的工具(
    command -v
    )。Colab 没有 GNU
    /usr/bin/time
    ;请使用 bash
    $SECONDS
    或 Python 计时。应用安全 guard(例如“refusing full run without approval” flag)也会在 runtime 中触发:请显式传入目标子集 flag,绝不要禁用该 guard。
  • 分离进程、标记完成并轮询标记。 通过一个很小的
    colab exec
    script 使用
    setsid nohup bash job.sh
    启动任务,将所有输出重定向到日志文件,并通过
    trap 'echo "exit=$?" > $OUT/done' EXIT
    写入 exit code。最多每分钟轮询一次
    $OUT/done
    ;切勿在整个任务期间一直保持
    colab exec
    打开。
  • 为每次轮询设置时限。
    colab exec
    调用可能会挂起数十分钟。使用
    timeout 120 colab exec ...
    包裹轮询器(或按 PID 终止卡住的调用),避免一次挂起阻塞其他 session 的结果收集。
  • 收集、验证,然后停止。 标记出现后,在远端 tar 输出目录(排除大型媒体),下载单个 archive,在本地确认其存在,然后立即执行
    colab stop
    ,避免 GPU 空闲计费。
  • 注意上传大小。 大型单次上传会失败并返回
    400 Bad Request
    (曾在约 120 MB 时出现)。请使用
    split -b 40M
    将其拆分为约 40 MB 的分片,分别上传,并在任务内部使用
    cat
    将其合并,然后验证 hash。
  • 并发。 超出账户并发限制的 GPU 分配会失败,并返回
    Allocation refused (precondition failed)
    (一个账户的 limit 是三个 G4 session;CPU runtime 不计入)。应将额外任务排队,并在 collector 释放 slot 后回填,而不是循环重试。
  • 仅在并行有效时使用并行。 相互独立的正确性运行可以使用相同 accelerator 类型的独立 session;A/B timing 应在同一 session 中交错执行,因为不同 VM 会引入硬件噪声。
  • Colab 上的 Hermetic Python。 预装的本地版本 wheel(例如
    torchaudio 2.11.0+cu128
    )会破坏
    --require-hashes
    安装,残留软件包(例如
    torchvision
    )会破坏 import;请将锁定的依赖安装到全新的
    uv venv
    中。kernel 会导出
    MPLBACKEND=module://matplotlib_inline...
    ,而全新 venv 缺少该设置:请设置
    MPLBACKEND=Agg
    。
    COLAB_LANGUAGE_SERVER_PROXY
    看起来像指向 urllib 的 proxy(NLTK 3.10 会拒绝下载):仅为该命令取消设置它,而不要禁用库的 guard。
  • 在本地按 PID 终止进程,不要按 pattern 终止。
    pkill -f <pattern>
    可能匹配 Agent 自身的 shell 命令行并将其杀死。

Backend Inventory And Benchmarking

后端资源清单与基准测试

The installed CLI advertises these accelerator selectors:
  • CPU: omit
    --gpu
    and
    --tpu
  • GPU:
    --gpu T4
    ,
    --gpu L4
    ,
    --gpu G4
    ,
    --gpu H100
    ,
    --gpu A100
  • TPU:
    --tpu v5e1
    ,
    --tpu v6e1
Observed Colab web UI behavior on 2026-06-06: high-memory toggles were available for CPU-only, T4, and A100; L4 and TPU runtimes appeared to use their fixed higher-memory shapes. Treat this as a snapshot, not a contract.
Availability is account-, region-, demand-, and subscription-dependent. A supported selector can still return
Service Unavailable
or fall back in the web UI. Always inspect the actual assigned hardware with
nvidia-smi
, CPU/RAM checks, and task-specific benchmarks.
Stock upstream does not validate accelerator selector strings strictly: an unrecognized
--gpu
value silently maps to A100 and an unrecognized
--tpu
value to v6e1. The unified fork rejects invalid selectors and simultaneous
--gpu
+
--tpu
before allocation. In either case, spell selectors exactly: GPU
T4
,
L4
,
G4
,
H100
,
A100
; TPU
v5e1
,
v6e1
.
For a compact VPS-style profile, run the bundled benchmark script:
bash
colab run --session bench-cpu --timeout 600 \
  colab-cli/scripts/benchmark-runtime.py cpu > cpu.json

colab run --session bench-t4 --gpu T4 --timeout 600 \
  colab-cli/scripts/benchmark-runtime.py T4 > T4.json
The script records CPU model/core count, system RAM, disk size, disk read/write, NumPy RAM-copy speed, GPU/TPU indicators, approximate FP32/FP16/BF16 matmul throughput where supported,
speedtest-cli
output, and cleanup-safe JSON. Read the dated Pro+ snapshot in
references/pro-plus-snapshot-2026-06-06.md
only as an example of what one account received at one point in time.
For scarce GPUs, do not conclude unavailability from one failed allocation. Use the repo-level retry helper when the user explicitly wants persistence:
bash
ATTEMPTS=80 SLEEP_SECONDS=20 scripts/retry-gpu-benchmarks.sh G4 A100 H100
This retries named
colab run
sessions, validates JSON output, and checks sessions between attempts. It can consume compute units when allocation succeeds, so use it only with user approval.
If the user interrupts a retry or benchmark run, immediately check for local wrapper and
colab run
processes, stop the current named session if one exists, and run
colab sessions
:
bash
pgrep -a -f 'retry-gpu-benchmarks|colab run --session'
colab stop -s <current-session-name>
colab sessions
An interrupted shell does not prove the remote assignment was released.
已安装的 CLI 声明支持以下 accelerator selector:
  • CPU:省略
    --gpu
    和
    --tpu
  • GPU:
    --gpu T4
    、
    --gpu L4
    、
    --gpu G4
    、
    --gpu H100
    、
    --gpu A100
  • TPU:
    --tpu v5e1
    、
    --tpu v6e1
2026-06-06 观察到的 Colab Web UI 行为:high-memory 开关可用于 CPU-only、T4 和 A100;L4 和 TPU runtime 似乎使用固定的高内存 shape。请将此视为快照,而非契约。
可用性取决于账户、地区、需求和订阅。即使 selector 受支持,仍可能返回
Service Unavailable
,或在 Web UI 中回退到其他配置。请始终使用
nvidia-smi
、CPU/RAM 检查和特定任务的 benchmark 检查实际分配的硬件。
原版上游不会严格验证 accelerator selector 字符串:无法识别的
--gpu
值会静默映射到 A100,无法识别的
--tpu
值会静默映射到 v6e1。统一 fork 会在分配前拒绝无效 selector 以及同时使用
--gpu
和
--tpu
。无论如何,请准确拼写 selector:GPU 使用
T4
、
L4
、
G4
、
H100
、
A100
;TPU 使用
v5e1
、
v6e1
。
如需精简的 VPS 风格性能画像,请运行内置 benchmark script:
bash
colab run --session bench-cpu --timeout 600 \
  colab-cli/scripts/benchmark-runtime.py cpu > cpu.json

colab run --session bench-t4 --gpu T4 --timeout 600 \
  colab-cli/scripts/benchmark-runtime.py T4 > T4.json
该脚本会记录 CPU 型号和核心数、系统 RAM、磁盘大小、磁盘读写速度、NumPy RAM-copy 速度、GPU/TPU 指标、受支持时的大致 FP32/FP16/BF16 matmul 吞吐量、
speedtest-cli
输出,以及 cleanup-safe JSON。仅将
references/pro-plus-snapshot-2026-06-06.md
中的 Pro+ 日期快照视为一个账户在某一时点所获配置的一个示例。
对于稀缺 GPU,不要因一次分配失败就断定不可用。当用户明确希望持续尝试时,请使用 repo-level retry helper:
bash
ATTEMPTS=80 SLEEP_SECONDS=20 scripts/retry-gpu-benchmarks.sh G4 A100 H100
它会重试命名的
colab run
session、验证 JSON 输出,并在各次尝试之间检查 session。分配成功时会消耗 compute unit,因此仅在用户批准后使用。
如果用户中断 retry 或 benchmark run,请立即检查本地 wrapper 和
colab run
进程;如果存在当前命名 session,请将其停止,并运行
colab sessions
:
bash
pgrep -a -f 'retry-gpu-benchmarks|colab run --session'
colab stop -s <current-session-name>
colab sessions
中断 shell 并不能证明远端分配已释放。

Authentication

身份验证

The global
--auth
option chooses how the CLI authenticates to the Colab control plane:
bash
colab --auth oauth2 sessions
colab --auth adc sessions
oauth2
is the default in v0.7.4/current upstream. On first authorization, the CLI prints an authorization URL and waits for the user to paste back Google's authorization code; it does not automatically open a browser. It uses
~/.colab-cli-oauth-config.json
(or
-c PATH
) when present and otherwise falls back to its bundled OAuth client config.
On stock upstream, issue #116 remains a granular-consent bug: a partial grant can break initial login or later refresh. The unified fork fixes this by persisting granted scopes, restoring them without re-expanding the request, relaxing only the token exchange, and requiring only control-plane scopes.
adc
uses Google Application Default Credentials and is usually better for headless agent workflows once configured. If ADC user credentials fail with scope errors, re-authenticate with:
bash
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
Do not confuse CLI control-plane auth with
colab auth
. The
colab auth
subcommand pushes credentials into the remote VM for notebook code that needs GCP services such as BigQuery or Cloud Storage.
Debug control-plane identity and scopes with:
bash
colab whoami
colab --auth adc whoami
auth
and
whoami
are hidden commands (absent from
colab --help
's list) but remain registered and directly callable.
whoami
is a read-only credential inspection command;
auth
starts the interactive in-VM Google auth flow.
For control-plane 401/403 errors, first run
colab whoami
and inspect the active provider and scopes. Current session allocation uses
colab.research.google.com
; do not use obsolete
colab.pa.googleapis.com
keep-alive troubleshooting.
全局
--auth
选项决定 CLI 如何向 Colab control plane 验证身份:
bash
colab --auth oauth2 sessions
colab --auth adc sessions
oauth2
是 v0.7.4 和当前上游的默认选项。首次授权时,CLI 会打印授权 URL,并等待用户粘贴回 Google 的 authorization code;它不会自动打开浏览器。当存在
~/.colab-cli-oauth-config.json
(或通过
-c PATH
指定路径)时,CLI 会使用该配置,否则回退到内置的 OAuth client 配置。
在原版上游中,issue #116 仍是一个 granular-consent 缺陷:部分授权可能导致初始登录或后续刷新失败。统一 fork 通过持久化已授予的 scopes、在不重新扩展请求的情况下恢复它们、仅放宽 token exchange 并只要求 control-plane scopes 来修复该问题。
adc
使用 Google Application Default Credentials,完成配置后通常更适合无头 Agent 工作流。如果 ADC 用户凭据因 scope 错误而失败,请使用以下命令重新认证:
bash
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
不要混淆 CLI control-plane 身份验证与
colab auth
。
colab auth
子命令会将凭据推送到远端 VM,供需要 BigQuery 或 Cloud Storage 等 GCP 服务的 notebook 代码使用。
可使用以下命令调试 control-plane 身份和 scopes:
bash
colab whoami
colab --auth adc whoami
auth
和
whoami
是 hidden commands(不会出现在
colab --help
列表中),但仍已注册且可直接调用。
whoami
是只读凭据检查命令;
auth
会启动 VM 内交互式 Google auth 流程。
对于 control-plane 401/403 错误,先运行
colab whoami
并检查当前 provider 和 scopes。当前 session 分配使用
colab.research.google.com
;不要使用已过时的
colab.pa.googleapis.com
keep-alive 故障排查方法。

One-Shot Jobs

一次性任务

Use
colab run
when the user wants a script run on temporary hardware:
bash
colab run --gpu T4 train.py --epochs 1
Useful options:
bash
colab run --gpu T4 script.py
colab run --gpu L4 --timeout 600 script.py
colab run --tpu v5e1 script.py
colab run --gpu T4 --env EPOCHS=1 train.py
colab run --keep -s inspect-job script.py
Default execution timeout is 30.0s; pass an explicit
--timeout
for long jobs.
--env KEY=VALUE
is repeatable; if the same key is supplied more than once, the last value wins. Use it only for non-secret values on stock upstream because expanded environment assignments can be persisted in local session history.
Use
--keep
only when you need to inspect the runtime afterward. If you use it, stop the session explicitly:
bash
colab stop -s inspect-job
For executable scripts, a shebang can request Colab hardware:
python
#!/usr/bin/env -S colab run --gpu T4
print("running remotely")
Operational details:
  • colab run
    forwards script arguments and sets
    __name__ == "__main__"
    like local
    python script.py
    .
  • Script exit codes propagate. An exception or
    sys.exit(1)
    makes
    colab run
    return non-zero.
  • CLI status chatter goes to stderr; the script's stdout stays on stdout. This makes
    colab run job.py > out.txt
    capture only the script output.
  • Exception: the CLI prints a once-daily upgrade banner (
    [colab] A new version ...
    ) to stdout before command output on non-display subcommands, including
    run
    ,
    exec
    ,
    new
    , and
    sessions
    . When parsing captured stdout, ignore leading
    [colab]
    -prefixed lines, or silence the check with
    "enable_update_check": false
    in
    ~/.config/colab-cli/settings.json
    .
  • A missing script path fails before VM allocation.
当用户希望在临时硬件上运行脚本时,使用
colab run
:
bash
colab run --gpu T4 train.py --epochs 1
常用选项:
bash
colab run --gpu T4 script.py
colab run --gpu L4 --timeout 600 script.py
colab run --tpu v5e1 script.py
colab run --gpu T4 --env EPOCHS=1 train.py
colab run --keep -s inspect-job script.py
默认执行超时为 30.0s;长时间任务请显式传入
--timeout
。
--env KEY=VALUE
可重复使用;如果多次提供同一个 key,则最后一个值生效。在原版上游中,仅将其用于非 secret 值,因为展开后的环境变量赋值可能会保存在本地 session history 中。
仅当需要事后检查 runtime 时才使用
--keep
。如果使用,请明确停止 session:
bash
colab stop -s inspect-job
对于可执行脚本,可以通过 shebang 请求 Colab 硬件:
python
#!/usr/bin/env -S colab run --gpu T4
print("running remotely")
操作细节:
  • colab run
    会转发脚本参数,并像本地
    python script.py
    一样设置
    __name__ == "__main__"
    。
  • 脚本 exit code 会向上传递。异常或
    sys.exit(1)
    会使
    colab run
    返回非零状态。
  • CLI 状态信息会写入 stderr;脚本 stdout 保持为 stdout。因此,
    colab run job.py > out.txt
    只会捕获脚本输出。
  • 例外情况:CLI 每天最多一次会在非 display 子命令(包括
    run
    、
    exec
    、
    new
    和
    sessions
    )的输出之前,将升级提示横幅(
    [colab] A new version ...
    )打印到 stdout。解析捕获的 stdout 时,应忽略开头的
    [colab]
    前缀行,或者在
    ~/.config/colab-cli/settings.json
    中设置
    "enable_update_check": false
    来禁用检查。
  • 如果脚本路径不存在,则会在分配 VM 之前失败。

Multi-Step Sessions

多步骤 Session

Use a named session for setup, multiple runs, file transfer, or log export:
bash
colab new -s trainer --gpu T4
colab status -s trainer
colab install -s trainer torch transformers datasets peft trl accelerate
colab exec -s trainer -f train.py --timeout 1800
colab download -s trainer /content/outputs/adapter.safetensors ./adapter.safetensors
colab log -s trainer -o trainer-log.ipynb
colab stop -s trainer
colab sessions
Available accelerators reported by the CLI:
  • GPU:
    T4
    ,
    L4
    ,
    G4
    ,
    H100
    ,
    A100
  • TPU:
    v5e1
    ,
    v6e1
Availability depends on the user's Colab subscription and remaining compute units. If a high-end GPU fails, retry with a cheaper option such as
T4
only after explaining the tradeoff.
If an accelerator request returns a quota or entitlement error, fall back to
--gpu T4
or CPU only after checking the user's goal. Do not assume GPU/TPU allocation will succeed on every account. If the error indicates exhausted compute units or an expired subscription, suggest
colab pay
, which opens the Colab subscription page in a browser.
当需要环境准备、多次运行、文件传输或日志导出时,使用命名 session:
bash
colab new -s trainer --gpu T4
colab status -s trainer
colab install -s trainer torch transformers datasets peft trl accelerate
colab exec -s trainer -f train.py --timeout 1800
colab download -s trainer /content/outputs/adapter.safetensors ./adapter.safetensors
colab log -s trainer -o trainer-log.ipynb
colab stop -s trainer
colab sessions
CLI 报告的可用 accelerator:
  • GPU:
    T4
    、
    L4
    、
    G4
    、
    H100
    、
    A100
  • TPU:
    v5e1
    、
    v6e1
可用性取决于用户的 Colab 订阅和剩余 compute unit。如果高端 GPU 分配失败,请先说明取舍,再尝试成本较低的选项,例如
T4
。
如果 accelerator 请求返回 quota 或 entitlement 错误,请先确认用户目标,再回退到
--gpu T4
或 CPU。不要假定 GPU/TPU 分配在每个账户上都会成功。如果错误表明 compute unit 已耗尽或订阅已过期,请建议使用
colab pay
,它会在浏览器中打开 Colab 订阅页面。

Execution

执行

Run local Python code on an existing session:
bash
colab exec -s analysis -f script.py --timeout 300
colab exec -s analysis --env BATCH=32 -f script.py
Default execution timeout is 30.0s; pass an explicit
--timeout
for long jobs.
--env KEY=VALUE
is repeatable here too, with the last duplicate key winning. Do not pass secrets through this flag on stock upstream because values can be written into local execution history.
Pipe short code through stdin:
bash
printf '%s\n' "import torch; print(torch.cuda.is_available())" | colab exec -s analysis
Run a notebook against the remote kernel:
bash
colab exec -s analysis -f notebook.ipynb --timeout 900
colab log -s analysis -o analysis-log.ipynb
Notebook execution writes an output notebook next to the input, and
colab log -o
can export the session history separately.
For plots, pass
--output-image <path>
to
exec
or
repl
when you need a deterministic local image path.
For batch shell commands, prefer Python through
exec
when possible. If a real shell is required:
bash
printf '%s\n' "pwd; ls -la /content" | colab console -s analysis
console
uses a terminal shell, so captured output can contain control bytes.
在已有 session 上运行本地 Python 代码:
bash
colab exec -s analysis -f script.py --timeout 300
colab exec -s analysis --env BATCH=32 -f script.py
默认执行超时为 30.0s;长时间任务请显式传入
--timeout
。这里的
--env KEY=VALUE
同样可以重复使用,重复 key 以最后一个为准。在原版上游中,不要通过此 flag 传递 secret,因为这些值可能会被写入本地执行 history。
通过 stdin 传入短代码:
bash
printf '%s\n' "import torch; print(torch.cuda.is_available())" | colab exec -s analysis
针对远程 kernel 运行 notebook:
bash
colab exec -s analysis -f notebook.ipynb --timeout 900
colab log -s analysis -o analysis-log.ipynb
Notebook 执行会在输入文件旁写入输出 notebook,而
colab log -o
可以单独导出会话历史。
对于绘图,如果需要确定性的本地图像路径,请向
exec
或
repl
传入
--output-image <path>
。
对于批量 shell 命令,应尽可能优先通过
exec
运行 Python。如果确实需要真实 shell:
bash
printf '%s\n' "pwd; ls -la /content" | colab console -s analysis
console
使用终端 shell,因此捕获的输出可能包含控制字节。

Remote Shell Access

远程 Shell 访问

colab ssh -s <name>
opens an interactive SSH shell over WebSocket. In normal interactive mode, bare
colab ssh
auto-creates only when there are zero local sessions; with exactly one active session it attaches to that session, and with multiple sessions it requires
-s
.
--gpu
/
--tpu
/
--high-mem
only affect a runtime created by the SSH command. Interactive
--rm
removes only a runtime that this
colab ssh
auto-created; it is ignored for an existing session.
--proxy-mode
acts as a ProxyCommand bridge for IDE remote-dev (
ProxyCommand colab ssh --proxy-mode -s SESS
in
~/.ssh/config
). In proxy mode, a missing named
-s SESS
is auto-created and
--rm
stops the bridged session on disconnect; bare proxy mode with no active session does not auto-create one.
-i/--identity
selects the SSH private key (default: first of
~/.ssh/id_ed25519
,
~/.ssh/id_ecdsa
). Interactive mode is TTY-oriented: do not run it unpiped from a non-interactive agent shell.
colab ssh -s <name>
通过 WebSocket 打开交互式 SSH shell。在正常交互模式下,直接执行
colab ssh
时,仅在本地没有 session 的情况下自动创建;有且仅有一个活跃 session 时连接该 session;有多个 session 时必须指定
-s
。
--gpu
/
--tpu
/
--high-mem
仅影响由 SSH 命令创建的 runtime。交互式
--rm
仅删除此次
colab ssh
自动创建的 runtime;对已有 session 无效。
--proxy-mode
充当面向 IDE remote-dev 的 ProxyCommand bridge(可在
~/.ssh/config
中配置
ProxyCommand colab ssh --proxy-mode -s SESS
)。在 proxy 模式下,缺少命名
-s SESS
时会自动创建,而
--rm
会在断开连接时停止桥接 session;没有任何活跃 session 时,直接执行 proxy 模式不会自动创建。
-i/--identity
用于选择 SSH 私钥(默认使用
~/.ssh/id_ed25519
或
~/.ssh/id_ecdsa
中的第一个)。交互模式面向 TTY:不要在非交互式 Agent shell 中未通过管道运行它。

Files And Environment

文件与环境

Remote filesystem commands:
bash
colab ls -s analysis /content
colab upload -s analysis ./local.txt /content/local.txt
colab download -s analysis /content/result.json ./result.json
colab rm -s analysis /content/temp.txt
colab edit -s analysis /content/config.py
On current stock upstream, prefer an explicit
download -> local edit -> upload
sequence for valuable existing files instead of
colab edit
. The released
colab edit
catches any download exception as if the remote file did not exist; a transient transport/auth failure can therefore open an empty temp file and later overwrite the remote path if the user saves changes.
Install packages on the VM:
bash
colab install -s analysis numpy pandas
colab install -s analysis -r requirements.txt
On the unified fork, prefer persistent DriveFS for repeat/agent workflows:
bash
undefined
远程文件系统命令:
bash
colab ls -s analysis /content
colab upload -s analysis ./local.txt /content/local.txt
colab download -s analysis /content/result.json ./result.json
colab rm -s analysis /content/temp.txt
colab edit -s analysis /content/config.py
在当前原版上游中,对于重要的现有文件,优先采用明确的
download -> 本地 edit -> upload
流程,而不要使用
colab edit
。已发布的
colab edit
会将任何 download 异常都视为远端文件不存在;因此,临时传输或身份验证故障可能会打开一个空的临时文件,并可能在用户保存更改后覆盖远端路径。
在 VM 上安装软件包:
bash
colab install -s analysis numpy pandas
colab install -s analysis -r requirements.txt
在统一 fork 中,对于重复执行或 Agent 工作流,请优先使用持久化 DriveFS:
bash
undefined

One-time user-owned authorization and private Desktop-client installation.

One-time user-owned authorization and private Desktop-client installation.

colab drive-mount login --client-config /path/to/client_secret.json
colab drive-mount login --client-config /path/to/client_secret.json

Every later runtime can mount without repeating browser consent.

Every later runtime can mount without repeating browser consent.

colab new -s analysis colab drive-mount -s analysis colab drive-mount status

The fork stores the Desktop OAuth client at `~/.config/colab-cli/drive-mount-client.json` and the refresh grant at `drive-mount-auth.json`, both with user-only permissions. Per-shell OAuth environment configuration is optional rather than required. If a desktop browser cannot be discovered, login prints a loopback URL instead of failing; open it on the same machine because its callback is localhost. `colab drivemount -s analysis` automatically uses the persistent path when configured, otherwise it falls back to stock interactive behavior. Use `colab drive-mount logout` to revoke/remove the refresh grant. Stock upstream issue #113 still affects the legacy interactive path, so verify mounts before depending on it.
colab new -s analysis colab drive-mount -s analysis colab drive-mount status

该 fork 将 Desktop OAuth client 存储在 `~/.config/colab-cli/drive-mount-client.json`,将 refresh grant 存储在 `drive-mount-auth.json`,二者均仅允许用户访问。每个 shell 的 OAuth 环境配置是可选的,而不再是必需。如果无法发现桌面浏览器,login 会打印 loopback URL 而不是直接失败;请在同一台机器上打开该 URL,因为 callback 指向 localhost。`colab drivemount -s analysis` 会在配置完成时自动使用持久化路径,否则回退到原版交互行为。使用 `colab drive-mount logout` 撤销或移除 refresh grant。原版上游的 issue #113 仍会影响旧版交互路径,因此请先验证挂载是否成功,再依赖该功能。

Drive API quota and transfer guidance

Drive API 配额与传输指南

For large Drive-backed Colab jobs, read
references/drive-api-limits-2026-10-01.md
before estimating transfer safety or cost. For projects on Google's standardized 2026 Drive API quotas, remember the headline limits: 1 TB/day project egress, 750 GB/day Workspace upload+copy, 1,000,000 quota units/min/project, 325,000/min/user/project, and a 400,000,000 quota-unit/day no-additional-charge threshold. Drive -> Colab is the egress direction; Colab -> Drive is upload/ingress. Treat exact DriveFS byte accounting as unverified unless the project's Cloud quota telemetry confirms it, because Google's public quota page does not explicitly document one-for-one DriveFS accounting. Grandfathered projects can retain older quotas.
对于大型 Drive-backed Colab 任务,在估算传输安全性或成本之前,请阅读
references/drive-api-limits-2026-10-01.md
。对于采用 Google 2026 年标准化 Drive API 配额的项目,请记住以下主要限制:每项目每天 1 TB egress、每 Workspace 每天 750 GB upload+copy、每项目每分钟 1,000,000 个 quota unit、每用户每项目每分钟 325,000 个以及每天 400,000,000 个 quota unit 的免额外收费阈值。Drive -> Colab 属于 egress 方向;Colab -> Drive 属于 upload/ingress。除非项目的 Cloud quota telemetry 予以确认,否则请将 DriveFS 的精确字节计数视为未经验证,因为 Google 的公开配额页面没有明确说明 DriveFS 是否采用 1:1 计数。存量项目可能会继续沿用旧配额。

Logs And Reporting

日志与报告

Inspect and save execution history:
bash
colab log -s analysis -n 20
colab log -s analysis -t execution
colab log -s analysis -o analysis-log.ipynb
colab log -s analysis -o analysis-log.md
colab log -s analysis -o analysis-log.txt
colab log -s analysis -o analysis-log.jsonl
The
-o
suffix picks the export format:
.ipynb
,
.md
,
.txt
, or
.jsonl
.
Use
colab help <command>
for per-command options and defaults; it is equivalent to
colab <command> --help
.
When reporting completion, include the session name, hardware, files retrieved, log file path if exported, and confirmation that cleanup ran.
检查和保存执行历史:
bash
colab log -s analysis -n 20
colab log -s analysis -t execution
colab log -s analysis -o analysis-log.ipynb
colab log -s analysis -o analysis-log.md
colab log -s analysis -o analysis-log.txt
colab log -s analysis -o analysis-log.jsonl
-o
后缀决定导出格式:
.ipynb
、
.md
、
.txt
或
.jsonl
。
使用
colab help <command>
查看各命令的选项和默认值;它等价于
colab <command> --help
。
报告任务完成情况时,请包含 session 名称、硬件、已取回的文件、导出后的日志文件路径,以及清理是否已执行的确认信息。

Recovery

恢复

  • Treat
    ~/.config/colab-cli/history/
    as sensitive. Besides executed code and outputs, current stock upstream records raw interactive stdin replies, which can include one-time auth codes or other secrets. Do not publish/export history without reviewing and redacting it first.
  • Session not found
    : run
    colab sessions
    before recreating anything. If the backend assignment is gone, recreate as needed. If an unnamed/
    [?]
    assignment or the recorded endpoint is still live, treat it as an orphaned local record and recover/stop that assignment instead of allocating a duplicate. See
    references/session-resilience-2026-10-01.md
    .
  • Kernel stuck or timeout: run
    colab restart-kernel -s <name>
    once, then retry. If still stuck, stop and recreate the session.
  • Unexpected stale behavior: check
    which colab
    and
    colab version
    .
  • Auth failure: inspect whether the command used
    oauth2
    or
    adc
    , then run
    colab whoami
    ; do not use
    colab auth
    to fix control-plane credential problems.
  • Cleanup uncertainty: run
    colab sessions
    and reconcile all assignments created for the current task, including unnamed/orphaned endpoints; do not treat named-session disappearance as successful cleanup.
  • For paid long jobs, use a detached spend watchdog with CU cap, account floor, wall deadline, bounded usage probes, and stop fallback. Parse numeric CLI output under
    LC_ALL=C
    ; locale decimal commas can silently break awk/printf comparisons. Kill watchdog/helper processes by recorded PID, not broad patterns. Detailed field-tested design:
    references/session-resilience-2026-10-01.md
    .
  • 请将
    ~/.config/colab-cli/history/
    视为敏感目录。除了已执行代码和输出,当前原版上游还会记录原始交互式 stdin 回复,其中可能包含一次性 auth code 或其他 secret。未经检查和脱敏,不要发布或导出 history。
  • Session not found
    :在重新创建任何资源之前,先运行
    colab sessions
    。如果后端分配已经消失,请按需重新创建。如果未命名或
    [?]
    的分配、已记录的 endpoint 仍然存活,请将其视为孤立的本地记录,并恢复或停止该分配,而不是分配重复资源。参见
    references/session-resilience-2026-10-01.md
    。
  • Kernel 卡住或超时:运行一次
    colab restart-kernel -s <name>
    ,然后重试。如果仍然卡住,请停止并重新创建 session。
  • 出现意外的陈旧行为:检查
    which colab
    和
    colab version
    。
  • 身份验证失败:检查命令使用的是
    oauth2
    还是
    adc
    ,然后运行
    colab whoami
    ;不要使用
    colab auth
    修复 control-plane 凭据问题。
  • 不确定是否已清理:运行
    colab sessions
    ,并核对当前任务创建的所有分配,包括未命名或孤立 endpoint;不要将命名 session 消失视为清理成功。
  • 对于付费的长时间任务,请使用分离的支出 watchdog,并设置 CU cap、账户余额下限、墙钟截止时间、有时限的用量探测和停止 fallback。请在
    LC_ALL=C
    下解析数值型 CLI 输出;locale 使用小数逗号时可能会悄悄破坏 awk/printf 比较。应按照记录的 PID 终止 watchdog 和 helper 进程,不要使用宽泛的 pattern。详细且经过实战验证的设计参见
    references/session-resilience-2026-10-01.md
    。

Stock upstream vs unified fork

原版上游与统一 fork

Stock upstream still has the
colab edit
broad-download exception risk, broad Contents 404 classification, ambiguous assignment POST timeout handling, locally cached
status
machine shape, and destructive local pruning after a single missing-assignment listing. The unified fork fixes these: safe
edit
, proxy 401/404 classification, bounded assignment reconciliation, backend
machineShape
, and in
c7512ab
(
0.7.5.dev13+gc7512abed
) retry + private stale-session storage + automatic re-adoption + stale endpoint stop fallback + same-name stale cleanup. Keep
colab sessions
as the final server-side resource source of truth. Do not reinstall an older live job mid-run just to gain the new recovery logic; retain its existing external guard until a safe stop/checkpoint boundary.
原版上游仍存在
colab edit
宽泛 download 异常风险、宽泛的 Contents 404 分类、模糊的分配 POST timeout 处理、本地缓存的
status
machine shape,以及在单次缺失分配列表后执行破坏性本地清理等问题。统一 fork 修复了这些问题:安全的
edit
、proxy 401/404 分类、有界的分配记录核对、后端
machineShape
,并在
c7512ab
(
0.7.5.dev13+gc7512abed
)中加入 retry + 私有 stale-session storage + 自动重新接管 + stale endpoint 停止 fallback + 同名 stale 清理。请始终将
colab sessions
作为服务器端资源状态的最终事实来源。不要在任务运行中途仅为获得新的恢复逻辑而重新安装旧版本;请保留现有的外部 guard,直到安全的 stop/checkpoint 边界。

Fast Command Reference

快速命令参考

bash
colab new -s NAME [--gpu T4|L4|G4|H100|A100] [--tpu v5e1|v6e1] [--high-mem]
colab sessions
colab status -s NAME
colab run [--gpu GPU|--tpu TPU] [--high-mem] [--keep] [--env KEY=VALUE]... SCRIPT [ARGS...]
colab exec -s NAME -f FILE [--timeout SECONDS] [--env KEY=VALUE]...
colab install -s NAME PKG...
colab install -s NAME -r requirements.txt
colab upload -s NAME LOCAL REMOTE
colab download -s NAME REMOTE LOCAL
colab log -s NAME [-n N|-o FILE]
colab restart-kernel -s NAME
colab url -s NAME [--open] [--host HOST]
colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem] [--rm]
colab stop -s NAME
colab usage
colab help [COMMAND]
colab pay
colab skill
colab readme
colab whoami
colab version
For upstream details, consult:
  • Google Developers Blog announcement:
    https://developers.googleblog.com/introducing-the-google-colab-cli/
  • Google Colab CLI repository:
    https://github.com/googlecolab/google-colab-cli
bash
colab new -s NAME [--gpu T4|L4|G4|H100|A100] [--tpu v5e1|v6e1] [--high-mem]
colab sessions
colab status -s NAME
colab run [--gpu GPU|--tpu TPU] [--high-mem] [--keep] [--env KEY=VALUE]... SCRIPT [ARGS...]
colab exec -s NAME -f FILE [--timeout SECONDS] [--env KEY=VALUE]...
colab install -s NAME PKG...
colab install -s NAME -r requirements.txt
colab upload -s NAME LOCAL REMOTE
colab download -s NAME REMOTE LOCAL
colab log -s NAME [-n N|-o FILE]
colab restart-kernel -s NAME
colab url -s NAME [--open] [--host HOST]
colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem] [--rm]
colab stop -s NAME
colab usage
colab help [COMMAND]
colab pay
colab skill
colab readme
colab whoami
colab version
有关上游详情,请参阅:
  • Google Developers Blog 公告:
    https://developers.googleblog.com/introducing-the-google-colab-cli/
  • Google Colab CLI repository:
    https://github.com/googlecolab/google-colab-cli