# 无头模式与自动化

> 在脚本中使用打印模式，明确写入权限、媒体路径和结果处理。

- 网址：https://funcoding.ai/agents/cursor/cli/headless/
- 核实日期：2026-10-07（命令、配置和价格以官方文档为准）
- 官方来源：[Cursor 官方文档：Using Headless CLI](https://cursor.com/docs/cli/headless)、[Cursor 官方文档：Permissions](https://cursor.com/docs/cli/reference/permissions)、[Cursor 官方文档：Parameters](https://cursor.com/docs/cli/reference/parameters)、[Cursor 官方文档：Output format](https://cursor.com/docs/cli/reference/output-format)

---
`-p` 或 `--print` 用于非交互脚本，把结果输出到控制台。它改变交互方式，不构成只读权限边界。

## 开始运行

先按[认证说明](https://funcoding.ai/agents/cursor/cli/authentication/)设置 CURSOR_API_KEY，再运行：

```bash
agent -p "Explain how authentication works in this repository"
```

需要账号当前可用的模型列表时运行 `agent models`；模型参数形式为 `--model <model>`。默认输出 text，只含最后一条助手消息。

## 文件修改与权限

官方 Headless 页示例用 `--force` 启用无需确认的修改：

```bash
agent -p --force "Update the documentation for the current public API"
```

但该页同时称“不加 --force 只提出修改”，而当前 Parameters、Permissions 和 Using 页明确说明打印模式可使用 write 和 shell 工具。因此不要依赖省略 --force 来保证只读。实际执行应由模式、permissions.allow、permissions.deny 与沙箱共同控制；`--force` 自动允许未被显式拒绝的命令。

自动化需要严格限制时，先配置[权限规则](https://funcoding.ai/agents/cursor/cli/permissions/)，检查工作目录与可修改范围，再运行实际任务。

## 图片与文件路径

可直接在提示中引用相对或绝对文件路径，Agent 按需用工具读取：

```bash
agent -p "Compare these screenshots: ./before.png ./after.png"
```

路径相对于当前工作目录解析，文件必须存在并可访问。无需把二进制内容塞入提示文本。

## 消费结果

| 输出 | 适合用途 |
| --- | --- |
| text | 只需最终回复 |
| json | 完成后解析一个结果对象 |
| stream-json | 逐行消费事件与工具进度 |

`--stream-partial-output` 配合 stream-json 输出更细的文本增量。失败时须检查退出码和 stderr，JSON 不保证产生完整结果，流也可能缺少终止事件。字段与去重细节见[JSON 与流式事件](https://funcoding.ai/agents/cursor/cli/output-format/)。

在 CI 中将密钥、Agent 工作和发布步骤分开配置，见[GitHub Actions](https://funcoding.ai/agents/cursor/cli/github-actions/)。
