OpenCode 2.1 常用 CLI 命令详解

OpenCode 2.1.3 命令行全量实测详解:TUI 交互、run/models/auth/mcp/session/service/serve/api/debug 等全部子命令的参数与真实回显,附最小 MCP 服务器脚本、shell 补全与排障实录。

OpenCodeOpenCode人工智能LLM2026/10/23

OpenCode 2.1 常用 CLI 命令详解

目标:逐条实测讲解 OpenCode 2.1.3 的命令行体系——主命令与 TUI 交互、17 个子命令(run/models/auth/mcp/session/service/serve/api/debug/plugin/stats 等)的参数与真实回显、shell 补全与排障技巧。全部输出在 Ubuntu 22.04(x86_64)+ OpenCode 2.1.3 + 本地 Ollama 0.40.8 环境实测取得,实测日期 2026-10-23,输出逐行照抄未做修饰。

一、环境信息

  • 操作系统:Ubuntu 22.04.5 LTS(x86_64)
  • OpenCode:2.1.3(npm install -g @opencode/cli 安装,安装过程见《Ubuntu 22.04 安装 OpenCode 2.1 指南》)
  • LLM 后端:Ollama 0.40.8(OpenAI 兼容端点 http://127.0.0.1:11434/v1),provider 配置见《OpenCode 2.1 配置参数详解》5.1 节
  • 演示模型:qwen2.5:0.5b / qwen3:0.6b / qwen2.5-coder:1.5b
  • 工作项目:/root/demo-app(含 calc.py,已 git init)
  • 实验账号:root;凭据变量 OLLAMA_API_KEY=ollama(本地 Ollama 不校验值)

版本确认:

opencode --version

实测回显:

opencode v2.1.3

二、工具概览

OpenCode 2.x 采用"客户端 + 本地后台服务"架构:默认首次运行会拉起一个本机后台服务,之后的 TUI、run、models 等命令都连到该服务(会话、状态全局共享);--standalone 强制本次运行使用独立私有服务,--server 可连到指定 URL 的服务。主命令结构(实测 opencode --help 全文):

DESCRIPTION
  OpenCode command line interface

USAGE
  opencode <subcommand> [flags] [<directory>]

ARGUMENTS
  directory string    Directory to start OpenCode in (optional)

FLAGS
  --standalone            Run with a private server instead of the background service
  --server string         Connect to a server URL instead of the background service
  --auto                  Auto-approve permissions that are not explicitly denied
  --continue, -c          Continue the last session
  --session, -s string    Session ID to continue, or to create if it does not exist
  --prompt string         Prompt to use

GLOBAL FLAGS
  --help, -h                                                          Show help information
  --version, -v                                                       Show version information
  --wizard                                                            Start wizard mode for a command
  --completions <bash|zsh|fish|sh>                                    Print shell completion script (choices: bash, zsh, fish, sh)
  --log-level <all|trace|debug|info|warn|warning|error|fatal|none>    Sets the minimum log level (choices: all, trace, debug, info, warn, warning, error, fatal, none)
  --print-logs                                                        Print logs to stderr (server logs require --standalone)

SUBCOMMANDS
  upgrade, update    Upgrade OpenCode to the latest or a specific version
  uninstall          Uninstall OpenCode, keeping session data, configuration, and state
  acp                Start an Agent Client Protocol server
  api                Make a request to the running server
  debug              Debugging and troubleshooting tools
  auth               manage integrations and credentials
  mcp                Manage MCP (Model Context Protocol) servers
  plugin             Manage plugins
  models             List all available models
  stats              Show shareable usage statistics
  mini               Start the minimal interactive interface
  run                Run OpenCode with a message
  session            Manage sessions
  service            Manage the background server
  reload             Reload configuration
  pair               Print one-time links to connect a browser or app
  serve              Start the v2 API and web server

命令分四类:会话类(主命令 TUI、run、mini)、资产类(models、auth、mcp、plugin、session、stats)、服务类(service、serve、api、pair、acp)、运维类(debug、reload、upgrade、uninstall)。后台服务地址与状态随时可用 opencode service status 查看(实测返回 http://127.0.0.1:49374)。

三、前置条件

  1. 安装并验证版本(见《Ubuntu 22.04 安装 OpenCode 2.1 指南》);
  2. 一个可用模型:免费模型组零配置可用,或按《OpenCode 2.1 配置参数详解》配置商业凭据/本地 Ollama provider;
  3. 本文所有会话类命令示例在 OLLAMA_API_KEY 已导出的环境执行(export OLLAMA_API_KEY=ollama)。

四、会话类命令:TUI 主命令、run、mini

4.1 主命令(TUI)

不带子命令直接运行 opencode(可带项目目录参数)即进入交互式 TUI:

cd /root/demo-app
opencode

实测界面(终端文本截取,2026-10-23):

                                                                 ▄
                                                                █▀▀█ █▀▀█ █▀▀█ █▀▀▄ █▀▀▀ █▀▀█ █▀▀█ █▀▀█
                                                                █  █ █  █ █▀▀▀ █  █ █    █  █ █  █ █▀▀▀
                                                                ▀▀▀▀ █▀▀▀ ▀▀▀▀ ▀  ▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀

  ┃
  ┃  Ask anything… "Fix broken tests"
  ┃
  ┃  Build · Qwen2.5 0.5B Ollama
  ╹▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
  ~/demo-app:master                         shift+tab agents  ctrl+p commands

要点:输入框提示 Ask anything…;Build · Qwen2.5 0.5B Ollama 表示当前 Agent 为 build、模型来自配置的 Ollama provider;底部左侧为当前项目与 git 分支,右侧两个核心快捷键——shift+tab 切换 Agent(build ⇄ plan)、ctrl+p 打开命令面板。

发送一条消息后的实测界面(模型真实回复,统计行逐字照抄):

  ┃  用一句话说明 calc.py 中 add 函数的作用

     add 函数负责将两个数字相加。

     Build · Qwen2.5 0.5B · 7.8s · 1.4 tok/s

右侧边栏同步显示流式输出与上下文用量:Context 2,061 tokens / 6% used。

TUI 内常用命令(斜杠命令,实测可用的入口):

命令/快捷键作用实测表现
/models切换模型打开 Select model 列表
/connect连接模型账号录入商业凭据
/mcps管理 MCP 服务器连接OAuth 授权入口
/update安装更新/升级 2.x见《Ubuntu 22.04 安装 OpenCode 2.1 指南》第十章
shift+tabbuild/plan Agent 切换底栏常驻提示
ctrl+p命令面板底栏常驻提示

/models 打开的模型选择器实测(文本截取):Free 分组(MiMo-V2.6-Flash Free、DeepSeek V4.1 Flash Free、GLM-5.3-Flash Free、Nemotron 3.5 Lightning Free、Nemotron 3 Ultra Free、Big Pickle)、Ollama 分组(Qwen2.5 Coder 1.5B、● Qwen2.5 0.5B、Qwen3 0.6B)、Ollama Cloud 分组依次列出,底部提示 Connect an integration ctrl+a · Favorite ctrl+f——自配 provider 的模型会实时出现在选择器中。

主命令的其他 flags(--continue/--session/--prompt 等)与 run 语义一致,见 4.2。

4.2 run:非交互一次性执行

opencode run 是脚本化与 CI 场景的主力——发送一条消息、拿到回复即退出。参数表(实测 opencode run --help):

DESCRIPTION
  Run OpenCode with a message

USAGE
  opencode run [flags] [<message...>]

ARGUMENTS
  message... string    Message to send (optional)

FLAGS
  --standalone            Run with a private server instead of the background service
  --server string         Connect to a server URL instead of the background service
  --continue, -c          Continue the last session
  --session, -s string    Session ID to continue, or to create if it does not exist
  --fork                  Fork the session before continuing
  --model, -m string      Model to use in the format provider/model#variant
  --agent string          Agent to use
  --format choice         Output format (choices: default, json)
  --file, -f string       File to attach to the message
  --title string          Session title
  --thinking              Show thinking blocks
  --auto                  Auto-approve permissions that are not explicitly denied

基础用法实测:

cd /root/demo-app
opencode run "请用一句话回答:calc.py 里的 add 函数是做什么的?"

实测回显:


> build · qwen2.5:0.5b
"a函数"

首行 > build · qwen2.5:0.5b 标注本次会话的 Agent 与模型;回复内容原样输出。0.5B 模型回答质量有限属模型能力问题,链路本身(配置解析 → OpenAI 兼容请求 → 响应 → 终端输出)完整可用。

指定模型实测(--model,绕开配置默认值):

opencode run --model ollama/qwen3:0.6b --auto "在当前目录创建 hello.txt,内容为一行文字 hello opencode,然后告诉我你完成了"

实测回显:


> build · qwen3:0.6b
← Write /currentDirectory
Created file successfully: /currentDirectory
> build · qwen3:0.6b
The file has been successfully created in the /currentDirectory directory.

要点:← Write 行是 Agent 真实调用了内置 write 工具并成功创建文件(工具协议链路打通);小模型把"当前目录"理解成了字面路径 /currentDirectory(文件确实创建在那里,内容正确),这是本地小模型的典型失误,生产用 7B+ 模型。--auto 放行了未被显式 deny 的权限,无人值守跑 agent 任务必备。

带思考块与 JSON 输出:--thinking 显示模型的 thinking 块(qwen3 系列实测输出 <think>…</think> 段落);--format json 输出结构化会话 JSON 供程序处理。附加文件用 --file(如日志、截图)。

会话延续:-c 接续最近一次会话;-s <ID> 接续指定会话(ID 从 opencode session list 获取);--fork 复制一份会话再继续,不影响原会话。

⚠️ 注意:run 与 TUI 共享后台服务的会话存储——run 创建的会话在 TUI 里同样可见,反之亦然;脚本化批量执行时建议加 --standalone 隔离出私有服务,避免与交互会话互相干扰。

4.3 mini:极简交互界面

opencode mini 是精简版交互界面(单输入框 + 流式回复,无侧栏)。参数与 run/TUI 类似(实测 --help):--continue/-c、--session/-s、--fork、--replay(恢复历史,默认 200 条上限 --replay-limit)、--model/-m、--agent、--prompt。适合低带宽 SSH 会话或仅需要"问答式"交互的场景。参数默认值实测标注:--replay-limit 默认 200。

五、资产类命令:models、auth、stats

5.1 models:列出可用模型

opencode models [flags]

实测(过滤 ollama 相关):

opencode models | grep -E 'ollama' | head -6

回显:

ollama-cloud/beam
ollama-cloud/deepseek-v4-pro
ollama-cloud/deepseek-v4-pro:0813
ollama-cloud/deepseek-v4.1-flash
ollama-cloud/deepseek-v4.1-flash:1017
ollama/qwen2.5:0.5b

输出为 provider/model 全量清单:内置目录(models.dev)、自配 provider(ollama/qwen2.5:0.5b,实测精确匹配 grep -x 'ollama/qwen2.5:0.5b.*' 有输出)、官方云服务(ollama-cloud)混排。该命令只读,用于确认某 provider/model 引用是否存在——配置 model 键前先在这里核对是最快路径。

5.2 auth:凭据管理

SUBCOMMANDS
  list      list integrations and credentials
  login     connect an integration
  logout    log out of a saved account
  export    print stored credentials, including secrets, as JSON
  import    import credentials exported by auth export
  switch    switch the active account for an integration

实测 opencode auth list(当前环境凭据来自环境变量):

Ollama        OLLAMA_API_KEY              environment
Ollama Cloud  OLLAMA_API_KEY              environment

三列分别是集成名、凭据变量名、来源。要点:

  • auth login 以向导方式接入商业 provider(也可在 TUI 用 /connect,效果相同);
  • auth export 会输出含密钥的 JSON,迁移凭据到新机器用 auth export > cred.json + auth import cred.json 组合;⚠️ 导出文件含明文密钥,用完即删;
  • 同一集成多账号时用 auth switch 切换活动账号。

5.3 stats:用量统计

opencode stats [flags]

实测(当天用量,有真实会话记录后):

opencode stats · today · all projects

activity
   Oct
Mo

Tu

We

Th █

Fr

Sa

Su

   less ·░▒▓█ more

输出活动热力日历;进阶 flags:--days N(近 N 天,0 为今天)、--year(整年)、--all(全部历史)、--project .(限当前项目)、--models(按模型用量)、--tools(工具可靠性)、--cost(成本与 token 明细)、--full(全部明细)、--json(结构化输出)。团队内评估"谁/哪个模型消耗多、哪个模型工具调用失败率高"就用 --models --tools --cost --full。

六、MCP 与插件:mcp、plugin

6.1 mcp:MCP 服务器管理

SUBCOMMANDS
  list      List configured MCP servers and their status
  add       Add an MCP server to your configuration
  auth      Authenticate with an OAuth-capable remote MCP server
  logout    Remove stored OAuth credentials for an MCP server

add 实测(注册一个本地 stdio 服务器;测试服务器为按 MCP stdio 协议应答的最小 Node 脚本):

opencode mcp add echo -- node /root/mcp/echo-mcp.mjs

回显:

MCP server "echo" added to /root/demo-app/opencode.json

写入的项目配置(实测 cat /root/demo-app/opencode.json):

{
  "mcp": {
    "servers": {
      "echo": {
        "type": "local",
        "command": [
          "node",
          "/root/mcp/echo-mcp.mjs"
        ]
      }
    }
  }
}

-- 之后是启动命令;--global 写入全局配置而非项目配置;远程服务器用 --url:opencode mcp add context7 --url https://mcp.context7.com/mcp。

测试用的最小 MCP stdio 服务器脚本 /root/mcp/echo-mcp.mjs(完整可运行,实现 initialize/ping/tools/list/tools/call 四个方法):

// 最小 MCP stdio 服务器:initialize / tools/list / tools/call
let buf = "";
process.stdin.on("data", (d) => {
  buf += d.toString();
  let idx;
  while ((idx = buf.indexOf("\n")) >= 0) {
    const line = buf.slice(0, idx).trim();
    buf = buf.slice(idx + 1);
    if (!line) continue;
    let msg; try { msg = JSON.parse(line); } catch { continue; }
    handle(msg);
  }
});
const send = (m) => process.stdout.write(JSON.stringify(m) + "\n");
function handle(msg) {
  if (msg.method === "initialize") {
    send({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: msg.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "echo-mcp", version: "1.0.0" } } });
  } else if (msg.method === "ping") {
    send({ jsonrpc: "2.0", id: msg.id, result: {} });
  } else if (msg.method === "tools/list") {
    send({ jsonrpc: "2.0", id: msg.id, result: { tools: [{ name: "echo", description: "Echo back the input text", inputSchema: { type: "object", properties: { text: { type: "string", description: "text to echo" } }, required: ["text"] } }] } });
  } else if (msg.method === "tools/call") {
    const text = msg.params?.arguments?.text ?? "";
    send({ jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "text", text: "echo: " + text }] } });
  }
}

