《Cursor文档》-使用 Headless CLI

使用 Cursor 命令行界面在脚本和自动化工作流中执行代码分析、生成和重构任务。

工作方式

使用 print 模式 (-p, --print) 进行非交互式脚本编写和自动化。

在脚本中修改文件

在脚本中,将 --print--force (或 --yolo) 结合使用即可修改文件:

# 在 print 模式下允许修改文件
agent -p --force "Refactor this code to use modern ES6+ syntax"

# 不使用 --force 时,只会建议更改,不会实际应用
agent -p "Add JSDoc comments to this file"  # 不会修改文件

# 批量处理并实际修改文件
find src/ -name "*.js" | while read file; do
  agent -p --force "Add comprehensive JSDoc comments to $file"
done

--force 标志允许智能体无需确认,直接修改文件

设置

完整的设置说明请参阅安装身份验证

# 安装 Cursor 命令行界面(macOS、Linux、WSL)
curl https://cursor.com/install -fsS | bash

# 安装 Cursor 命令行界面(Windows PowerShell)
irm 'https://cursor.com/install?win32=true' | iex

# 为脚本设置 API 密钥
export CURSOR_API_KEY=your_api_key_here
agent -p "Analyze this code"

示例脚本

根据不同的脚本需求使用不同的输出格式。详见输出格式

搜索代码库

默认情况下,--print 使用 text 格式,仅输出简洁的最终答案:

#!/bin/bash
# 简单的代码库问题 - 默认使用文本格式

agent -p "What does this codebase do?"

自动代码评审

使用 --output-format json 获取结构化分析结果:

#!/bin/bash
# simple-code-review.sh - 基础代码评审脚本

echo "Starting code review..."

# 评审近期更改
agent -p --force --output-format text \
  "Review the recent code changes and provide feedback on:
  - Code quality and readability
  - Potential bugs or issues
  - Security considerations
  - Best practices compliance

  Provide specific suggestions for improvement and write to review.txt"

if [ $? -eq 0 ]; then
  echo "✅ Code review completed successfully"
else
  echo "❌ Code review failed"
  exit 1
fi

实时进度跟踪

使用 --output-format stream-json 按消息级别跟踪进度,或添加 --stream-partial-output 以流式获取增量输出:

#!/bin/bash
# stream-progress.sh - 实时跟踪进度

echo "🚀 Starting stream processing..."

# 实时跟踪进度
accumulated_text=""
tool_count=0
start_time=$(date +%s)

agent -p --force --output-format stream-json --stream-partial-output \
  "Analyze this project structure and create a summary report in analysis.txt" | \
  while IFS= read -r line; do

    type=$(echo "$line" | jq -r '.type // empty')
    subtype=$(echo "$line" | jq -r '.subtype // empty')

    case "$type" in
      "system")
        if [ "$subtype" = "init" ]; then
          model=$(echo "$line" | jq -r '.model // "unknown"')
          echo "🤖 Using model: $model"
        fi
        ;;

      "assistant")
        # 仅处理流式增量(包含 timestamp_ms,且不包含 model_call_id)。
        # 跳过工具调用前和轮次结束时的缓冲内容刷新。
        has_ts=$(echo "$line" | jq 'has("timestamp_ms")')
        has_mc=$(echo "$line" | jq 'has("model_call_id")')
        if [ "$has_ts" = "true" ] && [ "$has_mc" = "false" ]; then
          content=$(echo "$line" | jq -r '.message.content[0].text // empty')
          accumulated_text="$accumulated_text$content"
          printf "\r📝 Generating: %d chars" ${#accumulated_text}
        fi
        ;;

      "tool_call")
        if [ "$subtype" = "started" ]; then
          tool_count=$((tool_count + 1))

          # 提取工具信息
          if echo "$line" | jq -e '.tool_call.writeToolCall' > /dev/null 2>&1; then
            path=$(echo "$line" | jq -r '.tool_call.writeToolCall.args.path // "unknown"')
            echo -e "\n🔧 Tool #$tool_count: Creating $path"
          elif echo "$line" | jq -e '.tool_call.readToolCall' > /dev/null 2>&1; then
            path=$(echo "$line" | jq -r '.tool_call.readToolCall.args.path // "unknown"')
            echo -e "\n📖 Tool #$tool_count: Reading $path"
          fi

        elif [ "$subtype" = "completed" ]; then
          # 提取并显示工具结果
          if echo "$line" | jq -e '.tool_call.writeToolCall.result.success' > /dev/null 2>&1; then
            lines=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.linesCreated // 0')
            size=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.fileSize // 0')
            echo "   ✅ Created $lines lines ($size bytes)"
          elif echo "$line" | jq -e '.tool_call.readToolCall.result.success' > /dev/null 2>&1; then
            lines=$(echo "$line" | jq -r '.tool_call.readToolCall.result.success.totalLines // 0')
            echo "   ✅ Read $lines lines"
          fi
        fi
        ;;

      "result")
        duration=$(echo "$line" | jq -r '.duration_ms // 0')
        end_time=$(date +%s)
        total_time=$((end_time - start_time))

        echo -e "\n\n🎯 Completed in ${duration}ms (${total_time}s total)"
        echo "📊 Final stats: $tool_count tools, ${#accumulated_text} chars generated"
        ;;
    esac
  done

使用图像

要向智能体发送图像、媒体文件或其他二进制数据,请在提示词中提供文件路径。智能体可通过工具调用读取任何文件,包括图像、视频和其他格式的文件。

在提示词中加入文件路径

只需在提示词中引用文件路径。智能体会在需要时自动读取相应文件:

# 分析图像
agent -p "Analyze this image and describe what you see: ./screenshot.png"

# 处理多个媒体文件
agent -p "Compare these two images and identify differences: ./before.png ./after.png"

# 在文本指令中结合使用文件路径
agent -p "Review the code in src/app.ts and the design mockup in designs/homepage.png. Suggest improvements to match the design."

工作原理

当您在提示词中包含文件路径时:

  1. 智能体会收到包含文件路径引用的提示词
  2. 智能体会通过工具调用自动读取文件
  3. 图像会被自动处理
  4. 您可以使用相对路径或绝对路径引用文件

示例:图像分析脚本

#!/bin/bash
# analyze-image.sh - 使用 Headless CLI 分析图像

IMAGE_PATH="./screenshots/ui-mockup.png"

agent -p --output-format json \
  "Analyze this image and provide a detailed description: $IMAGE_PATH" | \
  jq -r '.result'

示例:批量处理媒体文件

#!/bin/bash
# process-media.sh - 批量处理媒体文件

for image in images/*.png; do
  echo "Processing $image..."
  agent -p --output-format text \
    "Describe what's in this image: $image" > "${image%.png}.description.txt"
done

文件路径可以是相对于当前工作目录的相对路径,也可以是绝对路径。
智能体会通过工具调用读取文件,因此请确保文件存在,
并可从运行命令的位置访问。

羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

小夜