# AutoDL 命令行手册（独立 Node 执行）

AutoDL 容器实例管理命令行 / 库。核心是 `autodl.mjs`——**纯 Node.js**（ESM + `fetch` + JWT），
**与 opencli 完全无关**（零第三方依赖），不依赖浏览器 / CDP / 登录态页面，Node 18+ 直接可用。
opencli 只是可选的外壳：`opencli autodl <command> ...` 的命令模块是调用同一份核心逻辑的薄封装。

## 三种使用方式

| 方式 | 命令 |
|------|------|
| npm 全局安装（推荐） | `npm i -g autodl-cli` 后直接 `autodl <command> [args...]` |
| 免安装 npx | `npx autodl <command> [args...]` |
| 直接 Node 执行 | `node ~/.opencli/clis/autodl/autodl.mjs <command> [args...]` |
| Node 短入口 | `node ~/.opencli/clis/autodl/run.mjs <command> [args...]` |
| opencli CLI | `opencli autodl <command> [args...]` |

> 输出默认 YAML 风格，加 `--format json` 可输出 JSON。
> opencli 方式只是外壳：14 个 `.js` 命令模块是调用 `autodl.mjs` 的薄封装，逻辑完全一致。

### 快速上手

```bash
# 全局安装后（或 npx autodl ...）
autodl help

# 查看全部命令
node ~/.opencli/clis/autodl/autodl.mjs help

# 查看某个命令的参数
node ~/.opencli/clis/autodl/autodl.mjs ssh --help
```

## 一次性配置 Token

从已登录的 Chrome 控制台复制 JWT（`F12 → Application → Local Storage → autodl.com → token`），任选一种：

```bash
# 方式一：写入文件（权限 600，推荐）
node ~/.opencli/clis/autodl/autodl.mjs token --set "<jwt>"

# 方式二：环境变量（每次执行前设置）
export AUTODL_TOKEN="<jwt>"
```

token 文件路径：`~/.autodl/token`（兼容旧路径 `~/.opencli/autodl.token`，存在时自动读取）。
失效后重新 `token --set` 即可。

## 命令总览

| 命令 | 说明 |
|------|------|
| `list` | 列出实例（合并 Pro + 标准实例） |
| `ssh <uuid>` | 获取 SSH 登录命令 + root 密码 |
| `create <machine> <image>` | 租用新实例（按量直接创建；包期创建订单并支付） |
| `start <uuid>` | 开机 |
| `stop <uuid>` | 关机 |
| `release <uuid> --yes` | 释放（销毁）实例，数据清空不可恢复 |
| `renew <uuid>` | 续费 |
| `rename <uuid> <name>` | 改名 |
| `schedule-shutdown <uuid>` | 设置 / 取消定时关机 |
| `gpus` | 列出 GPU 型号与空闲量 |
| `machines` | 列出可租 GPU 主机（算力市场） |
| `images` | 列出系统镜像 |
| `price <machine>` | 价格预览（不产生订单） |
| `token` | 查看 / 写入 token |
| `deploy-apps` / `deploy-app-detail` / `deploy-user-apps` | 应用广场搜索 / 详情 / 用户应用（公开） |
| `deploy-common` | 部署公告与可选地区（公开） |
| `deploy-list` | 我的部署列表（需 autodl.art 登录） |
| `deploy-create <appId> [specId] [--gpuType X] [--region X]` | 部署应用（按应用创建 Pro 实例，需登录） |
| `deploy-gpus [--region X] [--gpuType X] [--specs]` | 列出可部署 GPU 型号/空闲数/规格 id（需登录） |
| `deploy-ssh <uuid>` | 获取部署实例 SSH 命令/端口/root 密码/Jupyter（需登录） |
| `deploy-detail <uuid>` | 部署实例详情：启动命令/SSH/Jupyter/服务端口/价格/定时关机（需登录） |
| `deploy-start-command <uuid> <command>` | 设置部署实例开机启动命令（需登录） |
| `deploy-rename <uuid> <name>` | 重命名部署实例（需登录） |
| `deploy-schedule-shutdown <uuid> [--time]` | 设置/取消部署实例定时关机（需登录） |
| `deploy-start/stop/release <uuid>` | 部署实例开机 / 关机 / 释放（需登录） |
| `deploy-star` / `deploy-unstar <appId>` | 收藏 / 取消收藏应用（需登录） |
| `deploy-token` | 查看 / 写入 autodl.art token |