list 实测(配置改动后先 reload 再 list):

opencode reload
opencode mcp list

回显:

Configuration reloaded
✓ echo  connected

✓ connected 表示 stdio 子进程已按 MCP 协议完成握手。OAuth 型远程服务器首次 list 会显示 needs authentication,此时执行 opencode mcp auth <名称> 走浏览器授权,完成后同位置显示 connected;opencode mcp logout <名称> 清除已存的 OAuth 凭据。

⚠️ 排障实录:mcp add 刚写入配置后立即 mcp list 实测出现过 No MCP servers configured——后台服务尚未拾取新配置;执行 opencode reload 后即显示 ✓ echo connected。配置类改动后 reload 是标准动作。

6.2 plugin:插件管理

SUBCOMMANDS
  list      List plugins
  add       Install a plugin and add it to the global configuration
  check     Check package plugins for updates
  update    Update package plugins
  remove    Remove a plugin from global configuration

plugin add <包名或本地目录> 安装并写入全局配置(等价于在配置 plugins 数组手工登记);check/update 管理包型插件的版本。空环境实测 opencode plugin list 无输出(未装任何插件)。

七、服务类命令:session、service、serve、api、pair、acp

7.1 session:会话管理

SUBCOMMANDS
  list      List top-level sessions in the current project, newest first
  delete    Delete a session and its child sessions
  export    Export session data as JSON
  import    Import session data from a JSON file or URL

