> ## Documentation Index
> Fetch the complete documentation index at: https://docs.flashcat.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# 命令行工具

> 使用 Flashduty CLI 在终端中管理故障、值班、状态页和通知模板

## 概述

Flashduty CLI（`flashduty`）是一款命令行工具，可在终端中完成故障生命周期管理、值班查询、状态页发布、通知模板调试等操作，适用于运维脚本、本地排障以及与 AI 编程代理协同工作。

工具开源在 [flashcatcloud/flashduty-cli](https://github.com/flashcatcloud/flashduty-cli)，支持 macOS、Linux 和 Windows。

## 安装

<Tabs>
  <Tab title="macOS / Linux">
    ```bash theme={null}
    curl -sSL https://static.flashcat.cloud/flashduty-cli/install.sh | sh
    ```

    默认安装到 `/usr/local/bin`，可通过环境变量 `FLASHDUTY_INSTALL_DIR` 自定义。
  </Tab>

  <Tab title="Windows (PowerShell)">
    ```powershell theme={null}
    irm https://static.flashcat.cloud/flashduty-cli/install.ps1 | iex
    ```

    默认安装到 `~\.flashduty\bin`，可通过环境变量 `FLASHDUTY_INSTALL_DIR` 自定义。
  </Tab>

  <Tab title="手动下载">
    访问 [CDN 最新版本指针](https://static.flashcat.cloud/flashduty-cli/releases/latest) 获取最新版本号，然后从 `https://static.flashcat.cloud/flashduty-cli/releases/download/<version>/<asset>` 下载对应平台的二进制包，解压后放入 `PATH` 即可。
  </Tab>
</Tabs>

### 安装选项

| 环境变量                        | 说明                                        | 默认值                                                    |
| --------------------------- | ----------------------------------------- | ------------------------------------------------------ |
| `FLASHDUTY_VERSION`         | 安装指定版本，如 `v0.6.0`                         | 最新版本                                                   |
| `FLASHDUTY_INSTALL_DIR`     | 安装目录                                      | `/usr/local/bin`（Shell）、`~\.flashduty\bin`（PowerShell） |
| `MIRROR_URL`                | 覆盖安装脚本的 Release 资产下载镜像前缀，需以 `https://` 开头 | `https://static.flashcat.cloud/flashduty-cli`          |
| `FLASHDUTY_UPDATE_BASE_URL` | 覆盖 `flashduty update` 及自动更新检查的下载基础 URL    | `https://static.flashcat.cloud/flashduty-cli`          |

## 认证

### 登录

```bash theme={null}
flashduty login
```

按提示输入 APP Key。获取方式：登录 [Flashduty 控制台](https://console.flashcat.cloud)，进入 **个人中心 > 个人信息**，复制 APP Key。

### 凭证解析顺序

CLI 按以下优先级查找 APP Key（高优先级在前）：

1. `--app-key` 命令行参数（脚本场景使用）
2. `FLASHDUTY_APP_KEY` 环境变量
3. 配置文件 `~/.flashduty/config.yaml`（由 `flashduty login` 写入）

### 配置文件

存储在 `~/.flashduty/config.yaml`，权限为 `0600`：

```yaml theme={null}
app_key: your_app_key
base_url: https://api.flashcat.cloud
```

### 配置命令

```bash theme={null}
flashduty config show              # 查看当前配置（APP Key 已脱敏）
flashduty config set app_key KEY   # 设置 APP Key
flashduty config set base_url URL  # 覆盖 API 地址
```

## 全局参数

所有子命令均支持以下参数：

| 参数                | 说明                                                       |
| ----------------- | -------------------------------------------------------- |
| `--output-format` | 输出格式：`table`（默认）、`json` 或 `toon`（紧凑、更省 token）            |
| `--json`          | 以 JSON 格式输出，是 `--output-format json` 的别名，便于通过 `jq` 等工具解析 |
| `--no-trunc`      | 表格输出时不截断长字段                                              |
| `--base-url`      | 覆盖 API 地址（私有部署场景）                                        |

## 命令清单

### incident — 故障生命周期

```bash theme={null}
flashduty incident list [flags]         # 列出故障（默认最近 24 小时）
flashduty incident get <id> [<id2>...]  # 查看故障详情（单个 ID 显示完整视图）
flashduty incident create [flags]       # 创建故障（参数缺失时进入交互模式）
flashduty incident update <id> [flags]  # 更新故障字段
flashduty incident ack <id> [<id2>...]  # 认领故障
flashduty incident close <id> [<id2>...] # 关闭（解决）故障
flashduty incident timeline <id>        # 查看故障时间线
flashduty incident alerts <id>          # 查看故障关联的告警
flashduty incident similar <id>         # 查找相似的历史故障
```

`incident list` 常用过滤参数：

| 参数           | 说明                                                | 默认值   |
| ------------ | ------------------------------------------------- | ----- |
| `--progress` | 进度过滤：`Triggered`、`Processing`、`Closed`            | 全部    |
| `--severity` | 等级过滤：`Critical`、`Warning`、`Info`                  | 全部    |
| `--channel`  | 按协作空间 ID 过滤                                       | -     |
| `--query`    | 按标题、标签或内容关键字自由搜索（也可直接输入 24 位故障 ID 或 6 位短编号进行精准查询） | -     |
| `--since`    | 起始时间（时长、日期、日期时间或 Unix 时间戳）                        | `24h` |
| `--until`    | 截止时间                                              | `now` |
| `--limit`    | 最大结果数                                             | `20`  |
| `--page`     | 页码                                                | `1`   |

时间格式示例：`5m`、`1h`、`24h`、`168h`、`2026-04-01`、`2026-04-01 10:00:00`、`1712000000`。

### change — 变更记录

```bash theme={null}
flashduty change list [flags]    # 列出变更记录（部署、配置变更等）
```

支持 `--channel`、`--since`、`--until`、`--type`、`--limit`、`--page`。

### member — 成员查询

```bash theme={null}
flashduty member list [flags]    # 列出成员
```

支持 `--query`（姓名/邮箱关键字搜索）、`--role-id`、`--page`、`--limit`、`--orderby`、`--asc`。

### team — 团队管理

```bash theme={null}
flashduty team list [flags]                          # 列出团队及成员
flashduty team info --team-id <id>                   # 查看单个团队详情
flashduty team upsert --team-name <name> [flags]     # 创建或更新团队（含 --team-id 时为更新）
flashduty team delete --team-id <id>                 # 删除团队（不可逆）
```

`team list` 支持 `--query`（团队名称子串匹配）、`--page`、`--limit`、`--orderby`（`created_at`/`updated_at`/`team_name`）、`--asc`、`--person-id`（按成员 ID 过滤所属团队）。

`team info` 支持通过 `--team-id`、`--team-name` 或 `--ref-id` 指定团队（三选一）。

`team upsert` 创建或更新团队：

* `--team-name`（必填，1–39 字符）
* `--team-id`（填写则为更新，否则创建）
* `--description`（最多 500 字符）
* `--person-ids`（成员 ID 列表；**会完整替换现有成员名单，更新前请先用 `team info` 确认当前成员**）
* `--emails`（邀请邮箱列表）
* `--ref-id`（外部系统引用 ID）

`team delete` 支持通过 `--team-id`、`--team-name` 或 `--ref-id` 指定团队，**操作不可逆**。

### channel — 协作空间查询

```bash theme={null}
flashduty channel list [flags]   # 列出协作空间
```

支持 `--name`。

### channel escalate-rule-list — 分派策略查询

分派策略现已并入 `channel` 命令组，通过位置参数传入协作空间 ID：

```bash theme={null}
flashduty channel escalate-rule-list <channel-id>   # 列出指定协作空间下的所有分派策略
```

其他分派策略管理命令：`escalate-rule-create`、`escalate-rule-update`、`escalate-rule-delete`（均在 `channel` 命令组下，`--channel-id` 为必填）。

### field — 自定义字段查询

```bash theme={null}
flashduty field list [flags]     # 列出自定义字段定义
```

支持 `--name`。

### status-page — 状态页管理

```bash theme={null}
flashduty status-page list                                             # 列出状态页
flashduty status-page change-active-list <page-id>                    # 列出活跃的变更事件
flashduty status-page change-create <page-id> [flags]                 # 创建状态页事件
flashduty status-page change-timeline-create [flags]                  # 追加时间线更新
```

#### 从 Atlassian Statuspage 迁移

迁移任务为异步执行，需通过 `migration-status` 轮询进度：

```bash theme={null}
# 1. 迁移结构与历史记录
flashduty status-page migrate-structure <source-page-id> \
  --from atlassian \
  --api-key $ATLASSIAN_STATUSPAGE_API_KEY

# 2. 查询迁移进度
flashduty status-page migration-status <job-id>

# 3. 迁移邮件订阅者
flashduty status-page migrate-email-subscribers \
  --from atlassian \
  --source-page-id page_123 \
  --target-page-id <target_page_id> \
  --api-key $ATLASSIAN_STATUSPAGE_API_KEY

# 4. 取消运行中的任务
flashduty status-page migration-cancel <job-id>
```

其他可用子命令：`change-delete`、`change-info`、`change-list`、`change-timeline-delete`、`change-timeline-update`、`change-update`、`subscriber-export`。

### template — 通知模板

```bash theme={null}
flashduty template get-preset --channel <channel>             # 获取预设模板代码
flashduty template validate --channel <channel> --file <path> # 验证并预览模板渲染结果
flashduty template variables [--category <category>]          # 列出可用模板变量
flashduty template functions [--type custom|sprig|all]        # 列出可用模板函数
```

支持的通知渠道：`dingtalk`、`dingtalk_app`、`feishu`、`feishu_app`、`wecom`、`wecom_app`、`slack`、`slack_app`、`telegram`、`teams_app`、`email`、`sms`、`zoom`。

### session — AI SRE 会话

用于巡查 AI SRE（以及其他 Flashduty 智能体）的会话：`session list` 列出调用者可见的会话，`session export` 将单个会话的完整事件流式导出，便于离线分析。

```bash theme={null}
flashduty session list [flags]            # 列出智能体会话（默认按 updated_at 倒序，最新在前）
flashduty session export <session_id>     # 以 NDJSON 流式导出单个会话的完整事件
```

`session list` 常用参数：

| 参数                | 说明                                                              | 默认值      |
| ----------------- | --------------------------------------------------------------- | -------- |
| `--app`           | 列出哪个智能体应用的会话                                                    | `ai-sre` |
| `--scope`         | 可见范围：`all`（自己 + 所属团队，默认）、`personal`、`team`                      | `all`    |
| `--status`        | 归档状态：`active`（默认）、`archived`、`all`                              | `active` |
| `--team-id`       | 仅保留指定团队 ID 的会话                                                  | -        |
| `--since`         | 仅保留在该时间窗口内有更新的会话（客户端过滤），如 `30d`、`24h`、`2026-05-01`              | -        |
| `--limit`         | 最多拉取的会话数                                                        | `200`    |
| `--page`          | 起始页码（1 开始）                                                      | `1`      |
| `--output-format` | 输出格式：`jsonl`（默认，每行一个会话对象，可直接管道给 `jq`）、`json`（完整信封）、`toon`（紧凑编码） | `jsonl`  |

<Note>
  服务端 `/safari/session/list` 单页上限为 100 条，超出 `--limit` 时 CLI 会自动向服务端翻页拉取，无需手动分页。API 本身没有时间窗口过滤，`--since` 是在拉取后于客户端按会话的 `updated_at` 进行过滤的。
</Note>

`session export` 将会话事件以换行分隔 JSON（NDJSON）流式写入标准输出：第一行始终是 `session_meta` 信封，其后每行是一个事件（`user_message`、`llm_call`、`tool_call`、`subagent_dispatch`、`final_answer`、`agent_text`、`error`）。导出内容可能很大，建议重定向到文件而非直接打印到终端：

```bash theme={null}
flashduty session export <session_id> > session.ndjson
flashduty session export <session_id> --include-subagents > session.ndjson
```

| 参数                    | 说明                                          |
| --------------------- | ------------------------------------------- |
| `--include-subagents` | 在每条 `subagent_dispatch` 之后递归内联该子智能体自身的完整事件流 |

### monit-agent — 主机/数据库在线诊断

通过 flashmonit 代理对目标主机或数据源执行在线诊断，无需登录目标机器。

```bash theme={null}
flashduty monit-agent catalog --target-locator <host>    # 列出该目标可用的诊断工具
flashduty monit-agent invoke  --target-locator <host> --data '<json>'  # 并发执行最多 8 个诊断工具
```

`catalog` 和 `invoke` 均需要 `--target-locator`（内网 IP、主机名或数据源名称）。`--target-kind` 可选（`host`、`mysql`、`redis` 等），不填时由代理自动推断。

`invoke` 通过 `--data` 指定要运行的工具列表，最多 8 个并发：

```bash theme={null}
flashduty monit-agent invoke --target-locator '10.0.0.1' \
  --data '{"tools":[{"tool":"os.overview"},{"tool":"disk.usage"}]}'
```

对于包含引号或逗号的 SQL 参数，推荐用 heredoc 通过 stdin 传入（`--data -`）：

```bash theme={null}
flashduty monit-agent invoke --target-locator 'db-host' --data - <<'FDUTY'
{"tools":[{"tool":"mysql.query","params":{"sql":"SELECT a, b FROM t WHERE s='RUNNING'","max_rows":50}}]}
FDUTY
```

### monit-query — 监控数据源查询

直接探测监控后端数据源（Prometheus、VictoriaLogs、Loki、MySQL），无需经过告警规则层。

```bash theme={null}
flashduty monit-query diagnose [flags]   # 预聚合 RCA 分析（日志模式或指标趋势）
flashduty monit-query rows [flags]       # 原始数据直通查询
```

`diagnose` 常用参数：

| 参数              | 说明                                                   |
| --------------- | ---------------------------------------------------- |
| `--ds-type`     | 数据源类型（必填）：`prometheus`、`victorialogs`、`loki`、`mysql` |
| `--ds-name`     | 数据源名称（必填，与控制台配置一致）                                   |
| `--input-query` | 过滤查询语句或 PromQL（必填）                                   |
| `--time-start`  | 窗口起始时间，支持相对时长如 `15m`、`1h`（默认 `15m`）                  |
| `--time-end`    | 窗口截止时间（默认 `now`，窗口最长 6 小时）                           |
| `--operation`   | `log_patterns` 或 `metric_trends`（根据数据源类型自动推断）        |

`rows` 常用参数：`--ds-type`、`--ds-name`（均必填）、`--expr`（查询表达式，必填）、`--args KEY=VALUE`（可重复）。

### 全量命令覆盖

除上述精选命令外，CLI 现已通过 spec 驱动的代码生成实现对 Flashduty OpenAPI 的「全量覆盖」（约 248 条命令），并按资源组织为顶层命令组。除 On-call 域（incident、change、channel、field、status-page、template 等）外，还覆盖了：

* **AI SRE（`safari`）**：a2a-agents、mcp-servers、sessions、skills 等
* **告警与降噪**：alert、alert-event、enrichment（alert-rules、rule-sets）、route
* **On-call 与日程**：calendar、schedule
* **平台管理**：account、member、person、team、role（roles-permissions）、audit（audit-logs）
* **监控与 RUM**：monit、rum、sourcemap
* **集成与 Webhook**：datasource（IM 集成）、webhook（integrations）

这些生成命令的叶子名称采用「资源-动作」形式（如 `flashduty safari a2a-agent-get`、`flashduty safari session-list`），其入参与返回字段直接映射到对应 API。鼓励用 `flashduty <资源> --help` 逐层探索：

```bash theme={null}
flashduty --help                 # 查看全部顶层命令组
flashduty safari --help          # 查看 AI SRE 相关的生成命令
flashduty alert --help           # 查看告警相关的生成命令
```

### 工具命令

```bash theme={null}
flashduty login          # 交互式登录
flashduty config show    # 查看当前配置
flashduty config set     # 设置配置项
flashduty version        # 打印版本信息
flashduty whoami         # 显示当前认证身份（账号 ID、邮箱、角色等）
flashduty update         # 更新到最新版本
flashduty update --check # 仅检查是否有新版本，不安装
flashduty completion     # 生成 Shell 自动补全（bash/zsh/fish/powershell）
```

<Note>
  `flashduty update` 会下载并执行平台安装脚本，将当前二进制替换为最新版本。`--check` 仅打印可用版本号，不修改本地文件。在终端中执行其他命令后，若检测到有新版本可用，CLI 会在 stderr 自动输出更新提示横幅。
</Note>

启用 Shell 自动补全示例（zsh）：

```bash theme={null}
flashduty completion zsh > "${fpath[1]}/_flashduty"
```

## 输出格式

通过 `--output-format` 选择输出形态（`--json` 是 `--output-format json` 的别名），便于在不同场景下消费：

<Tabs>
  <Tab title="表格（默认）">
    人类可读，列对齐，长字段截断显示。

    ```
    ID           TITLE                    SEVERITY   PROGRESS     CHANNEL       CREATED
    inc_abc123   DB connection timeout    Critical   Triggered    Production    2026-04-10 10:23
    inc_def456   High memory usage        Warning    Processing   Staging       2026-04-10 09:15
    Showing 2 results (page 1, total 2).
    ```
  </Tab>

  <Tab title="JSON（--json / --output-format json）">
    机器可解析，完整数据，不截断。适合脚本、CI/CD 流水线消费。

    ```bash theme={null}
    flashduty incident list --json | jq '.[].title'
    ```
  </Tab>

  <Tab title="TOON（--output-format toon）">
    TOON（Token-Oriented Object Notation）输出完整数据且不截断，但对同构数组省去了 JSON 中每行重复的字段名，列表输出可显著减少 token 消耗，更适合喂给 AI / 智能体消费。

    ```bash theme={null}
    flashduty incident list --output-format toon
    ```

    <Note>
      TOON 不能直接用 `jq` 解析；需要管道给 `jq` 时请改用 `--json`。
    </Note>
  </Tab>

  <Tab title="完整表格（--no-trunc）">
    表格视图但不截断长字段，便于复制粘贴或终端宽度较大的场景。
  </Tab>
</Tabs>

## Agent Skills

Flashduty CLI 内置 10 个 Agent Skills，可让 Claude Code、Cursor、Codex、Gemini CLI、Windsurf 等 AI 编程代理通过 CLI 操作 Flashduty。

一键安装到当前机器上检测到的所有代理：

```bash theme={null}
npx skills add flashcatcloud/flashduty-cli -y -g
```

可用技能列表：

| 技能                     | 覆盖范围                             |
| ---------------------- | -------------------------------- |
| `flashduty-shared`     | 基础：认证、三层降噪模型、全局参数、安全规则           |
| `flashduty-incident`   | 故障生命周期：分诊、调查、解决、合并、暂停、转派         |
| `flashduty-alert`      | 告警与告警事件调查：下钻、追踪、合并               |
| `flashduty-change`     | 变更事件追踪与部署频率趋势                    |
| `flashduty-oncall`     | 值班查询：当前值班人、排班详情                  |
| `flashduty-channel`    | 协作空间与分派策略查询                      |
| `flashduty-statuspage` | 状态页管理以及从 Atlassian 迁移到 Flashduty |
| `flashduty-insight`    | 分析：MTTA/MTTR、降噪率、通知趋势            |
| `flashduty-admin`      | 团队/成员查询与审计日志搜索                   |
| `flashduty-template`   | 通知模板验证与预览                        |

## 常见用法

<AccordionGroup>
  <Accordion title="在告警通知中追加 CLI 链接">
    通过 `flashduty incident get <id>` 在终端中快速查看故障详情，可将命令片段嵌入到通知模板里供值班同学一键复制。
  </Accordion>

  <Accordion title="批量认领或关闭故障">
    ```bash theme={null}
    flashduty incident ack inc_001 inc_002 inc_003
    flashduty incident close inc_001 inc_002 inc_003
    ```
  </Accordion>

  <Accordion title="将故障数据导出到 BI 工具">
    ```bash theme={null}
    flashduty incident list --since 168h --limit 500 --json > incidents.json
    ```

    然后通过 `jq` 处理或导入数据仓库。
  </Accordion>

  <Accordion title="在 CI/CD 中验证通知模板">
    ```bash theme={null}
    flashduty template validate --channel feishu --file templates/feishu.yaml
    ```

    将上述命令加入 CI，可在模板提交时立即捕获语法或字段错误。
  </Accordion>
</AccordionGroup>

<Tip>
  完整源码和问题反馈请访问 [GitHub 仓库](https://github.com/flashcatcloud/flashduty-cli)。
</Tip>