## 作为库引用

`autodl.mjs` 导出一组异步 API，可直接 `import` 到自己的 Node 项目里：

```js
import {
  listInstances, listGpus, listMachines, listImages,
  createInstance, startInstance, stopInstance, releaseInstance,
  renewInstance, renameInstance, setScheduleShutdown,
  getSsh, pricePreview, tokenInfo,
  deployList, deploySsh, deployDetail, deployCreate, deployStartCommand,
  deployRename, deployScheduleShutdown, deployStart, deployStop, deployRelease,
  getToken, setToken, api, main, AutodlError, COMMANDS,
} from '/home/idea/.opencli/clis/autodl/autodl.mjs';

// 查实例
const rows = await listInstances({ status: 'running' });

// 生命周期
await startInstance('wpn6tqcvq6-8f7ab54b');
await stopInstance('wpn6tqcvq6-8f7ab54b');
await releaseInstance('wpn6tqcvq6-8f7ab54b', { yes: true });

// 部署（autodl.art）
const deploys = await deployList();
const ssh = await deploySsh(deploys[0].uuid);
await deployStartCommand(deploys[0].uuid, 'bash /root/start.sh');
await deployScheduleShutdown(deploys[0].uuid, '+2h'); // 或 'YYYY-MM-DD HH:mm'
await deployScheduleShutdown(deploys[0].uuid);        // 取消
await deployStart(deploys[0].uuid);
await deployStop(deploys[0].uuid);
await deployRelease(deploys[0].uuid, { yes: true });

// 错误处理：所有业务错误都是 AutodlError（含 code/hint）
try {
  await listInstances();
} catch (e) {
  if (e instanceof AutodlError) console.log(e.code, e.message); // NO_DATA ...
}

// 编程式 CLI：main(argv) 返回退出码，不操作 process.exit
const code = await main(['list', '--format', 'json']);
```

> 库零依赖，只用到 Node 内置 `fetch`/`fs`/`path`；token 读取规则与环境变量
> `AUTODL_TOKEN`（优先）、文件 `~/.autodl/token`（兼容旧路径 `~/.opencli/autodl.token`；
> 可被 `AUTODL_TOKEN_FILE` 覆盖）。
> 被 `import` 时不会触发 CLI 主流程（只有 `node autodl.mjs` 直跑才走 CLI）。

## autodl.art 部署（/app/deploy）

`autodl.art` 的「部署」是**应用部署**：从应用广场（CodeWithGPU 社区镜像）挑一个应用，
按 GPU 机器创建实例（自动带 `cg_application_uuid`），然后在「我的部署」里管理。

### Token（仅登录类命令需要）

应用广场搜索/详情等公开接口无需 token；`deploy-list` / `deploy-create` / `deploy-ssh` /
`deploy-detail` / `deploy-start-command` / `deploy-rename` / `deploy-schedule-shutdown` /
`deploy-start` / `deploy-stop` / `deploy-release` / `deploy-star` / `deploy-unstar`
需要 **autodl.art 登录态**：

```bash
# 浏览器登录 https://www.autodl.art → F12 → localStorage.token 复制 JWT
node autodl.mjs deploy-token --set "<jwt>"
# 或环境变量
export AUTODL_ART_TOKEN="<jwt>"
```

token 文件：`~/.autodl/art.token`（兼容旧路径 `~/.opencli/autodl.art.token`；
与 autodl.com 的 token 相互独立）。

### 命令示例