实测 opencode session list(本章 4.2 的 run 实测留下的真实会话):

ses_e9a5e32ccffenjx4M6ppMr5rEA  add 函数的作用是向包含的列表添加元素。  10/22/2026, 10:01:12 PM
ses_e9a5f25f7ffeLvlCxoRACBsUWM  hi.txt contents hello opencode  10/22/2026, 10:00:32 PM
ses_e9a5fdfc3ffekvNEdAfUCOWF8A  create hello.txt        10/22/2026, 9:59:54 PM
ses_e9a60b42bffeo346Q58i9AizGk  Create and update hello.txt     10/22/2026, 9:58:33 PM
ses_e9a61954affeyx9yqeNeGA9RoA  calc.py: add函数用于向列表中添加元素。  10/22/2026, 9:57:32 PM

三列:会话 ID(ses_ 前缀)、自动生成的标题、时间(新到旧)。会话 ID 正是 opencode run -s <ID> 与 --continue 的接续凭据;session export <ID> 导出 JSON(可再 session import 导入到其他机器或从 URL 恢复);session delete <ID> 连同子会话一起删除。

7.2 service:后台服务管理

SUBCOMMANDS
  start      Start the background server
  restart    Restart the background server
  status     Show background server status
  stop       Stop the background server
  get        Get service configuration
  set        Set service configuration
  unset      Unset service configuration

