### Install OpenCode GitHub App Source: https://learnopencode.com/5-advanced/14-github Command to install the OpenCode GitHub App. This initiates a guided setup process including selecting a provider, model, creating a workflow file, and setting up secrets. ```bash opencode github install ``` -------------------------------- ### Comprehensive OpenCode Configuration Example Source: https://learnopencode.com/5-advanced/01a-config-basics An example of a complete opencode.json configuration file, integrating settings for models, providers, default agent, username, theme, and automatic updates, utilizing environment variables for sensitive data. ```jsonc { "$schema": "https://opencode.ai/config.json", // 模型 "model": "anthropic/claude-opus-4-5-thinking", "small_model": "anthropic/claude-haiku-4-5", "default_agent": "build", // Provider "provider": { "anthropic": { "options": { "apiKey": "{env:ANTHROPIC_API_KEY}", "timeout": 600000 } } }, // Provider 控制 "disabled_providers": ["gemini"], // 用户 "username": "开发者", // 主题 "theme": "catppuccin", // 自动更新 "autoupdate": true } ``` -------------------------------- ### Initiate OpenCode and Connect to MiniMax Source: https://learnopencode.com/1-start/04d-minimax This snippet shows the basic commands to start OpenCode and initiate the connection process to a provider like MiniMax. It assumes OpenCode is installed and accessible. ```bash opencode /connect ``` -------------------------------- ### JSONC Configuration Example Source: https://learnopencode.com/5-advanced/01a-config-basics Demonstrates a basic OpenCode configuration using JSONC format, including schema, model, and provider settings. JSONC allows for comments, making configurations more readable. ```jsonc { "$schema": "https://opencode.ai/config.json", // 这是注释,JSONC 格式支持 "model": "anthropic/claude-opus-4-5-thinking" } ``` -------------------------------- ### Install OpenCode on Windows using Scoop Source: https://learnopencode.com/1-start/02-install These commands install OpenCode on Windows using the Scoop package manager. It first adds the 'extras' bucket to Scoop and then installs the 'opencode' package from that bucket. ```powershell scoop bucket add extras scoop install extras/opencode ``` -------------------------------- ### Install OpenCode using Official Script with Version and Path Options Source: https://learnopencode.com/1-start/02a-install-alternatives Demonstrates advanced usage of the official OpenCode installation script. Includes installing a specific version and preventing automatic PATH modification. ```bash # Install specific version curl -fsSL https://opencode.ai/install | bash -s -- --version 1.1.6 # Do not modify shell configuration (do not add to PATH automatically) curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path ``` -------------------------------- ### Verify OpenCode Installation Source: https://learnopencode.com/1-start/02-install This command checks if OpenCode has been installed correctly by displaying its version number. A successful output indicates that the installation was successful and the 'opencode' command is available in your PATH. ```bash opencode --version ``` -------------------------------- ### Text: Context Usage Display Example Source: https://learnopencode.com/5-advanced/20-compaction This text shows an example of how the current context usage is displayed in the OpenCode TUI. It indicates the total number of tokens used and the percentage of the model's context window that is occupied. ```text Context 145,234 tokens 73% used ``` -------------------------------- ### Install Scoop on Windows Source: https://learnopencode.com/1-start/02-install This command downloads and executes the Scoop installation script, installing the package manager to your user directory. It's recommended to run this in a non-administrator PowerShell session. ```powershell Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression ``` -------------------------------- ### Installation Source: https://learnopencode.com/5-advanced/10a-sdk-basics Install the OpenCode SDK using npm. ```APIDOC ## Install SDK ```bash npm install @opencode-ai/sdk ``` ``` -------------------------------- ### Install Scoop on Windows Source: https://learnopencode.com/1-start/02a-install-alternatives Installs Scoop on Windows by sequentially running PowerShell commands. Includes setting execution policy, downloading and executing the installer, and installing git. ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression scoop install git ``` -------------------------------- ### Install OpenCode from Local Binary Source: https://learnopencode.com/1-start/02a-install-alternatives Installs OpenCode using a local binary file. This method is used after manually downloading the binary and is often part of advanced script usage. ```bash ./install --binary /path/to/opencode ``` -------------------------------- ### Login and Add MiniMax API Key via CLI Source: https://learnopencode.com/1-start/04d-minimax This command initiates the login process for adding API keys in OpenCode. It guides the user through selecting a provider (like 'Other' for manual setup) and entering the provider ID and API key. ```bash opencode auth login ``` -------------------------------- ### Install Missing Tools for OpenCode Installation Source: https://learnopencode.com/1-start/02b-install-troubleshoot This snippet shows how to install essential tools like 'tar' and 'unzip' which might be required by the OpenCode installation script. Instructions are provided for macOS, Ubuntu/Debian, and CentOS/RHEL systems. ```bash # macOS (usually built-in) # If not, install Xcode command line tools: xcode-select --install ``` ```bash # Ubuntu/Debian sudo apt install -y tar unzip ``` ```bash # CentOS/RHEL sudo yum install -y tar unzip ``` -------------------------------- ### OpenCode Installation via Package Managers Source: https://learnopencode.com/appendix/migration This section provides commands for installing or upgrading OpenCode using common package managers. It includes instructions for npm, Homebrew, and Scoop, ensuring users can update to the latest version regardless of their environment. ```bash # npm npm install -g opencode-ai # Homebrew brew upgrade opencode # Scoop scoop update opencode ``` -------------------------------- ### Install Ollama - Windows Source: https://learnopencode.com/1-start/04g-ollama Instructions for installing Ollama on Windows. Users should download the installer from the official Ollama website. ```powershell # From the official website download the installer # https://ollama.com/download ``` -------------------------------- ### Install Ollama - Linux Source: https://learnopencode.com/1-start/04g-ollama Installs Ollama on Linux by downloading and executing the official installation script. This command fetches the script and runs it. ```bash curl -fsSL https://ollama.com/install.sh | sh ``` -------------------------------- ### Install Scoop with Administrator Privileges on Windows Source: https://learnopencode.com/1-start/02-install This command is used to install Scoop when running PowerShell as an administrator. It ensures that Scoop is installed correctly even with elevated privileges. ```powershell iex "& {$(irm get.scoop.sh)} -RunAsAdmin" ``` -------------------------------- ### Install Git for Scoop on Windows Source: https://learnopencode.com/1-start/02-install This command installs Git using Scoop. Git is a dependency for Scoop to manage package repositories (buckets). ```powershell scoop install git ``` -------------------------------- ### Alternative OpenCode Installation Methods Source: https://learnopencode.com/1-start/02b-install-troubleshoot These commands provide alternative ways to install OpenCode using npm and Homebrew. These methods can be useful if the official script encounters network issues, as npm and brew often have better access to domestic mirrors. ```bash npm install -g opencode-ai ``` ```bash brew install anomalyco/tap/opencode ``` -------------------------------- ### Install OpenCode on macOS/Linux Source: https://learnopencode.com/1-start/02-install This command downloads and executes the OpenCode installation script for macOS and Linux systems. It automatically detects your system architecture and installs OpenCode to the appropriate location, updating your shell configuration. ```bash curl -fsSL https://opencode.ai/install | bash ``` -------------------------------- ### Configure PowerShell Execution Policy for Scoop on Windows Source: https://learnopencode.com/1-start/02-install This command sets the execution policy for PowerShell to 'RemoteSigned' for the current user, allowing the execution of downloaded scripts, which is necessary for installing Scoop. ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser ``` -------------------------------- ### Start Web Interface Source: https://learnopencode.com/appendix/cli Launches the web-based user interface. Similar to the serve command, it allows configuration of port, hostname, mDNS, and CORS. ```bash opencode web # Start the web interface opencode web # Specify port opencode web --port 4096 ``` -------------------------------- ### Practical Example: Batch Code Review Source: https://learnopencode.com/5-advanced/10a-sdk-basics A practical example demonstrating how to perform a batch code review on TypeScript files within a specified directory using the OpenCode SDK. ```APIDOC ### Batch Code Review Example This example shows how to create a session, find all TypeScript files in a directory, and then prompt the AI to review each file. ```typescript import { createOpencode } from "@opencode-ai/sdk"; import { readdir } from "fs/promises"; async function batchCodeReview(directory: string) { const { client, server } = await createOpencode({ config: { model: "anthropic/claude-opus-4-5-thinking", }, }); try { // Create a session const session = await client.session.create({ body: { title: `Batch Code Review - ${directory}` }, }); const sessionId = session.data!.id; // Find all TypeScript files const files = await client.find.files({ query: { query: "*.ts", type: "file", directory }, }); console.log(`Found ${files.data?.length} files`); // Review each file individually for (const file of files.data ?? []) { console.log(`Reviewing: ${file}`); await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: `Please review file ${file} for potential issues and suggestions for improvement.` }], }, }); } console.log("Review complete!"); } finally { server.close(); } } batchCodeReview("./src"); ``` ``` -------------------------------- ### Create Opencode Server + Client (Recommended) Source: https://learnopencode.com/5-advanced/10a-sdk-basics This method starts both the OpenCode server and client, suitable for standalone scripts and automation scenarios. It allows you to use the client to call APIs and manage sessions. ```APIDOC ## Create Server + Client (Recommended) This approach starts both the server and client, ideal for standalone scripts and automation. ### Method ```typescript import { createOpencode } from "@opencode-ai/sdk" const { client, server } = await createOpencode() // Use the client to call APIs const sessions = await client.session.list() console.log(`Currently ${sessions.data?.length} sessions available`) // Close the server when done server.close() ``` ### ServerOptions Parameters | Parameter | Type | Description | Default Value | |---|---|---|---| | `hostname` | `string` | Server hostname | `127.0.0.1` | | `port` | `number` | Server port | `4096` | | `signal` | `AbortSignal` | Abort signal for cancellation | `undefined` | | `timeout` | `number` | Server startup timeout (ms) | `5000` | | `config` | `Config` | Configuration object, overrides `opencode.json` | `{}` | > **Source**: `packages/sdk/js/src/server.ts:4-10` ### Configuration Override Example ```typescript import { createOpencode } from "@opencode-ai/sdk" const opencode = await createOpencode({ hostname: "127.0.0.1", port: 4097, // Use a different port to avoid conflicts timeout: 10000, config: { model: "anthropic/claude-opus-4-5-thinking", logLevel: "DEBUG", }, }) console.log(`Server running on ${opencode.server.url}`) // Close when finished opencode.server.close() ``` ``` -------------------------------- ### Running OpenCode CLI Source: https://learnopencode.com/1-start/04e-claude This command starts the OpenCode application from the terminal. Ensure OpenCode is installed and accessible in your system's PATH. ```bash opencode ``` -------------------------------- ### 禁用 OpenCode 自动压缩 Source: https://learnopencode.com/5-advanced/20-compaction 通过修改配置文件或设置环境变量来禁用 OpenCode 的自动压缩功能。这可以防止 OpenCode 在对话过程中自动压缩内容,适用于需要保留完整对话历史的场景。 ```json { "compaction": { "auto": false } } ``` ```bash OPENCODE_DISABLE_AUTOCOMPACT=true opencode ``` -------------------------------- ### Automatic Update Configuration Source: https://learnopencode.com/5-advanced/01a-config-basics Configures the behavior of automatic updates for OpenCode. Options include automatic download and installation, disabling updates, or only receiving notifications for new versions. ```json { "autoupdate": true } ``` -------------------------------- ### Batch Code Review Example (TypeScript) Source: https://learnopencode.com/5-advanced/10a-sdk-basics This practical example demonstrates how to perform a batch code review on all TypeScript files within a specified directory. It involves creating a session, finding files, and then iterating through each file to prompt the AI for a review. ```typescript import { createOpencode } from "@opencode-ai/sdk" import { readdir } from "fs/promises" async function batchCodeReview(directory: string) { const { client, server } = await createOpencode({ config: { model: "anthropic/claude-opus-4-5-thinking", }, }) try { // 创建会话 const session = await client.session.create({ body: { title: `批量代码审查 - ${directory}` }, }) const sessionId = session.data!.id // 查找所有 TypeScript 文件 const files = await client.find.files({ query: { query: "*.ts", type: "file", directory }, }) console.log(`找到 ${files.data?.length} 个文件`) // 逐个审查 for (const file of files.data ?? []) { console.log(`审查: ${file}`) await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: `请审查文件 ${file},检查潜在问题和改进建议。` }], }, }) } console.log("审查完成!") } finally { server.close() } } batchCodeReview("./src") ``` -------------------------------- ### JSON Configuration for Default Agent Source: https://learnopencode.com/5-advanced/02a-agent-quickstart This JSON configuration sets the default primary agent to be used when OpenCode starts. In this example, 'plan' is set as the default agent. If not specified, the default is 'build'. ```jsonc { "default_agent": "plan" // 默认使用 plan agent } ``` -------------------------------- ### Reload Shell Configuration on macOS/Linux (bash) Source: https://learnopencode.com/1-start/02-install This command reloads the bash shell configuration file, applying changes to environment variables like PATH without needing to restart the terminal. ```bash source ~/.bashrc ``` -------------------------------- ### Reload Shell Configuration on macOS/Linux (zsh) Source: https://learnopencode.com/1-start/02-install This command reloads the zsh shell configuration file, applying changes to environment variables like PATH without needing to restart the terminal. ```bash source ~/.zshrc ``` -------------------------------- ### File Operation Examples in TypeScript Source: https://learnopencode.com/5-advanced/10b-sdk-reference Illustrates file system operations using the OpenCode SDK, such as listing directory contents, reading file content, and checking file status (e.g., Git changes). The examples show how to use `client.file.list`, `client.file.read`, and `client.file.status`. ```typescript // 列出目录内容 const nodes = await client.file.list({ query: { path: "src" }, }) // 读取文件 const content = await client.file.read({ query: { path: "src/index.ts" }, }) console.log(content.data?.content) // 获取 git 状态 const status = await client.file.status() for (const file of status.data ?? []) { console.log(`${file.status}: ${file.path} (+${file.added}/-${file.removed})`) } ``` -------------------------------- ### Globally Disable MCP Tools using Permissions Source: https://learnopencode.com/5-advanced/07b-mcp-advanced This configuration demonstrates how to globally disable MCP tools using the 'permission' setting. Wildcards can be used to disable multiple tools or all tools starting with a specific prefix. ```jsonc { "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "permission": { "my-mcp-foo_*": "deny" } } { "permission": { "my-mcp*": "deny" } } ``` -------------------------------- ### Configure Grep by Vercel MCP Service Source: https://learnopencode.com/5-advanced/07b-mcp-advanced This JSONC configuration sets up the Grep by Vercel MCP service, which allows searching for code snippets on GitHub. It's a remote service that can be directly integrated into your OpenCode setup. ```jsonc { "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } } } ``` -------------------------------- ### Placeholder Syntax Examples (Markdown) Source: https://learnopencode.com/appendix/prompt-guidelines Demonstrates the correct and incorrect usage of placeholders in prompts. It covers required, optional, default value, and multi-choice placeholders, emphasizing clarity and consistency. ```markdown **❌ 差的写法** : ``` 类型:玄幻/都市/言情 语言:语言 粘贴代码 ``` **✅ 好的写法** : ``` 类型:【玄幻/都市/言情/悬疑/科幻】 语言:【编程语言】 [粘贴代码] ``` ``` -------------------------------- ### Install OpenCode on Windows using Package Managers (PowerShell) Source: https://learnopencode.com/appendix/faq Provides commands for installing OpenCode on Windows using popular package managers like Scoop and Chocolatey. It also includes the npm installation method and advises running the terminal with administrator privileges. ```powershell # Using Scoop scoop install opencode # Or using Chocolatey choco install opencode # Or using npm npm install -g @anthropic-ai/opencode ``` -------------------------------- ### Text: Context Usage After Compression Example Source: https://learnopencode.com/5-advanced/20-compaction This text illustrates the typical display of context usage after a compression operation has been performed. It shows a significantly reduced token count and percentage, reflecting the effectiveness of the pruning and summarization process. ```text Context 45,678 tokens 23% used ``` -------------------------------- ### Configure Google Gemini Provider via Vertex AI Source: https://learnopencode.com/appendix/providers This snippet details the setup for using Google Gemini models through Vertex AI with OpenCode. It requires setting environment variables for the Google Cloud project, credentials, and optionally the location, before starting OpenCode. ```bash # 设置环境变量 export GOOGLE_CLOUD_PROJECT=your-project-id export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json export VERTEX_LOCATION=global # 可选 # 启动 opencode opencode ``` -------------------------------- ### Connect to IO.NET Provider Source: https://learnopencode.com/appendix/providers Steps to connect to IO.NET, which offers over 17 models, using OpenCode. Run the `/connect` command and search for 'IO.NET'. ```bash /connect # 搜索 IO.NET ``` -------------------------------- ### Project Management Examples in TypeScript Source: https://learnopencode.com/5-advanced/10b-sdk-reference Shows how to interact with project management features using the OpenCode SDK. It includes examples for retrieving the current project and listing all available projects. The code demonstrates accessing project details like the worktree path. ```typescript // 获取当前项目 const current = await client.project.current() console.log(`项目路径: ${current.data?.worktree}`) // 列出所有项目 const projects = await client.project.list() ``` -------------------------------- ### Session Management Examples in TypeScript Source: https://learnopencode.com/5-advanced/10b-sdk-reference Demonstrates core session management operations using the OpenCode SDK, including creating sessions, sending messages, retrieving message history, forking sessions, getting file differences, and aborting sessions. It utilizes the `client.session` object and its various methods. ```typescript // 创建会话 const session = await client.session.create({ body: { title: "代码重构任务" }, }) // 发送消息 const result = await client.session.prompt({ path: { id: session.data!.id }, body: { model: { providerID: "anthropic", modelID: "claude-opus-4-5-thinking" }, parts: [{ type: "text", text: "请帮我重构这个函数" }], }, }) // 获取消息列表 const messages = await client.session.messages({ path: { id: session.data!.id }, }) // 获取 Todo 列表 const todos = await client.session.todo({ path: { id: session.data!.id }, }) // 分叉会话 const forked = await client.session.fork({ path: { id: session.data!.id }, body: { messageID: "msg-123" }, }) // 获取文件变更 const diff = await client.session.diff({ path: { id: session.data!.id }, }) // 中止会话 await client.session.abort({ path: { id: session.data!.id }, }) ```