```bash
# 搜索应用（公开）
node autodl.mjs deploy-apps --keyword comfyui --limit 10

# 应用详情（公开，含版本列表）
node autodl.mjs deploy-app-detail 252

# 某用户主页的应用（公开）
node autodl.mjs deploy-user-apps zealman --sortType hot

# 公告与可选地区（公开）
node autodl.mjs deploy-common

# 我的部署（需登录）
node autodl.mjs deploy-list

# 可部署 GPU（需登录；--specs 可同时列出规格 id）
node autodl.mjs deploy-gpus --region beijingDC2 --gpuType "RTX 5090" --specs

# 部署实例 SSH 命令 / root 密码（需登录）
node autodl.mjs deploy-ssh <uuid>

# 部署实例详情（启动命令 / SSH / Jupyter / 服务端口 / 价格 / 定时关机，需登录）
node autodl.mjs deploy-detail <uuid>

# 设置部署实例的开机启动命令（需登录）
node autodl.mjs deploy-start-command <uuid> "bash /root/start.sh"

# 重命名部署实例（需登录）
node autodl.mjs deploy-rename <uuid> "my-comfyui"

# 设置 / 取消部署实例定时关机（需登录；时间支持 YYYY-MM-DD HH:mm（秒自动去掉）
# 或相对偏移 +30m/+2h/+1d；不带 --time 时取消）
node autodl.mjs deploy-schedule-shutdown <uuid> --time "+2h"
node autodl.mjs deploy-schedule-shutdown <uuid>

# 部署应用：估价（需登录，不创建）
node autodl.mjs deploy-create 252 --gpuType "RTX 5090" --region beijingDC2 --dryRun

# 部署应用：真实创建（按量；也可直接传规格 id）
node autodl.mjs deploy-create 252 1 --chargeType payg --name my-comfyui

# 管理部署实例
node autodl.mjs deploy-start <uuid>
node autodl.mjs deploy-stop <uuid>
node autodl.mjs deploy-release <uuid> --yes

# 收藏 / 取消收藏
node autodl.mjs deploy-star 252
node autodl.mjs deploy-unstar 252
```

> 说明：`deploy-create` 会自动拉取应用详情并使用其最新（或 `--versionId` 指定）版本。
> Pro 部署 API 使用 `data_center_list` + `gpu_spec_info.id`（来自
> `/machine_pro/gpu_spec_config`，用 `deploy-gpus --specs` 查看），`--dataDisk` 为
> 系统盘扩容 GB（基础 30GB 之上）；`--dryRun` 走 `/adl_server/order/price/preview/pro` 估价。
> 部署实例的列表/开机/关机/释放走 autodl.art 的 `/api/v1/adl_server/instance/pro/*`。

## 命令详解

### list — 实例列表

```bash
node autodl.mjs list
node run.mjs list --status running,shutdown   # 按状态过滤
node run.mjs list --chargeType payg           # 按计费方式过滤
node run.mjs list --limit 20                  # 返回数量（默认 50，最大 200）
```

输出：`uuid / status / chargeType / gpu / gpuNum / region / sshCommand / rootPassword / createdAt` 等。

### ssh — SSH 登录信息

```bash
node run.mjs ssh <uuid>
```

输出：
```
uuid: wpn6tqcvq6-8f7ab54b
status: running
sshCommand: ssh -p 24400 root@connect.westd.seetacloud.com
rootPassword: tXYJ7J/d7HVI
```

### create — 租用新实例

```bash
# 先查可租主机与镜像
node run.mjs machines --gpu "RTX 4090" --region west-B --chargeType payg
node run.mjs images --keyword pytorch

# 估价（不创建）
node run.mjs create <machineId> <imageUrl> --dryRun

# 按量租用（直接创建并开机，秒级计费）
node run.mjs create <machineId> <imageUrl> --chargeType payg --gpu 1

# 包日租用（创建订单并自动支付）
node run.mjs create <machineId> <imageUrl> --chargeType daily --duration 1

# 其他参数
--name "my-gpu"      # 实例名称（≤32 字符）
--dataDisk 50        # 数据盘扩容（GB）
--pay false          # 包期订单不自动支付
```

### start / stop — 开机 / 关机

```bash
node run.mjs start <uuid>    # 开机（按量恢复计费）
node run.mjs stop <uuid>     # 关机（按量停止计费，保留实例）
```

Pro 与标准实例自动路由，无需区分。

### release — 释放（销毁）实例

