OpenCode CLI 命令行模式完全指南:用 AI 编程助手构建自动化脚本

在日常开发中,我们习惯在终端中启动 OpenCode 的 TUI 界面,通过对话完成代码编写、重构和调试。但 OpenCode 的价值远不止于此——它提供了一套完善的 CLI 命令行工具,让你可以在脚本、定时任务和 CI/CD 管道中以非交互方式调用 AI 编程能力。

本文将深入讲解 OpenCode 的命令行模式,涵盖 opencode runopencode serve、自动化脚本编写、GitHub Actions 集成等实战场景。

为什么需要命令行模式?

大多数时候,我们通过 opencode 命令启动交互式 TUI 来和 AI 对话。但在以下场景中,命令行模式才是最优解:

  • 批量任务处理:定时对代码库进行安全检查、依赖更新、代码格式化
  • CI/CD 集成:在 GitHub Actions 或 GitLab CI 中自动审查 PR、修复 Issue
  • 脚本化调用:在其他工具或工作流中嵌入 AI 编程能力
  • 服务化部署:启动后端服务供 Web 端或移动端调用

OpenCode 提供了三种非交互模式:run(单次执行)、serve(HTTP 服务)、web(Web 界面)。

opencode run:单次执行模式

opencode run 是自动化脚本的核心命令。它接收一条消息作为参数,在非交互模式下执行,然后退出。

opencode run "Explain the use of context in Go"

这会在终端直接输出结果,非常适合在脚本中获取 AI 的回答。

核心参数详解

opencode run [message...] [flags]

常用参数:

| 参数 | 说明 |
|------|------|
| --model, -m | 指定模型,格式 provider/model |
| --agent | 指定 Agent |
| --file, -f | 附加文件到消息中 |
| --share | 自动分享会话 |
| --title | 设置会话标题 |
| --format | 输出格式(defaultjson) |
| --auto | 自动批准未明确拒绝的权限 |

实战示例:审查代码文件

opencode run --model anthropic/claude-sonnet-4-20250514 \
  --file src/app.ts \
  "Review this file for security vulnerabilities"

使用 JSON 格式输出:

opencode run --format json "Check if package.json has outdated dependencies"

JSON 输出格式让其他程序更容易解析处理结果。

在 Shell 脚本中集成

你可以将 opencode run 嵌入到 Bash 脚本中,实现自动化工作流:

#!/bin/bash
# auto-review.sh - 自动审查 Git 变更文件

CHANGED_FILES=$(git diff --name-only HEAD~1)
for file in $CHANGED_FILES; do
  if [[ $file == *.ts ]] || [[ $file == *.tsx ]]; then
    echo "Reviewing $file..."
    opencode run --model anthropic/claude-sonnet-4-20250514 \
      --file "$file" \
      "Review this file for bugs, performance issues, and type safety problems"
  fi
done

这个脚本可以配置在 Git hooks 中,每次提交前自动审查变更的 TypeScript 文件。

opencode serve:HTTP 服务模式

opencode serve 启动一个无界面的 HTTP 服务器,提供 REST API 接口。这让你可以通过 HTTP 请求调用 OpenCode,非常适合集成到 Web 应用或微服务架构中。

opencode serve --port 4096 --hostname 0.0.0.0

API 调用示例

服务器启动后,可以通过 HTTP API 创建会话并发送消息:

# 创建新会话
SESSION_ID=$(curl -s -X POST http://localhost:4096/session \
  -H "Content-Type: application/json" \
  -d '{}' | jq -r '.id')

# 发送消息
curl -s -X POST "http://localhost:4096/session/$SESSION_ID/message" \
  -H "Content-Type: application/json" \
  -d '{
    "parts": [{
      "type": "text",
      "text": "Find all unused imports in the codebase"
    }]
  }' | jq '.parts[].text'

安全认证

通过环境变量设置 HTTP Basic Auth:

OPENCODE_SERVER_PASSWORD=your-secure-password opencode serve

客户端调用时需携带认证信息:

curl -u opencode:your-secure-password http://localhost:4096/session

服务化架构的优势

opencode serve 采用客户端-服务器架构——TUI 本身就是服务器的一个客户端。这意味着你可以:

  • 在服务器上保持 MCP 连接池,避免每次请求都冷启动
  • 通过 opencode attach 从远程终端连接到运行中的服务器
  • 在 IDE 插件中通过 /tui API 控制前端界面
# 在终端 A 启动服务
opencode serve --port 4096

# 在终端 B 连接到同一服务
opencode run --attach http://localhost:4096 "Explain async/await in JavaScript"

使用 --attach 参数可以复用已启动服务的 MCP 连接和模型上下文,显著减少延迟。

在 GitHub Actions 中集成

OpenCode 官方支持 GitHub Actions,可以在 Issue 评论和 PR 中触发自动化操作。