实测:

opencode service status

回显:

http://127.0.0.1:49374

后台服务监听本机回环地址;改配置/升级后 opencode service restart,排查"配置明明改了却不生效"时先 restart 再 reload。get/set/unset 管理服务级配置项。无 systemd 的最小化环境同样可用(服务由 CLI 自管,实测通过)。

7.3 serve:独立 v2 API 与 Web 服务

opencode serve [flags]

FLAGS 实测:--hostname、--port、--cors(追加允许的 CORS 源,可重复)、--service、--stdio。

实测(起在 4321 端口):

opencode serve --port 4321 &

回显:

server listening on http://127.0.0.1:4321
server password 9zH4GOKffwsKBjDI8Leq9rJQ7XUhS67E8UDaFqFUktM
curl -s -o /dev/null -w "root=%{http_code}\n" http://127.0.0.1:4321/

回显:

root=200

要点:serve 对外提供 v2 API 与 Web 界面;首次启动自动生成一次性 server password(实测回显第二行),API 请求需携带该凭据——未带凭据访问 API 返回(实测 curl -s http://127.0.0.1:4321/api/config):

{"_tag":"UnauthorizedError","message":"Authentication required"}

⚠️ 注意:serve 是把 OpenCode 暴露为网络服务的方式,务必只在内网/回环使用并妥善保管 server password;公网暴露场景应放在反向代理与认证之后。

7.4 api:调用运行中服务

USAGE
  opencode api [flags] <operation | method path...>

ARGUMENTS
  operation | method path... string OpenAPI operation ID, or an HTTP method followed by a path

FLAGS
  --standalone           Run with a private server instead of the background service
  --server string        Connect to a server URL instead of the background service
  --data, -d string      Request body
  --header, -H string    Request header in name:value form
  --param key=value      OpenAPI path or query parameter

opencode api 是对运行中服务的官方 CLI 封装:可用 OpenAPI operation ID 或 方法 + 路径 直接请求(如 opencode api get /config),--param 传路径/查询参数,-d 传请求体,-H 加头。比起裸 curl 免去自行处理鉴权与地址拼接,适合脚本化取会话/项目数据。

7.5 pair 与 acp:多端接入

pair(实测 --help):打印一次性配对链接,把浏览器/App 连到本机服务:

DESCRIPTION
  Print one-time links to connect a browser or app

FLAGS
  --url string    Use an external HTTP(S) server URL in pairing links
  --remote        Pair through the OpenTunnel remote address, enabling remote access if needed (exposes the server to the internet)
  --yes, -y       Accept exposing the server to the internet when --remote enables remote access for the first time (required without an interactive terminal)

官方文档明确:链接一次性有效、5 分钟过期。--remote 会经 OpenTunnel 把服务暴露到公网(官方标注风险,非交互终端必须显式 -y 确认),生产慎用。

acp:启动 Agent Client Protocol(ACP)服务器,供支持 ACP 的编辑器/客户端接入;--login 直接进入登录流程而非起服务。

八、运维类命令:debug、reload、upgrade、uninstall

8.1 debug:诊断三件套

SUBCOMMANDS
  agents    List all agents
  config    List configuration sources
  paths     Show global paths (data, config, cache, state)

debug paths 实测回显:

home       /root
data       /root/.local/share/opencode
cache      /root/.cache/opencode
config     /root/.config/opencode
state      /root/.local/state/opencode
tmp        /tmp/opencode
bin        /root/.cache/opencode/bin
log        /root/.local/share/opencode/log
repos      /root/.local/share/opencode/repos
db         /root/.local/share/opencode/opencode.db

debug config 实测(列出全部配置源与合并结果;凭据已脱敏):

[
  {
    "type": "document",
    "path": "/root/.config/opencode/opencode.json",
    "info": {
      "$schema": "https://opencode.ai/config.json",
      "model": {
        "providerID": "ollama",
        "model": "qwen2.5:0.5b"
      },
      ...

debug agents 实测(内置 Agent 的权限细节):

[
  {
    "id": "build",
    "name": "Build",
    "request": {
      "settings": {},
      "headers": {},
      "body": {}
    },
    "description": "The default agent. Executes tools based on configured permissions.",
    "mode": "primary",
    "hidden": false,
    "permissions": [
      {
        "action": "*",
        "resource": "*",
        "effect": "allow"
      },
      {
        "action": "read",
        "resource": "*.env",
        "effect": "ask"
      },
      ...

价值点:build 默认放行一切(* → allow),但对读取 .env/.env.* 强制询问——内置的密钥文件保护策略,权限排障时先看这里。

8.2 reload:重载配置

实测回显:

Configuration reloaded

改配置文件、mcp add/plugin add 之后的标配动作(见 6.1 排障实录)。

8.3 upgrade / update:升级

DESCRIPTION
  Upgrade OpenCode to the latest or a specific version

USAGE
  opencode upgrade [flags] [<target>]

ARGUMENTS
  target string    Version to upgrade to (with or without a leading v) (optional)

FLAGS
  --method, -m choice    Installation method to use (choices: curl, npm, pnpm, bun, yarn, vp, brew, winget)

用法:opencode upgrade(同线最新)、opencode upgrade 2.1.3(指定版本)、opencode upgrade --major(跨大版本升 OpenCode 2 的显式动作);--method 在安装方式识别错误时强制指定。升级策略与 1.x/2.x 版本线关系见《Ubuntu 22.04 安装 OpenCode 2.1 指南》第三章、第十章。

8.4 uninstall:卸载

DESCRIPTION
  Uninstall OpenCode, keeping session data, configuration, and state

USAGE
  opencode uninstall [flags]

FLAGS
  --dry-run      Show what would be removed without removing
  --force, -f    Skip confirmation prompts

实测预演:

┌  Uninstall OpenCode
│
●  Installation method: curl
│
│  The following global files will be removed (shared by OpenCode versions and channels):
│
●    Cache: /root/.cache/opencode
│
●    Binary (manual removal): /root/.opencode/bin/opencode
│
▲  Dry run - no changes made
│
└  Done

--dry-run 先看将删什么,-f 真删;会话数据、配置与状态保留(完整卸载清理步骤见安装指南第十二章)。

九、全局 flags 速查

所有子命令共享(实测 --help 汇总):

flag作用备注
--help, -h帮助任意子命令可加
--version, -v版本opencode v2.1.3
--wizard向导模式启动该命令交互式补齐参数
--completions <bash|zsh|fish|sh>输出 shell 补全脚本见下方实测
--log-level <all|trace|debug|info|warn|warning|error|fatal|none>日志级别排障提级到 debug/trace
--print-logs日志打印到 stderr服务端日志需 --standalone

shell 补全实测(bash):

opencode --completions bash

回显(节选首部):

###-begin-opencode-completions-###
#
# Static completion script for Bash
#
# Installation:

按脚本头部注释安装到 ~/.bashrc(或输出重定向到 /etc/bash_completion.d/opencode),重开 shell 后子命令与参数自动补全。

十、注意事项

  1. 命令输出含真实路径/模型名:本文回显均为实测逐行照抄;在不同环境(模型名、路径、时间)执行时输出会相应变化,以本地实跑为准。
  2. 后台服务与会话共享:run/TUI/mini 共享会话库(~/.local/share/opencode/opencode.db);批量脚本建议 --standalone,防止污染交互会话。
  3. 权限与安全:--auto 会自动放行未显式 deny 的权限,仅在可信目录使用;serve/pair --remote 有网络暴露面,遵守 7.3/7.5 的使用约束;auth export 输出含明文密钥。
  4. 小模型跑 agent 任务不稳定:0.5B–1.5B 本地模型实测会把工具调用输出成 JSON 文本而不执行;工具调用场景选支持 function calling 的 7B+ 模型。
  5. 配置改动后 reload:配置类命令(mcp add、plugin add、手改 JSON)后执行 opencode reload,必要时 opencode service restart。

十一、常见问题

Q1:opencode models 里找不到我配置的模型? 按序排查:opencode debug config 确认 provider 已加载(含路径与模型键)→ opencode reload → opencode models | grep '你的provider/'。仍无输出说明配置文件没被识别(检查文件位置与 JSON 语法,opencode.jsonc 与 opencode.json 均可)。

Q2:opencode run 报模型不存在/鉴权失败? provider/model 引用要与 opencode models 输出逐字一致;env 声明的凭据变量必须在当前 shell 已导出(opencode auth list 显示来源,实测 environment 表示取自环境变量)。

Q3:TUI 和 run 的会话互不相通? 默认是相通的(同一后台服务)。若某侧用了 --standalone/--server 指向了私有/远程服务,会话就会隔离——检查这两类 flag 的使用。

Q4:MCP 服务器一直连不上? local 型先手动跑一遍 command 数组里的命令,确认进程能启动、协议应答正常;再看配置 command 是否用数组形式、路径是否绝对路径;最后 opencode reload + opencode mcp list 看状态(实测 ✓ echo connected 为正常态)。

Q5:怎么彻底重置 OpenCode? opencode uninstall -f 卸载程序,再按安装指南第十二章清 ~/.config/opencode、~/.local/share/opencode、~/.cache/opencode 三个目录后重装。

Q6:日志在哪里? opencode debug paths 的 log 行(实测 /root/.local/share/opencode/log);实时排障用 --log-level debug --print-logs(服务端日志需配合 --standalone)。

十二、参考链接