```bash
# 必须先关机（shutdown 状态）才能释放
node run.mjs stop <uuid> && node run.mjs list   # 确认 status=shutdown
node run.mjs release <uuid> --yes               # 销毁，数据清空，不可恢复
node run.mjs list                               # 确认列表已空
```

> ⚠️ 实例运行中执行 release 会报 `BadRequest — 请在实例关机状态下执行释放操作`。

### renew — 续费

```bash
node run.mjs renew <uuid>                          # 默认续 1 天
node run.mjs renew <uuid> --chargeType weekly --duration 2
node run.mjs renew <uuid> --pay false              # 只建订单不支付
```

### rename / schedule-shutdown

```bash
node run.mjs rename <uuid> "train-4090"
node run.mjs schedule-shutdown <uuid> --time "2026-08-14 22:30:00"  # 设置
node run.mjs schedule-shutdown <uuid>                                  # 取消
```

### gpus / machines / images / price — 选机与估价

```bash
node run.mjs gpus                              # 各区域 GPU 空闲量（默认 west-B/C/D/E）
node run.mjs gpus --region west-B,west-C       # 指定区域
node run.mjs machines --gpu "RTX 4090"         # 可租主机
node run.mjs machines --region west-B --chargeType daily
node run.mjs images --keyword pytorch          # 镜像（可按 --cpuArch/--chipCorp 过滤）
node run.mjs price <machineId> --gpu 1 --chargeType payg --duration 1
```

### token

```bash
node run.mjs token                  # 查看当前 token（脱敏）
node run.mjs token --set "<jwt>"    # 写入 token 到 ~/.autodl/token
```

## 完整生命周期示例

```bash
# 1. 选机估价
node run.mjs machines --gpu "RTX 4090" --region west-B
node run.mjs create <machineId> <imageUrl> --dryRun

# 2. 租用（按量）
node run.mjs create <machineId> <imageUrl> --chargeType payg --name demo

# 3. 查看与 SSH
node autodl.mjs list
node run.mjs ssh <uuid>
ssh -p 24400 root@connect.westd.seetacloud.com   # 密码见上一步输出

# 4. 关机 / 开机
node run.mjs stop <uuid>
node run.mjs start <uuid>

# 5. 释放（先关机）
node run.mjs stop <uuid>
node run.mjs release <uuid> --yes
node run.mjs list    # 输出：当前账号没有实例
```

## 注意事项

- **计费**：按量实例开机即计费；关机仅停算机时费，仍保留资源；释放后完全停止计费。
- **释放前置**：必须先 `stop` 并等状态变为 `shutdown` 再 `release`。
- **安全**：root 密码/ssh 命令属敏感信息，`list`/`ssh` 会明文展示，注意保管输出。
- **网络**：需要能访问 `https://www.autodl.com`；命令全部走 HTTPS API。
- **token 过期**：报 `AUTH_REQUIRED` / HTTP 401 时重新 `token --set`。

## 发布到 npm（维护者）

```bash
# 1) 登录 npm（需要账号，首次会要求输入用户名/密码/邮箱或 OTP）
npm login

# 2) 发布（prepublishOnly 会自动先跑 node --check 语法校验）
npm publish

# 3) 验证安装
npm install -g autodl-cli
autodl help
```

> 包名 `autodl-cli`，bin 命令 `autodl`；`files` 只包含 `autodl.mjs` / `run.mjs` /
> `README.md` / `MANUAL.md` / `LICENSE`。发布前可用 `npm pack --dry-run` 预览产物，
> 用 `npm publish --dry-run` 校验（不真正上传）。升级版本号：`npm version patch/minor/major`。

## 目录结构

```
~/.opencli/clis/autodl/
├── autodl.mjs            # 核心库 + CLI（零依赖，与 opencli 无关）← 主文件
├── run.mjs               # Node 短入口（等价 node autodl.mjs）
├── _opencli.js           # opencli 桥接层（AutodlError → CliError）
├── create.js / list.js / start.js / stop.js / release.js   # opencli 薄封装
├── ssh.js / renew.js / rename.js / schedule-shutdown.js
├── gpus.js / machines.js / images.js / price.js / token.js
├── README.md             # 快速说明
└── MANUAL.md             # 本手册
```