基础工作流配置

name: opencode
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]

jobs:
  opencode:
    if: |
      contains(github.event.comment.body, '/oc') ||
      contains(github.event.comment.body, '/opencode')
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 1
          persist-credentials: false
      - uses: anomalyco/opencode/github@latest
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        with:
          model: anthropic/claude-sonnet-4-20250514

添加配置后,在 Issue 或 PR 中评论 /opencode fix this,OpenCode 会自动创建分支、实现修改并提交 PR。

自动 PR 审查

name: opencode-review
on:
  pull_request:
    types: [opened, synchronize, ready_for_review]

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
      pull-requests: read
    steps:
      - uses: actions/checkout@v6
        with:
          persist-credentials: false
      - uses: anomalyco/opencode/github@latest
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          model: anthropic/claude-sonnet-4-20250514
          use_github_token: true
          prompt: |
            Review this pull request:
            - Check for code quality issues
            - Look for potential bugs
            - Suggest improvements

定时任务示例

通过 schedule 事件,可以让 OpenCode 按计划执行:

on:
  schedule:
    - cron: "0 9 * * 1"  # 每周一 UTC 9:00

jobs:
  opencode:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: write
      pull-requests: write
    steps:
      - uses: anomalyco/opencode/github@latest
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        with:
          model: anthropic/claude-sonnet-4-20250514
          prompt: |
            Review the codebase for TODO comments and create a summary.
            If you find issues worth addressing, open an issue to track them.

在 GitLab CI 中集成

OpenCode 同样支持 GitLab CI/CD,通过社区提供的 CI 组件可以快速接入:

include:
  - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2
    inputs:
      config_dir: ${CI_PROJECT_DIR}/opencode-config
      auth_json: $OPENCODE_AUTH_JSON
      message: "Review this merge request for code quality issues"

或者通过自定义 GitLab CI 配置,实现 Duo 风格的 @opencode 评论触发:

image: node:22-slim
commands:
  - npm install --global opencode-ai
  - opencode run "You are an AI assistant helping with GitLab operations.
    Task: $AI_FLOW_INPUT
    Please execute the requested task using the glab CLI."

实用自动化脚本示例

代码健康检查

#!/bin/bash
# health-check.sh

PROJECT_DIR=${1:-.}
cd "$PROJECT_DIR" || exit 1

echo "Running code health check..."

opencode run \
  --model anthropic/claude-sonnet-4-20250514 \
  "Analyze the codebase and identify:
   1. Unused dependencies in package.json
   2. Deprecated API usage
   3. Missing error handling
   4. Potential memory leaks

   Output a structured report with file paths and line numbers."

批量代码迁移

#!/bin/bash
# migrate-apis.sh
# 将旧版 API 调用迁移到新版

for file in $(find src -name "*.ts" -exec grep -l "oldApiCall" {} \;); do
  echo "Migrating $file..."
  opencode run --file "$file" \
    "Replace all calls to 'oldApiCall' with the new 'newApiCall' signature.
     The new signature takes (userId: string, options: RequestOptions) instead of (id: number, config: any).
     Update type definitions accordingly."
done

自动生成变更日志

#!/bin/bash
# generate-changelog.sh

COMMITS=$(git log --oneline $(git describe --tags --abbrev=0)..HEAD)

opencode run \
  "Generate a CHANGELOG.md entry from these commits:
   $COMMITS

   Categorize into Features, Bug Fixes, and Refactoring.
   Format each entry with the commit hash and a clear description."

环境变量与配置技巧

OpenCode CLI 支持通过环境变量微调行为:

# 启用实验性功能
export OPENCODE_EXPERIMENTAL=true

# 设置非交互模式下的权限
export OPENCODE_PERMISSION='{"bash":{"allow":true},"read":{"allow":true},"edit":{"allow":true}}'

# 禁用自动更新检查
export OPENCODE_DISABLE_AUTOUPDATE=true

# 指定配置文件路径
export OPENCODE_CONFIG=/path/to/opencode.json

opencode run "Your automated task here"

总结

OpenCode 的命令行模式为 AI 编程助手打开了自动化的大门。无论是通过 opencode run 嵌入脚本、opencode serve 搭建服务,还是在 GitHub Actions 和 GitLab CI 中集成,OpenCode 都能在非交互场景下发挥强大能力。

关键要点:

  • opencode run 适合单次执行的自动化任务,支持多种输出格式
  • opencode serve 提供 REST API,适合微服务和远程调用场景
  • GitHub Actions 集成支持 PR 审查、Issue 修复和定时任务
  • 结合 Git hooks 和 Shell 脚本,可实现代码健康检查、批量迁移等自动化工作流
  • 环境变量和配置文件提供了精细化的权限和行为控制

试试将这些技巧应用到你的日常开发中,让 AI 编程助手成为你自动化工作流的一部分。