opencode Documentation

The open source coding agent.

219,931 stars TypeScript TypeScript 101 files · ~236,314 tokens
RAW Doc

Technical Documentation: anomalyco/opencode

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (README.md)


Installation

bash
# YOLO
curl -fsSL https://opencode.ai/v2/install | bash

# Package managers
npm i @opencode/cli@latest      # or bun/pnpm/yarn
brew install anomalyco/tap/opencode-v2 # macOS and Linux (recommended, always up to date)
brew install opencode              # macOS and Linux (official brew formula, updated less)
sudo pacman -S opencode            # Arch Linux (Stable)
paru -S opencode-beta              # Arch Linux (Latest from AUR)
mise use -g opencode               # Any OS
nix run github:anomalyco/opencode  # Nix

[!TIP]
Remove versions older than 0.1.x before installing.

Desktop App (BETA)

OpenCode is also available as a desktop application. Download it from opencode.ai/download.

Platform Download
macOS (Apple Silicon) opencode-desktop-mac-arm64.dmg
macOS (Intel) opencode-desktop-mac-x64.dmg
Windows opencode-desktop-win-x64.exe
Linux .deb, .rpm, or .AppImage
bash
# macOS (Homebrew)
brew install --cask opencode-desktop

Installation Directory

The install script respects the following priority order for the installation path:

  1. $OPENCODE_INSTALL_DIR - Custom installation directory
  2. $XDG_BIN_DIR - XDG Base Directory Specification compliant path
  3. $HOME/bin - Standard user binary directory (if it exists or can be created)
  4. $HOME/.opencode/bin - Default fallback
bash
# Examples
OPENCODE_INSTALL_DIR=/usr/local/bin curl -fsSL https://opencode.ai/v2/install | bash
XDG_BIN_DIR=$HOME/.local/bin curl -fsSL https://opencode.ai/v2/install | bash

Agents

OpenCode includes two built-in agents you can switch between with the Tab key.

  • build - Default, full-access agent for development work
  • plan - Read-only agent for analysis and code exploration
    • Denies file edits by default
    • Asks permission before running bash commands
    • Ideal for exploring unfamiliar codebases or planning changes

Also included is a general subagent for complex searches and multistep tasks.
This is used internally and can be invoked using @general in messages.

Learn more about agents.

Documentation

For more info on how to configure OpenCode, head over to our docs.

Contributing

If you're interested in contributing to OpenCode, please read our contributing docs before submitting a pull request.

Building on OpenCode

If you are working on a project that's related to OpenCode and is using "opencode" as part of its name, for example "opencode-dashboard" or "opencode-mobile", please add a note to your README to clarify that it is not built by the OpenCode team and is not affiliated with us in any way.


Join our community Discord | X.com


Packages Web Src Content Docs Index (`packages/web/src/content/docs/index.mdx`)


title: Intro

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../config.mjs"
export const console = config.console

:::note
OpenCode 1 and OpenCode 2 both use the opencode command and cannot be installed side by side under their default command.
See the OpenCode 2 docs to migrate to V2.
:::

OpenCode is an open source AI coding agent. It's available as a terminal-based interface, desktop app, or IDE extension.

Let's get started.


Prerequisites

To use OpenCode in your terminal, you'll need:

  1. A modern terminal emulator like:

  2. API keys for the LLM providers you want to use.


Install

The easiest way to install OpenCode 1 is through the install script. These installation methods provide the opencode
binary and can conflict with or replace an OpenCode 2 installation.

bash
curl -fsSL https://opencode.ai/install | bash

You can also install it with the following commands:

  • Using Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Using Homebrew on macOS and Linux

    bash
    brew install anomalyco/tap/opencode

    We recommend using the OpenCode tap for the most up to date releases. The official brew install opencode formula is maintained by the Homebrew team and is updated less frequently.

  • Installing on Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Recommended: Use WSL]
For the best experience on Windows, we recommend using Windows Subsystem for Linux (WSL). It provides better performance and full compatibility with OpenCode's features.
:::

  • Using Chocolatey

    bash
    choco install opencode
  • Using Scoop

    bash
    scoop install opencode
  • Using NPM

    bash
    npm install opencode-ai
  • Using Mise

    bash
    mise use -g github:anomalyco/opencode
  • Using Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Support for installing OpenCode on Windows using Bun is currently in progress.

You can also grab the binary from the Releases.


Configure

With OpenCode you can use any LLM provider by configuring their API keys.

If you are new to using LLM providers, we recommend using OpenCode Zen.
It's a curated list of models that have been tested and verified by the OpenCode
team.

  1. Run the /connect command in the TUI, select opencode, and head to opencode.ai/auth.

    txt
    /connect
  2. Sign in, add your billing details, and copy your API key.

  3. Paste your API key.

    txt
    ┌ API key
    │
    │
    └ enter

Alternatively, you can select one of the other providers. Learn more.


Initialize

Now that you've configured a provider, you can navigate to a project that
you want to work on.

bash
cd /path/to/project

And run OpenCode.

bash
opencode

Next, initialize OpenCode for the project by running the following command.

bash frame="none"
/init

This will get OpenCode to analyze your project and create an AGENTS.md file in
the project root.

:::tip
You should commit your project's AGENTS.md file to Git.
:::

This helps OpenCode understand the project structure and the coding patterns
used.


Usage

You are now ready to use OpenCode to work on your project. Feel free to ask it
anything!

If you are new to using an AI coding agent, here are some examples that might
help.


Ask questions

You can ask OpenCode to explain the codebase to you.

:::tip
Use the @ key to fuzzy search for files in the project.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

This is helpful if there's a part of the codebase that you didn't work on.


Add features

You can ask OpenCode to add new features to your project. Though we first recommend asking it to create a plan.

  1. Create a plan

    OpenCode has a Plan mode that disables its ability to make changes and
    instead suggest how it'll implement the feature.

    Switch to it using the Tab key. You'll see an indicator for this in the lower right corner.

    bash frame="none" title="switch to plan mode"
    <TAB>

    Now let's describe what we want it to do.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    You want to give OpenCode enough details to understand what you want. It helps
    to talk to it like you are talking to a junior developer on your team.

    :::tip
    Give OpenCode plenty of context and examples to help it understand what you
    want.
    :::

  2. Iterate on the plan

    Once it gives you a plan, you can give it feedback or add more details.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    Drag and drop images into the terminal to add them to the prompt.
    :::

    OpenCode can scan any images you give it and add them to the prompt. You can
    do this by dragging and dropping an image into the terminal.

  3. Build the feature

    Once you feel comfortable with the plan, switch back to Build mode by
    hitting the Tab key again.

    bash frame="none"
    <TAB>

    And asking it to make the changes.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Make changes

For more straightforward changes, you can ask OpenCode to directly build it
without having to review the plan first.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

You want to make sure you provide a good amount of detail so OpenCode makes the right
changes.


Undo changes

Let's say you ask OpenCode to make some changes.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

But you realize that it is not what you wanted. You can undo the changes
using the /undo command.

bash frame="none"
/undo

OpenCode will now revert the changes you made and show your original message
again.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

From here you can tweak the prompt and ask OpenCode to try again.

:::tip
You can run /undo multiple times to undo multiple changes.
:::

Or you can redo the changes using the /redo command.

bash frame="none"
/redo

Customize

And that's it! You are now a pro at using OpenCode.

To make it your own, we recommend picking a theme, customizing the keybinds, configuring code formatters, creating custom commands, or playing around with the OpenCode config.


Services Www Src Docs Content Index (`services/www/src/docs/content/index.mdx`)


title: "Intro"

OpenCode is an open source AI coding agent. It’s available as a terminal-based interface, desktop app, or web app.

CLI

<CodeTabs
id="install"
label="Install method"
tabs={[
{ label: "curl", code: "curl -fsSL https://opencode.ai/v2/install | bash" },
{ label: "homebrew", code: "brew install anomalyco/tap/opencode-v2" },
{ label: "npm", code: "npm install @opencode/cli" },
{ label: "bun", code: "bun install -g --trust @opencode/cli" },
{ label: "pnpm", code: "pnpm add --allow-build=@opencode/cli @opencode/cli" },
{ label: "yarn", code: "yarn global add @opencode/cli" },
{ label: "vite+", code: "vp install -g @opencode/cli" },
{ label: "aur", code: "paru -S opencode-beta" },
{ label: "mise", code: "mise use -g opencode" },
]}
/>

The npm package uses a postinstall script to select the native opencode binary for your platform. The Bun and pnpm commands
explicitly allow the required script; Vite+ requires no additional flag. The mise command requires mise 2026.10.9 or later;
older versions install OpenCode 1.

Windows package managers are not supported.

Download a standalone CLI binary for your platform.

Desktop

Download the latest OpenCode Desktop build for your platform.

Web

Access the OpenCode web interface with the opencode pair command.

bash
$ opencode pair

  Open a link to connect. Links work once and expire in 5 minutes.

  http://127.0.0.1:49374/auth/connect/...

Docker

Docker images use versioned tags, for example ghcr.io/anomalyco/opencode:2.0.0.


Connect

OpenCode has built-in support for many LLM providers. You can connect to them
directly in the TUI with /connect.

See Providers to configure custom providers.

If you'd like easy access to all the best coding models you can try out
OpenCode Console.

You can also try OpenCode Go, a $10/month subscription
plan that grants you access to the best coding models.


Customize

Make OpenCode your own by editing the OpenCode config, loading plugins, connecting MCP
servers
, or creating commands. For terminal interface themes and keybindings, see CLI
settings
.


Learn

If you are interested in an indepth course on OpenCode Boot.dev has created an excellent AI Coding with
OpenCode
course in consultation with our team. All the information in the course is
free to read and watch, though some interactive features may require payment.


Packages Web Src Content Docs Ar Index (`packages/web/src/content/docs/ar/index.mdx`)


title: مقدمة

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode هو وكيل ترميز بالذكاء الاصطناعي مفتوح المصدر. يتوفر كواجهة terminal، وتطبيق لسطح المكتب، أو إضافة لبيئة تطوير متكاملة (IDE).

لنبدأ.


المتطلبات

لاستخدام OpenCode في terminal، ستحتاج إلى:

  1. محاكي terminal حديث مثل:

  2. مفاتيح API لمزوّدي نماذج اللغة (LLM) الذين تريد استخدامهم.


التثبيت

أسهل طريقة لتثبيت OpenCode هي عبر سكربت التثبيت.

bash
curl -fsSL https://opencode.ai/install | bash

يمكنك أيضا تثبيته عبر الأوامر التالية:

  • باستخدام Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • باستخدام Homebrew على macOS وLinux

    bash
    brew install anomalyco/tap/opencode

    نوصي باستخدام tap الخاص بـ OpenCode للحصول على أحدث الإصدارات. صيغة brew install opencode الرسمية تُدار بواسطة فريق Homebrew ويتم تحديثها بوتيرة أقل.

  • باستخدام Paru على Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[موصى به: استخدم WSL]
لأفضل تجربة على Windows، نوصي باستخدام Windows Subsystem for Linux (WSL). يوفر أداء أفضل وتوافقا كاملا مع ميزات OpenCode.
:::

  • باستخدام Chocolatey

    bash
    choco install opencode
  • باستخدام Scoop

    bash
    scoop install opencode
  • باستخدام NPM

    bash
    npm install opencode-ai
  • باستخدام Mise

    bash
    mise use -g github:anomalyco/opencode
  • باستخدام Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

دعم تثبيت OpenCode على Windows باستخدام Bun قيد العمل حاليا.

يمكنك أيضا تنزيل الملف التنفيذي من صفحة Releases.


الإعداد

مع OpenCode يمكنك استخدام أي مزود LLM عبر إعداد مفاتيح API الخاصة به.

إذا كنت جديدا على استخدام مزوّدي LLM، فنوصي باستخدام OpenCode Zen.
إنها قائمة منتقاة من النماذج تم اختبارها والتحقق منها بواسطة فريق OpenCode.

  1. شغّل الأمر /connect في واجهة TUI، واختر opencode، ثم انتقل إلى opencode.ai/auth.

    txt
    /connect
  2. سجّل الدخول، وأضف تفاصيل الدفع، ثم انسخ مفتاح API.

  3. الصق مفتاح API.

    txt
    ┌ API key
    │
    │
    └ enter

بدلا من ذلك يمكنك اختيار أحد المزوّدين الآخرين. اعرف المزيد.


التهيئة

بعد أن قمت بإعداد مزوّد، يمكنك الانتقال إلى المشروع الذي تريد العمل عليه.

bash
cd /path/to/project

ثم شغّل OpenCode.

bash
opencode

بعد ذلك، هيّئ OpenCode للمشروع عبر تشغيل الأمر التالي.

bash frame="none"
/init

سيجعل هذا OpenCode يحلل مشروعك ويُنشئ ملف AGENTS.md في جذر المشروع.

:::tip
يستحسن أن تقوم بعمل commit لملف AGENTS.md الخاص بمشروعك إلى Git.
:::

يساعد هذا OpenCode على فهم بنية المشروع وأنماط الترميز المستخدمة.


الاستخدام

أصبحت الآن جاهزا لاستخدام OpenCode للعمل على مشروعك. لا تتردد في سؤاله أي شيء!

إذا كنت جديدا على استخدام وكيل ترميز بالذكاء الاصطناعي، فإليك بعض الأمثلة التي قد تساعد.


اطرح أسئلة

يمكنك أن تطلب من OpenCode شرح قاعدة الشيفرة لك.

:::tip
استخدم المفتاح @ للبحث التقريبي عن الملفات داخل المشروع.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

يفيد هذا عندما تكون هناك أجزاء من قاعدة الشيفرة لم تعمل عليها.


أضف ميزات

يمكنك أن تطلب من OpenCode إضافة ميزات جديدة إلى مشروعك، لكننا نوصي أولا بطلب إنشاء خطة.

  1. أنشئ خطة

    لدى OpenCode وضع Plan يعطل قدرته على إجراء التغييرات، ويقترح بدلا من ذلك كيف سينفّذ الميزة.

    انتقل إليه باستخدام مفتاح Tab. سترى مؤشرا لذلك في الزاوية السفلية اليمنى.

    bash frame="none" title="التبديل إلى وضع plan"
    <TAB>

    الآن لنصف ما نريده أن يفعله.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    احرص على تزويد OpenCode بتفاصيل كافية ليفهم ما تريد. يساعد أن تتحدث إليه كما لو كنت تتحدث إلى مطور مبتدئ ضمن فريقك.

    :::tip
    أعطِ OpenCode سياقا وأمثلة كافية لمساعدته على فهم ما تريد.
    :::

  2. حسّن الخطة

    بعد أن يقدم لك خطة، يمكنك إعطاؤه ملاحظات أو إضافة تفاصيل أكثر.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    اسحب الصور وأفلِتها داخل terminal لإضافتها إلى الطلب.
    :::

    يستطيع OpenCode فحص أي صور تزوده بها وإضافتها إلى الطلب. يمكنك فعل ذلك عبر سحب الصورة وإفلاتها داخل terminal.

  3. ابنِ الميزة

    عندما تشعر بالارتياح للخطة، عد إلى وضع Build بالضغط على مفتاح Tab مرة أخرى.

    bash frame="none"
    <TAB>

    ثم اطلب منه تنفيذ التغييرات.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

نفّذ تغييرات

للتغييرات الأبسط، يمكنك أن تطلب من OpenCode تنفيذها مباشرة دون الحاجة لمراجعة خطة أولا.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

تأكد من تقديم قدر مناسب من التفاصيل لكي يجري OpenCode التغييرات الصحيحة.


تراجع عن التغييرات

لنفترض أنك طلبت من OpenCode إجراء بعض التغييرات.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

لكن تتضح لك لاحقا أنها ليست ما تريده. يمكنك التراجع عن التغييرات باستخدام الأمر /undo.

bash frame="none"
/undo

سيقوم OpenCode الآن بعكس التغييرات التي أُجريت ويعرض رسالتك الأصلية مجددا.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

من هنا يمكنك تعديل الطلب وطلب المحاولة مرة أخرى.

:::tip
يمكنك تشغيل /undo عدة مرات للتراجع عن عدة تغييرات.
:::

أو يمكنك إعادة تنفيذ التغييرات باستخدام الأمر /redo.

bash frame="none"
/redo

التخصيص

وهذا كل شيء! أصبحت الآن محترفا في استخدام OpenCode.

لتجعله مناسبا لك، نوصي بـ اختيار سمة، وتخصيص اختصارات لوحة المفاتيح، وإعداد منسقات الشيفرة، وإنشاء أوامر مخصصة، أو التجربة مع إعدادات OpenCode.


Packages Web Src Content Docs Bs Index (`packages/web/src/content/docs/bs/index.mdx`)


title: Uvod

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode je AI agent za kodiranje otvorenog koda. Dostupan je kao interfejs baziran na terminalu, desktop aplikacija ili IDE ekstenzija.

Hajde da počnemo.


Preduvjeti

Da biste koristili OpenCode u svom terminalu, trebat će vam:

  1. Moderan emulator terminala kao što su:
  2. API ključevi za LLM provajdere koje želite koristiti.

Instalacija

Najlakši način za instaliranje OpenCode je putem instalacijske skripte.

bash
curl -fsSL https://opencode.ai/install | bash

Također ga možete instalirati pomoću sljedećih naredbi:

  • Korištenje Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Korištenje Homebrew-a na macOS-u i Linux-u

bash
brew install anomalyco/tap/opencode

Preporučujemo korištenje OpenCode tap za najnovija izdanja. Službenu formulu brew install opencode održava Homebrew tim i ažurira se rjeđe.

  • Korištenje Parua na Arch Linuxu

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Preporučeno: Koristite WSL]
Za najbolje iskustvo na Windows-u preporučujemo korištenje Windows Subsystem for Linux (WSL). Pruža bolje performanse i potpunu kompatibilnost sa OpenCode funkcijama.
:::

  • Korištenje Chocolatey-a
bash
choco install opencode
  • Korištenje Scoop-a
bash
scoop install opencode
  • Korištenje NPM-a
bash
npm install opencode-ai
  • Korištenje Mise
bash
mise use -g github:anomalyco/opencode
  • Korištenje Dockera
bash
docker run -it --rm ghcr.io/anomalyco/opencode

Podrška za instaliranje OpenCode na Windows koristeći Bun je trenutno u toku.
Također možete preuzeti binarnu datoteku iz Releases.


Konfiguracija

Uz OpenCode možete koristiti bilo kojeg LLM provajdera tako što ćete konfigurirati njihove API ključeve.
Ako ste tek počeli koristiti LLM provajdere, preporučujemo korištenje OpenCode Zen.
To je kurirana lista modela koji su testirani i verifikovani od strane OpenCode tima.

  1. Pokrenite naredbu /connect u TUI-u, odaberite opencode i idite na opencode.ai/auth.
txt
/connect
  1. Prijavite se, dodajte svoje detalje naplate i kopirajte svoj API ključ.
  2. Zalijepite svoj API ključ.
txt
┌ API key
   │
   │
   └ enter

Alternativno, možete odabrati jednog od drugih provajdera. Saznajte više.


Inicijalizacija

Sada kada ste konfigurisali provajdera, možete se kretati do projekta na kojem želite raditi.

bash
cd /path/to/project

I pokrenite OpenCode.

bash
opencode

Zatim inicijalizirajte OpenCode za projekat pokretanjem sljedeće naredbe.

bash frame="none"
/init

Ovo će omogućiti OpenCode da analizira vaš projekat i kreira AGENTS.md fajl u korijenu projekta.
:::tip
Trebali biste komitovati datoteku AGENTS.md vašeg projekta u Git.
:::
Ovo pomaže OpenCode da razumije strukturu projekta i obrasce kodiranja koji se koriste.


Korištenje

Sada ste spremni da koristite OpenCode za rad na svom projektu. Slobodno pitajte bilo šta!
Ako ste novi u korištenju agenta za AI kodiranje, evo nekoliko primjera koji bi mogli pomoći.


Postavljanje pitanja

Možete zamoliti OpenCode da vam objasni kodnu bazu.
:::tip
Koristite tipku @ za nejasnu pretragu datoteka u projektu.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Ovo je korisno ako postoji dio kodne baze na kojem niste radili.


Dodavanje funkcija

Možete zamoliti OpenCode da vašem projektu doda nove funkcije. Iako preporučujemo da ga prvo zamolite da napravi plan.

  1. Kreirajte plan
    OpenCode ima Plan mod koji onemogućuje njegovu sposobnost da pravi promjene i umjesto toga predlaže kako će implementirati ovu funkciju.
    Prebacite se na njega pomoću tipke Tab. Vidjet ćete indikator za ovo u donjem desnom uglu.
bash frame="none" title="switch to plan mode"
<TAB>

Hajde sada da opišemo šta želimo da uradi.

txt frame="none"
When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

Želite da date OpenCode dovoljno detalja da razumije šta želite. Pomaže da razgovarate s njim kao da razgovarate sa mlađim programerom u svom timu.
:::tip
Dajte OpenCode dosta konteksta i primjera koji će mu pomoći da razumije šta vi želite.
:::

  1. Ponovite plan
    Kada vam da plan, možete mu dati povratne informacije ili dodati više detalja.
txt frame="none"
We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

:::tip
Prevucite i ispustite slike u terminal da biste ih dodali u prompt.
:::
OpenCode može skenirati sve slike koje mu date i dodati ih u prompt. Možete to učiniti povlačenjem i ispuštanjem slike u terminal.

  1. Izgradite funkciju
    Kada se osjećate ugodno s planom, vratite se na Build mode ponovnim pritiskom na taster Tab.
bash frame="none"
<TAB>

I tražeći od njega da napravi promjene.

bash frame="none"
Sounds good! Go ahead and make the changes.

Pravljenje izmjena

Za jednostavnije promjene, možete zamoliti OpenCode da ga direktno izgradi bez potrebe da prvo pregledate plan.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Želite da budete sigurni da ste pružili dobru količinu detalja kako bi OpenCode napravio ispravne promjene.


Poništavanje izmjena

Recimo da tražite od OpenCode da izvrši neke promjene.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Ali shvatate da to nije ono što ste željeli. Možete poništiti promjene koristeći naredbu /undo.

bash frame="none"
/undo

OpenCode će sada poništiti promjene koje ste napravili i ponovo prikazati vašu originalnu poruku.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Odavde možete podesiti prompt i zamoliti OpenCode da pokuša ponovo.
:::tip
Možete pokrenuti /undo više puta da poništite više promjena.
:::
Ili možete ponoviti promjene koristeći naredbu /redo.

bash frame="none"
/redo

Prilagođavanje

I to je to! Sada ste profesionalac u korištenju OpenCode.
Da biste to učinili svojim, preporučujemo odabir teme, prilagođavanje povezivanja tipki, konfiguriranje formatera koda, kreiranje prilagođenih komandi, ili igranje sa OpenCode config.


Packages Web Src Content Docs Da Index (`packages/web/src/content/docs/da/index.mdx`)


title: Introduktion

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode er en open source AI-kodningsagent. Den er tilgængelig som en terminalbaseret grænseflade, desktop-app eller IDE-udvidelse.

Lad os komme i gang.


Forudsætninger

For at bruge OpenCode i din terminal skal du bruge:

  1. En moderne terminalemulator som:

  2. API-nøgler til de LLM udbydere, du vil bruge.


Installation

Den nemmeste måde at installere OpenCode på er gennem installationsscriptet.

bash
curl -fsSL https://opencode.ai/install | bash

Du kan også installere det med følgende kommandoer:

  • Bruger Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Brug af Homebrew på macOS og Linux

    bash
    brew install anomalyco/tap/opencode

    Vi anbefaler at bruge OpenCode-tap for at få de mest opdaterede udgivelser. Den officielle brew install opencode-formel vedligeholdes af Homebrew-teamet og opdateret sjældnere.

  • Brug af Paru på Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Anbefalet: Brug WSL]
For at få den bedste oplevelse på Windows anbefaler vi at bruge Windows Subsystem for Linux (WSL). Det giver bedre ydeevne og fuld kompatibilitet med OpenCodes funktioner.
:::

  • Brug af Chocolatey

    bash
    choco install opencode
  • Brug af Scoop

    bash
    scoop install opencode
  • Bruger NPM

    bash
    npm install opencode-ai
  • Brug af Mise

    bash
    mise use -g github:anomalyco/opencode
  • Brug af Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Support til installation af OpenCode på Windows ved hjælp af Bun er i gang.

Du kan også få fat i binæren fra Releases.


Konfiguration

Med OpenCode kan du bruge enhver LLM udbyder ved at konfigurere deres API-nøgler.

Hvis du er ny til at bruge LLM-udbydere, anbefaler vi at bruge OpenCode Zen.
Det er en udvalgt liste over modeller, der er blevet testet og verificeret af OpenCode
holde.

  1. Kør kommandoen /connect i TUI, vælg opencode, og gå til opencode.ai/auth.

    txt
    /connect
  2. Log ind, tilføj dine faktureringsoplysninger, og kopier din API-nøgle.

  3. Indsæt din API-nøgle.

    txt
    ┌ API key
    │
    │
    └ enter

Alternativt kan du vælge en af ​​de andre udbydere. Læs mere.


Initialisering

Nu hvor du har konfigureret en udbyder, kan du navigere til et projekt, der
du vil arbejde på.

bash
cd /path/to/project

Og kør OpenCode.

bash
opencode

Derefter initialiseres OpenCode for projektet ved at køre følgende kommando.

bash frame="none"
/init

Dette får OpenCode til at analysere dit projekt og oprette en AGENTS.md fil i
projektets rod.

:::tip
Du bør overgive dit projekter AGENTS.md fil til Git.
:::

Dette hjælper OpenCode med at forstå projektstrukturen og kodningsmønstrene
brugt.


Brug

Du er nu klar til at bruge OpenCode til at arbejde på dit projekt. Spørg det gerne
noget!

Hvis du er ny til at bruge en AI-kodningsagent, er her nogle eksempler, der evt
hjælp.


Stil spørgsmål

Du kan bede OpenCode om at forklare kodebasen for dig.

:::tip
Brug @-tasten til at søge efter filer i projektet.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Dette er nyttigt, hvis der er en del af kodebasen, som du ikke har arbejdet på.


Tilføj funktioner

Du kan bede OpenCode om at tilføje nye funktioner til dit projekt. Selvom vi først anbefaler, at du beder den om at lave en plan.

  1. Opret en plan

    OpenCode har en Plan mode, der deaktiverer dens evne til at foretage ændringer og
    foreslå i stedet hvordan det vil implementere funktionen.

    Skift til det ved hjælp af Tab-tasten. Du vil se en indikator for dette i nederste højre hjørne.

    bash frame="none" title="skift til plan-tilstand"
    <TAB>

    Lad os nu beskrive, hvad vi vil have den til at gøre.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    Du vil give OpenCode nok detaljer til at forstå, hvad du ønsker. Det hjælper
    at tale med det, som om du taler med en juniorudvikler på dit team.

:::tip
Giv OpenCode masser af kontekst og eksempler for at hjælpe den med at forstå, hvad du
ønsker.
:::

  1. Gentag om planen

    Når det giver dig en plan, kan du give den feedback eller tilføje flere detaljer.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

:::tip
Træk og slip billeder i terminalen for at tilføje dem til prompten.
:::

OpenCode kan scanne alle billeder, du giver dem og tilføje dem til prompten. Det kan du
gør dette ved at trække og slippe et billede ind i terminalen.

  1. Byg funktionen

    Når du føler dig godt tilpas med planen, skal du skifte tilbage til Byggetilstand ved
    trykke på Tab-tasten igen.

    bash frame="none"
    <TAB>

    Og beder den om at foretage ændringerne.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Foretag ændringer

For mere ligetil ændringer kan du bede OpenCode om at bygge den direkte
uden at skulle gennemgå planen først.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Du vil sikre dig, at du giver en god mængde detaljer, så OpenCode gør det rigtige
ændringer.


Fortryd ændringer

Lad os sige, at du beder OpenCode om at foretage nogle ændringer.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Men du indser, at det ikke er, hvad du ønskede. Du kan fortryde ændringerne
ved hjælp af kommandoen /undo.

bash frame="none"
/undo

OpenCode vil nu vende tilbage til ændringerne, du har foretaget, og vise din oprindelige besked
igen.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Herfra kan du justere prompten og bede OpenCode om at prøve igen.

:::tip
Du kan køre /undo flere gange for at fortryde flere ændringer.
:::

Eller du kan gentage ændringerne ved hjælp af kommandoen /redo.

bash frame="none"
/redo

Tilpasning

Og det er det! Du er nu en professionel i at bruge OpenCode.

For at gøre det til dit eget, anbefaler vi at vælge et tema, tilpasse genvejstaster, konfigurere kodeformater, oprette brugerdefinerede kommandoer eller at lege med OpenCode-konfiguration.


Packages Web Src Content Docs De Index (`packages/web/src/content/docs/de/index.mdx`)


title: Einführung

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode ist ein Open-Source-Coding-Agent für AI. Es ist als terminalbasierte Schnittstelle, Desktop-App oder IDE-Erweiterung verfügbar.

Fangen wir an.


Voraussetzungen

Um OpenCode in Ihrem Terminal verwenden zu können, benötigen Sie:

  1. Ein moderner Terminal-Emulator, zum Beispiel:

  2. API-Schlüssel für die LLM-Anbieter, die Sie verwenden möchten.


Installation

Der einfachste Weg, OpenCode zu installieren, ist über das Installationsskript.

bash
curl -fsSL https://opencode.ai/install | bash

Sie können es auch mit den folgenden Befehlen installieren:

  • Mit Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Homebrew unter macOS und Linux verwenden

    bash
    brew install anomalyco/tap/opencode

    Wir empfehlen die Verwendung des OpenCode-Taps für die aktuellsten Versionen. Die offizielle brew install opencode-Formel wird vom Homebrew-Team gepflegt und seltener aktualisiert.

  • Verwendung von Paru unter Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Empfohlen: Verwenden Sie WSL]
Für das beste Erlebnis unter Windows empfehlen wir die Verwendung von Windows Subsystem for Linux (WSL). Es bietet eine bessere Leistung und vollständige Kompatibilität mit den Funktionen von OpenCode.
:::

  • Verwendung von Chocolatey

    bash
    choco install opencode
  • Scoop verwenden

    bash
    scoop install opencode
  • Mit NPM

    bash
    npm install opencode-ai
  • Mit Mise

    bash
    mise use -g github:anomalyco/opencode
  • Verwendung von Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Die Unterstützung für die Installation von OpenCode unter Windows mit Bun ist derzeit in Arbeit.

Sie können die Binärdatei auch aus Releases abrufen.


Konfiguration

Mit OpenCode können Sie jeden LLM-Anbieter verwenden, indem Sie dessen API-Schlüssel konfigurieren.

Wenn Sie mit der Verwendung von LLM-Anbietern noch nicht vertraut sind, empfehlen wir die Verwendung von OpenCode Zen.
Es handelt sich um eine kuratierte Liste von Modellen, die vom OpenCode Team getestet und verifiziert wurden.

  1. Führen Sie den Befehl /connect in TUI aus, wählen Sie OpenCode aus und gehen Sie zu opencode.ai/auth.

    txt
    /connect
  2. Melden Sie sich an, geben Sie Ihre Rechnungsdaten ein und kopieren Sie Ihren API-Schlüssel.

  3. Fügen Sie Ihren API-Schlüssel ein.

    txt
    ┌ API key
    │
    │
    └ enter

Alternativ können Sie auch einen der anderen Anbieter auswählen. Mehr erfahren.


Initialisierung

Nachdem Sie nun einen Anbieter konfiguriert haben, können Sie zu einem Projekt navigieren
an dem Sie arbeiten möchten.

bash
cd /path/to/project

Und führen Sie OpenCode aus.

bash
opencode

Als nächstes initialisieren Sie OpenCode für das Projekt, indem Sie den folgenden Befehl ausführen.

bash frame="none"
/init

Dadurch wird OpenCode dazu veranlasst, Ihr Projekt zu analysieren und eine AGENTS.md-Datei im Projektstammverzeichnis zu erstellen.

:::tip
Sie sollten die AGENTS.md-Datei Ihres Projekts an Git übergeben.
:::

Dies hilft OpenCode, die Projektstruktur und die Codierungsmuster zu verstehen
die verwendet werden.


Verwendung

Sie können nun OpenCode verwenden, um an Ihrem Projekt zu arbeiten. Fragen Sie ruhig nach
allem!

Wenn Sie mit der Verwendung eines AI-Codierungsagenten noch nicht vertraut sind, finden Sie hier einige Beispiele, die hilfreich sein könnten.


Fragen stellen

Sie können OpenCode bitten, Ihnen die Codebasis zu erklären.

:::tip
Verwenden Sie die Taste @, um eine Fuzzy-Suche nach Dateien im Projekt durchzuführen.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Dies ist hilfreich, wenn es einen Teil der Codebasis gibt, an dem Sie nicht gearbeitet haben.


Funktionen hinzufügen

Sie können OpenCode bitten, Ihrem Projekt neue Funktionen hinzuzufügen. Wir empfehlen jedoch, es zunächst um die Erstellung eines Plans zu bitten.

  1. Erstellen Sie einen Plan

    OpenCode verfügt über einen Plan Mode, der seine Fähigkeit, Änderungen vorzunehmen, deaktiviert
    Schlagen Sie stattdessen vor, wie die Funktion implementiert wird.

    Wechseln Sie mit der Tabulatortaste dorthin. In der unteren rechten Ecke sehen Sie einen Indikator dafür.

    bash frame="none" title="in den plan-modus wechseln"
    <TAB>

    Beschreiben wir nun, was es tun soll.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    Sie möchten OpenCode genügend Details geben, um zu verstehen, was Sie wollen. Es hilft
    mit ihm zu sprechen, als ob Sie mit einem Junior-Entwickler in Ihrem Team sprechen würden.

    :::tip
    Geben Sie OpenCode reichlich Kontext und Beispiele, damit es versteht, was Sie
    wollen.
    :::

  2. Den Plan überarbeiten

    Sobald Sie einen Plan erhalten, können Sie ihm Feedback geben oder weitere Details hinzufügen.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    Ziehen Sie Bilder per Drag-and-Drop in das Terminal, um sie zur Eingabeaufforderung hinzuzufügen.
    :::

    OpenCode kann alle von Ihnen bereitgestellten Bilder scannen und zur Eingabeaufforderung hinzufügen. Du kannst
    Ziehen Sie dazu ein Bild per Drag & Drop in das Terminal.

  3. Funktion erstellen

    Wenn Sie mit dem Plan zufrieden sind, wechseln Sie zurück in den Build Mode
    indem Sie erneut die Tabulatortaste drücken.

    bash frame="none"
    <TAB>

    Und es bitten, die Änderungen vorzunehmen.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Änderungen vornehmen

Für einfachere Änderungen können Sie OpenCode bitten, es direkt zu erstellen
ohne den Plan vorher überprüfen zu müssen.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Sie möchten sicherstellen, dass Sie viele Details bereitstellen, damit OpenCode die richtigen
Änderungen vornimmt.


Änderungen rückgängig machen

Nehmen wir an, Sie bitten OpenCode, einige Änderungen vorzunehmen.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Aber Sie erkennen, dass es nicht das ist, was Sie wollten. Sie können die Änderungen rückgängig machen
mit dem Befehl /undo.

bash frame="none"
/undo

OpenCode macht nun die von Ihnen vorgenommenen Änderungen rückgängig und zeigt Ihre ursprüngliche Nachricht
wieder an.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Von hier aus können Sie die Eingabeaufforderung anpassen und OpenCode bitten, es erneut zu versuchen.

:::tip
Sie können /undo mehrmals ausführen, um mehrere Änderungen rückgängig zu machen.
:::

Oder Sie können die Änderungen mit dem Befehl /redo wiederholen.

bash frame="none"
/redo

Anpassung

Und das ist es! Sie sind jetzt ein Profi im Umgang mit OpenCode.

Um es zu Ihrem eigenen zu machen, empfehlen wir ein Theme auszuwählen, Keybinds anzupassen, Code-Formatter zu konfigurieren, eigene Commands zu erstellen oder mit der OpenCode-Konfiguration zu experimentieren.


Packages Web Src Content Docs Es Index (`packages/web/src/content/docs/es/index.mdx`)


title: Introducción

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode es un agente de codigo de IA de código abierto. Está disponible como interfaz basada en terminal, aplicación de escritorio o extensión IDE.

Comencemos.


Requisitos previos

Para usar OpenCode en la terminal, necesitará:

  1. Un emulador de terminal moderno como:

  2. Claves de API de los proveedores de LLM que quiera usar.


Instalar

La forma más sencilla de instalar OpenCode es mediante el script de instalación.

bash
curl -fsSL https://opencode.ai/install | bash

También puedes instalarlo con alguno de los siguientes métodos:

  • Usando Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Usando Homebrew en macOS y Linux

    bash
    brew install anomalyco/tap/opencode

    Recomendamos utilizar el tap OpenCode para las versiones más actualizadas. La fórmula oficial brew install opencode la mantiene el equipo Homebrew y se actualiza con menos frecuencia.

  • Usando Paru en Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Recomendado: Usar WSL]
Para obtener la mejor experiencia en Windows, recomendamos utilizar Windows Subsystem for Linux (WSL). Ofrece mejor rendimiento y compatibilidad total con las funciones de OpenCode.
:::

  • Usando Chocolatey

    bash
    choco install opencode
  • Usando Scoop

    bash
    scoop install opencode
  • Usando NPM

    bash
    npm install opencode-ai
  • Usando Mise

    bash
    mise use -g github:anomalyco/opencode
  • Usando Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

El soporte para instalar OpenCode en Windows usando Bun todavía está en desarrollo.

También puede obtener el binario desde Versiones.


Configuración

Con OpenCode, puede usar cualquier proveedor de LLM configurando sus claves de API.

Si es nuevo en el uso de proveedores de LLM, le recomendamos usar OpenCode Zen.
Es una selección de modelos probados y verificados por el equipo de OpenCode.

  1. Ejecute el comando /connect en la TUI, seleccione opencode y diríjase a opencode.ai/auth.

    txt
    /connect
  2. Inicie sesión, agregue sus datos de facturación y copie su clave de API.

  3. Pega tu clave de API.

    txt
    ┌ API key
    │
    │
    └ enter

También puede seleccionar otro proveedor. Más información.


Inicializar

Ahora que ya configuró un proveedor, vaya al proyecto en el que quiera trabajar.

bash
cd /path/to/project

Luego, ejecute OpenCode.

bash
opencode

A continuación, inicialice OpenCode para el proyecto con el siguiente comando:

bash frame="none"
/init

OpenCode analizará su proyecto y creará un archivo AGENTS.md en la raíz.

:::tip
Asegúrese de versionar en Git el archivo AGENTS.md de su proyecto.
:::

Esto ayuda a OpenCode a comprender la estructura del proyecto y los patrones de código que se usan en él.


Usar

Ahora ya está listo para usar OpenCode en su proyecto. Puede pedirle desde explicaciones del código hasta cambios concretos.

Si es la primera vez que usa un agente de codigo con IA, estos ejemplos pueden servirle como punto de partida.


Hacer preguntas

Puede pedirle a OpenCode que le explique el código base.

:::tip
Utilice la tecla @ para realizar una búsqueda aproximada de archivos dentro del proyecto.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
¿Cómo se maneja la autenticación en @packages/functions/src/api/index.ts

Esto resulta útil cuando hay una parte del código base en la que usted no ha trabajado.


Agregar funcionalidades

Puede pedirle a OpenCode que agregue nuevas funcionalidades a su proyecto. Aun así, primero recomendamos pedirle que cree un plan.

  1. Crear un plan

    OpenCode tiene un modo Plan que desactiva temporalmente su capacidad de hacer cambios y, en su lugar, propone cómo implementará la funcionalidad.

    Cambie a este modo con la tecla Tab. Verá un indicador en la esquina inferior derecha.

    bash frame="none" title="switch to plan mode"
    <TAB>

    Ahora describa lo que quiere que haga.

    txt frame="none"
    Cuando un usuario elimine una nota, queremos marcarla como eliminada en la base de datos.
    Luego, cree una pantalla que muestre todas las notas eliminadas recientemente.
    Desde esa pantalla, el usuario podrá restaurar una nota o eliminarla de forma permanente.

    Procure darle a OpenCode suficiente contexto para que entienda exactamente lo que necesita. Ayuda hablarle como si estuviera hablando con un desarrollador junior de su equipo.

    :::tip
    Déle a OpenCode todo el contexto y los ejemplos que pueda para ayudarle a comprender lo que desea.
    :::

  2. Iterar sobre el plan

    Una vez que OpenCode le proponga un plan, puede darle comentarios o agregar más detalles.

    txt frame="none"
    Queremos diseñar esta nueva pantalla usando un diseño que ya hemos usado antes.
    [Imagen #1] Revise esta imagen y úsela como referencia.

    :::tip
    Arrastre y suelte imágenes en la terminal para agregarlas al mensaje.
    :::

    OpenCode puede analizar cualquier imagen que usted le proporcione y añadirla al contexto del mensaje. Puede hacerlo arrastrando y soltando una imagen en la terminal.

  3. Implementar la funcionalidad

    Cuando esté conforme con el plan, vuelva al modo Build presionando de nuevo la tecla Tab.

    bash frame="none"
    <TAB>

    Luego, pídale que haga los cambios.

    bash frame="none"
    Perfecto. Continúe y realice los cambios.

Realizar cambios

Para cambios más sencillos, puede pedirle a OpenCode que los implemente directamente, sin revisar antes un plan.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
Necesitamos agregar autenticación a la ruta /settings. Revise cómo se maneja esto
en la ruta /notes en @packages/functions/src/notes.ts e implemente
la misma lógica en @packages/functions/src/settings.ts.

Procure dar suficientes detalles para que OpenCode pueda tomar las decisiones correctas al hacer los cambios


Deshacer cambios

Supongamos que le pide a OpenCode que haga algunos cambios.

txt frame="none" "@packages/functions/src/api/index.ts"
¿Puede refactorizar la función en @packages/functions/src/api/index.ts?

Pero luego se da cuenta de que no era lo que quería. Puede deshacer los cambios usando el comando /undo.

bash frame="none"
/undo

OpenCode revertirá los cambios que hizo y volverá a mostrar su mensaje original.

txt frame="none" "@packages/functions/src/api/index.ts"
¿Puede refactorizar la función en @packages/functions/src/api/index.ts?

Desde ahí, puede modificar el mensaje y pedirle a OpenCode que lo intente de nuevo.

:::tip
Puede ejecutar /undo varias veces para deshacer varios cambios.
:::

También puede rehacer los cambios usando el comando /redo.

bash frame="none"
/redo

Personalizar

Y eso es todo. Ya conoce lo básico para empezar a usar OpenCode.

Para personalizarlo, recomendamos elegir un tema, personalizar las combinaciones de teclas, configurar formateadores de código, crear comandos personalizados o explorar la configuración OpenCode.


Packages Web Src Content Docs Fr Index (`packages/web/src/content/docs/fr/index.mdx`)


title: Introduction

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode est un agent de codage d'IA open source. Il est disponible sous forme d'interface basée sur un terminal, d'application de bureau ou d'extension IDE.

Commençons.


Prérequis

Pour utiliser OpenCode dans votre terminal, vous aurez besoin de :

  1. Un émulateur de terminal moderne comme :

  2. Clés API pour les fournisseurs de LLM que vous souhaitez utiliser.


Installation

Le moyen le plus simple d'installer OpenCode est d'utiliser le script d'installation.

bash
curl -fsSL https://opencode.ai/install | bash

Vous pouvez également l'installer avec les commandes suivantes :

  • Node.js

    text
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
    </TabItem>
    
    <TabItem label="Bun">
    ```bash
    bun install -g opencode-ai
    ```
    
    </TabItem>
    
    <TabItem label="pnpm">
    ```bash
    pnpm install opencode-ai
    ```
    
    </TabItem>
    
    <TabItem label="Yarn">
    ```bash
    yarn global add opencode-ai
    ```
    
    </TabItem>
  • Via Homebrew sur macOS et Linux

    bash
    brew install anomalyco/tap/opencode

    Nous vous recommandons d'utiliser le tap OpenCode pour les versions les plus récentes. La formule officielle brew install opencode est maintenue par l'équipe Homebrew et est mise à jour moins fréquemment.

  • Via Paru sur Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Recommandé : utilisez WSL]
Pour une expérience optimale sur Windows, nous vous recommandons d'utiliser le Windows Subsystem for Linux (WSL). Il offre de meilleures performances et une compatibilité totale avec les fonctionnalités de OpenCode.
:::

  • Via Chocolatey

    bash
    choco install opencode
  • Via Scoop

    bash
    scoop install opencode
  • Via NPM

    bash
    npm install opencode-ai
  • Via Mise

    bash
    mise use -g github:anomalyco/opencode
  • Via Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Le support de l'installation de OpenCode sur Windows à l'aide de Bun est actuellement en cours de développement.

Vous pouvez également récupérer le binaire dans les Releases.


Configuration

Avec OpenCode, vous pouvez utiliser n'importe quel fournisseur de LLM en configurant ses clés API.

Si vous débutez avec les fournisseurs de LLM, nous vous recommandons d'utiliser OpenCode Zen.
C'est une liste curée de modèles qui ont été testés et vérifiés par l'équipe OpenCode.

  1. Exécutez la commande /connect dans le TUI, sélectionnez opencode et allez sur opencode.ai/auth.

    txt
    /connect
  2. Connectez-vous, ajoutez vos informations de facturation et copiez votre clé API.

  3. Collez votre clé API.

    txt
    ┌ API key
    │
    │
    └ enter

Vous pouvez également sélectionner l'un des autres fournisseurs. En savoir plus.


Initialisation

Maintenant que vous avez configuré un fournisseur, vous pouvez accéder à un projet sur lequel vous voulez travailler.

bash
cd /path/to/project

Et exécutez OpenCode.

bash
opencode

Ensuite, initialisez OpenCode pour le projet en exécutant la commande suivante.

bash frame="none"
/init

Cela permettra à OpenCode d'analyser votre projet et de créer un fichier AGENTS.md à la racine du projet.

:::tip
Vous devez valider le fichier AGENTS.md de votre projet dans Git.
:::

Cela aide OpenCode à comprendre la structure du projet et les modèles de codage utilisés.


Utilisation

Vous êtes maintenant prêt à utiliser OpenCode pour travailler sur votre projet. N'hésitez pas à lui demander n'importe quoi !

Si vous débutez dans l'utilisation d'un agent de codage IA, voici quelques exemples qui pourraient aider.


Poser des questions

Vous pouvez demander à OpenCode de vous expliquer la base de code.

:::tip
Utilisez la touche @ pour effectuer une recherche floue de fichiers dans le projet.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Ceci est utile s'il y a une partie de la base de code sur laquelle vous n'avez pas travaillé.


Ajouter des fonctionnalités

Vous pouvez demander à OpenCode d'ajouter de nouvelles fonctionnalités à votre projet. Cependant, nous recommandons d’abord de lui demander de créer un plan.

  1. Créer un plan

OpenCode dispose d'un Mode Plan qui désactive sa capacité à apporter des modifications et suggère plutôt comment il implémentera la fonctionnalité.

Accédez-y à l'aide de la touche Tab. Vous verrez un indicateur à cet effet dans le coin inférieur droit.

bash frame="none" title="switch to plan mode"
<TAB>

Décrivons maintenant ce que nous voulons qu'il fasse.

txt frame="none"
When a user deletes a note, we'd like to flag it as deleted in the database.
   Then create a screen that shows all the recently deleted notes.
   From this screen, the user can undelete a note or permanently delete it.

Vous souhaitez donner à OpenCode suffisamment de détails pour comprendre ce que vous voulez. Ça aide pour lui parler comme si vous parliez à un développeur junior de votre équipe.

:::tip
Donnez à OpenCode beaucoup de contexte et d'exemples pour l'aider à comprendre ce que vous voulez.
:::

  1. Itérer sur le plan

Une fois qu'il vous donne un plan, vous pouvez lui faire part de vos commentaires ou ajouter plus de détails.

txt frame="none"
We'd like to design this new screen using a design I've used before.
   [Image #1] Take a look at this image and use it as a reference.

:::tip
Glissez-déposez des images dans le terminal pour les ajouter à l'invite.
:::

OpenCode peut scanner toutes les images que vous lui donnez et les ajouter à l'invite. Vous pouvez le faire en glissant et en déposant une image dans le terminal.

  1. Créez la fonctionnalité

Une fois que vous vous sentez à l'aise avec le plan, revenez au Mode Build en appuyant à nouveau sur la touche Tab.

bash frame="none"
<TAB>

Et demandez-lui d'apporter les modifications.

bash frame="none"
Sounds good! Go ahead and make the changes.

Apporter des modifications

Pour des modifications plus simples, vous pouvez demander à OpenCode de construire directement sans avoir à revoir le plan au préalable.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Vous devez fournir suffisamment de détails pour qu'OpenCode effectue les bonnes modifications.


Annuler les modifications

Disons que vous demandez à OpenCode d'apporter quelques modifications.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Mais vous réalisez que ce n’est pas ce que vous vouliez. Vous pouvez annuler les modifications à l'aide de la commande /undo.

bash frame="none"
/undo

OpenCode annulera désormais les modifications que vous avez apportées et affichera votre message d'origine encore.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

À partir de là, vous pouvez modifier l'invite et demander à OpenCode de réessayer.

:::tip
Vous pouvez exécuter /undo plusieurs fois pour annuler plusieurs modifications.
:::

Ou vous pouvez refaire les modifications à l'aide de la commande /redo.

bash frame="none"
/redo

Personnaliser

Et c'est tout ! Vous êtes désormais un pro de l'utilisation de OpenCode.

Pour vous l'approprier, nous vous recommandons de choisir un thème, de personnaliser les raccourcis clavier, de configurer les formateurs de code, de créer des commandes personnalisées ou de jouer avec la OpenCode Config.


Packages Web Src Content Docs It Index (`packages/web/src/content/docs/it/index.mdx`)


title: Introduzione

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode e un agente di programmazione AI open source. E disponibile come interfaccia per terminale, app desktop o estensione per IDE.

Iniziamo.


Prerequisiti

Per usare OpenCode nel terminale, ti serve:

  1. Un emulatore di terminale moderno, come:

  2. Le chiavi API dei provider LLM che vuoi usare.


Installa

Il modo piu semplice per installare OpenCode e usare lo script di installazione.

bash
curl -fsSL https://opencode.ai/install | bash

Puoi anche installarlo con i seguenti comandi:

  • Con Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Con Homebrew su macOS e Linux

    bash
    brew install anomalyco/tap/opencode

    Ti consigliamo di usare il tap di OpenCode per avere le release piu aggiornate. La formula ufficiale brew install opencode e mantenuta dal team Homebrew e viene aggiornata meno spesso.

  • Con Paru su Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Consigliato: usa WSL]
Per la migliore esperienza su Windows, ti consigliamo di usare Windows Subsystem for Linux (WSL). Offre prestazioni migliori e piena compatibilita con le funzionalita di OpenCode.
:::

  • Con Chocolatey

    bash
    choco install opencode
  • Con Scoop

    bash
    scoop install opencode
  • Con NPM

    bash
    npm install opencode-ai
  • Con Mise

    bash
    mise use -g github:anomalyco/opencode
  • Con Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Il supporto per installare OpenCode su Windows usando Bun e attualmente in lavorazione.

Puoi anche scaricare il binario dalle Releases.


Configura

Con OpenCode puoi usare qualsiasi provider LLM configurando le relative chiavi API.

Se e la prima volta che usi provider LLM, ti consigliamo OpenCode Zen.
E una lista curata di modelli testati e verificati dal team di OpenCode.

  1. Esegui il comando /connect nella TUI, seleziona opencode e vai su opencode.ai/auth.

    txt
    /connect
  2. Accedi, aggiungi i dettagli di fatturazione e copia la tua chiave API.

  3. Incolla la tua chiave API.

    txt
    ┌ API key
    │
    │
    └ enter

In alternativa, puoi selezionare uno degli altri provider. Scopri di piu.


Inizializza

Ora che hai configurato un provider, puoi spostarti in un progetto su cui vuoi lavorare.

bash
cd /path/to/project

E avviare OpenCode.

bash
opencode

Poi inizializza OpenCode per il progetto eseguendo il comando seguente.

bash frame="none"
/init

Questo fara analizzare il progetto a OpenCode e creera un file AGENTS.md nella root del progetto.

:::tip
Dovresti committare il file AGENTS.md del progetto su Git.
:::

Questo aiuta OpenCode a capire la struttura del progetto e gli stili di codice usati.


Utilizzo

Ora sei pronto a usare OpenCode sul tuo progetto. Sentiti libero di chiedergli qualsiasi cosa!

Se e la prima volta che usi un agente di programmazione AI, ecco alcuni esempi che possono aiutare.


Fai domande

Puoi chiedere a OpenCode di spiegarti la codebase.

:::tip
Usa il tasto @ per fare una ricerca fuzzy dei file nel progetto.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Questo e utile se c'e una parte della codebase su cui non hai lavorato.


Aggiungi funzionalità

Puoi chiedere a OpenCode di aggiungere nuove funzionalita al progetto. Pero ti consigliamo prima di chiedergli di creare un piano.

  1. Crea un piano

    OpenCode ha una Plan mode che disabilita la possibilita di fare modifiche e si limita a suggerire come implementera la funzionalita.

    Passaci con il tasto Tab. Vedrai un indicatore nell'angolo in basso a destra.

    bash frame="none" title="switch to plan mode"
    <TAB>

    Ora descriviamo cosa vogliamo che faccia.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    Devi dare a OpenCode abbastanza dettagli per capire cosa vuoi. Aiuta parlargli come se stessi parlando a uno sviluppatore junior del tuo team.

    :::tip
    Dai a OpenCode molto contesto ed esempi per aiutarlo a capire cosa vuoi.
    :::

  2. Itera sul piano

    Una volta che ti da un piano, puoi dargli feedback o aggiungere piu dettagli.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    Trascina e rilascia le immagini nel terminale per aggiungerle al prompt.
    :::

    OpenCode puo analizzare le immagini che gli dai e aggiungerle al prompt. Puoi farlo trascinando e rilasciando un'immagine nel terminale.

  3. Implementa la funzionalita

    Quando ti senti a tuo agio con il piano, torna in Build mode premendo di nuovo il tasto Tab.

    bash frame="none"
    <TAB>

    E chiedigli di fare le modifiche.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Apporta modifiche

Per modifiche piu semplici, puoi chiedere a OpenCode di implementarle direttamente senza dover prima rivedere un piano.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Assicurati di fornire abbastanza dettagli, cosi OpenCode fa le modifiche giuste.


Annulla modifiche

Mettiamo che tu chieda a OpenCode di fare alcune modifiche.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Ma ti accorgi che non e quello che volevi. Puoi annullare le modifiche usando il comando /undo.

bash frame="none"
/undo

OpenCode ora ripristina le modifiche e mostra di nuovo il tuo messaggio originale.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Da qui puoi modificare il prompt e chiedere a OpenCode di riprovare.

:::tip
Puoi eseguire /undo piu volte per annullare piu modifiche.
:::

Oppure puoi rifare le modifiche usando il comando /redo.

bash frame="none"
/redo

Personalizza

E tutto qui! Ora sei un pro nell'usare OpenCode.

Per renderlo davvero tuo, ti consigliamo di scegliere un tema, personalizzare i tasti rapidi, configurare i formatter, creare comandi personalizzati o sperimentare con la configurazione di OpenCode.


Packages Web Src Content Docs Ja Index (`packages/web/src/content/docs/ja/index.mdx`)


title: はじめに

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode は、オープンソースの AI コーディングエージェントです。これは、ターミナルベースのインターフェイス、デスクトップアプリ、または IDE 拡張機能として利用できます。

を使用したOpenCode TUI

始めましょう。


前提条件

ターミナルで OpenCode を使用するには、次のものが必要です。

  1. 次のような最新のターミナルエミュレータ:

    • WezTerm、クロスプラットフォーム
    • Alacritty、クロスプラットフォーム
    • Ghostty、Linux および macOS
    • Kitty、Linux および macOS
  2. 使用する LLM プロバイダーの API キー。


インストール

OpenCode をインストールする最も簡単な方法は、インストールスクリプトを使用することです。

bash
curl -fsSL https://opencode.ai/install | bash

次のコマンドを使用してインストールすることもできます。

  • Node.js の使用

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • macOS および Linux での Homebrew の使用

    bash
    brew install anomalyco/tap/opencode

    最新のリリースには OpenCode タップを使用することをお勧めします。公式の brew install opencode 式は Homebrew チームによって維持されており、更新頻度は低くなります。

  • Arch Linux での Paru の使用

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[推奨: WSL を使用する]
Windows で最高のエクスペリエンスを得るには、Windows Subsystem for Linux (WSL) を使用することをお勧めします。これにより、パフォーマンスが向上し、OpenCode の機能との完全な互換性が提供されます。
:::

  • Chocolatey の使用

    bash
    choco install opencode
  • Scoop の使用

    bash
    scoop install opencode
  • npm の使用

    bash
    npm install opencode-ai
  • Mise の使用

    bash
    mise use -g github:anomalyco/opencode
  • Docker の使用

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Bun を使用して Windows に OpenCode をインストールするためのサポートは現在進行中です。

Releases.


設定

OpenCode を使用すると、API キーを構成することで任意の LLM プロバイダーを使用できます。

LLM プロバイダーを初めて使用する場合は、OpenCode Zen をお勧めします。
これは、OpenCode チームによってテストおよび検証されたモデルの厳選されたリストです。

  1. TUI で /connect コマンドを実行し、opencode を選択して、opencode.ai/auth で認証します。

    txt
    /connect
  2. サインインし、お支払いの詳細を追加し、API キーをコピーします。

  3. API キーを貼り付けます。

    txt
    ┌ API key
    │
    │
    └ enter

あるいは、他のプロバイダーのいずれかを選択することもできます。 詳細はこちら。


初期化

プロバイダーを構成したので、取り組みたいプロジェクトに移動できます。

bash
cd /path/to/project

そしてOpenCodeを実行します。

bash
opencode

次に、次のコマンドを実行して、プロジェクトの OpenCode を初期化します。

bash frame="none"
/init

これにより、OpenCode がプロジェクトを分析し、プロジェクトのルートに AGENTS.md ファイルを作成します。

:::tip
プロジェクトの AGENTS.md ファイルを Git にコミットする必要があります。
:::

これは、OpenCode がプロジェクトの構造と使用されているコーディングパターンを理解するのに役立ちます。


使用法

これで、OpenCode を使用してプロジェクトに取り組む準備が整いました。何でもお気軽にお尋ねください!

AI コーディングエージェントを初めて使用する場合は、次の例を参考にしてください。


質問する

OpenCode にコードベースの説明を依頼できます。

:::tip
プロジェクト内のファイルをあいまい検索するには、@ キーを使用します。
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

これは、コードベースに作業していない部分がある場合に役立ちます。


機能を追加する

OpenCode に新しい機能をプロジェクトに追加するよう依頼できます。ただし、最初は計画の作成を依頼することをお勧めします。

  1. 計画を作成する

OpenCode には、変更を加える機能を無効にする Plan mode があり、
代わりに、その機能をどのように実装するかを提案します。

Tab キーを使用してそれに切り替えます。右下隅にこれを示すインジケーターが表示されます。

bash frame="none" title="switch to plan mode"
<TAB>

では、何をしたいのかを説明しましょう。

txt frame="none"
When a user deletes a note, we'd like to flag it as deleted in the database.
   Then create a screen that shows all the recently deleted notes.
   From this screen, the user can undelete a note or permanently delete it.

自分が何を望んでいるのかを理解するために、OpenCode に十分な詳細を提供したいと考えています。
チームの若手開発者と話しているように話すと良いでしょう。

:::tip
OpenCode に多くのコンテキストと例を提供して、意図する内容を理解できるようにします。
:::

  1. 計画を反復する

計画が示されたら、フィードバックを送信したり、詳細を追加したりできます。

txt frame="none"
We'd like to design this new screen using a design I've used before.
   [Image #1] Take a look at this image and use it as a reference.

:::tip
画像をターミナルにドラッグアンドドロップして、プロンプトに追加します。
:::

OpenCode は、指定された画像をスキャンしてプロンプトに追加できます。
画像をターミナルにドラッグアンドドロップしてこれを行うことができます。

  1. 機能を構築する

計画に慣れたら、Build modeに戻ります。
Tab キーをもう一度押します。

bash frame="none"
<TAB>

そして変更を加えるように依頼します。

bash frame="none"
Sounds good! Go ahead and make the changes.

変更を加える

より単純な変更については、OpenCode に直接ビルドするよう依頼できます。
最初に計画を見直す必要はありません。

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

OpenCode が適切な変更を行えるように、十分な量の詳細を確実に提供する必要があります。


変更を元に戻す

OpenCode にいくつかの変更を依頼するとします。

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

しかし、それは自分が望んでいたものではないことに気づきます。変更は 元に戻すことができます
/undo コマンドを使用します。

bash frame="none"
/undo

OpenCode は加えた変更を元に戻し、元のメッセージを再度表示します。

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

ここからプロンプトを調整し、OpenCode に再試行を依頼できます。

:::tip
/undo を複数回実行すると、複数の変更を元に戻すことができます。
:::

または、/redo コマンドを使用して変更をやり直すこともできます。

bash frame="none"
/redo

カスタマイズ

それで終わりです!これであなたは OpenCode の使い方のプロになりました。

独自のものにするには、テーマ を選択する、キーバインドをカスタマイズする、コードフォーマッタ を設定する、カスタムコマンド を作成する、または OpenCode設定 を試してみることをお勧めします。


Packages Web Src Content Docs Ko Index (`packages/web/src/content/docs/ko/index.mdx`)


title: 소개

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode는 오픈 소스 AI coding agent입니다. 터미널 기반 인터페이스, 데스크톱 앱, IDE 확장으로 사용할 수 있습니다.

바로 시작해 보겠습니다.


사전 준비

터미널에서 OpenCode를 사용하려면 다음이 필요합니다.

  1. 다음과 같은 최신 터미널 에뮬레이터

  2. 사용할 LLM 제공자의 API 키


설치

OpenCode를 설치하는 가장 쉬운 방법은 설치 스크립트를 사용하는 것입니다.

bash
curl -fsSL https://opencode.ai/install | bash

다음 명령으로도 설치할 수 있습니다.

  • Node.js 사용

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • macOS/Linux에서 Homebrew 사용

    bash
    brew install anomalyco/tap/opencode

    최신 릴리스를 사용하려면 OpenCode tap 사용을 권장합니다. 공식 brew install opencode formula는 Homebrew 팀이 관리하며 업데이트 주기가 더 깁니다.

  • Arch Linux에 설치

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[권장: WSL 사용]
Windows에서는 Windows Subsystem for Linux (WSL) 사용을 권장합니다. 성능이 더 좋고 OpenCode 기능과의 완전한 호환성을 제공합니다.
:::

  • Chocolatey 사용

    bash
    choco install opencode
  • Scoop 사용

    bash
    scoop install opencode
  • NPM 사용

    bash
    npm install opencode-ai
  • Mise 사용

    bash
    mise use -g github:anomalyco/opencode
  • Docker 사용

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

현재 Windows에서 Bun을 사용한 OpenCode 설치 지원은 준비 중입니다.

Releases에서 바이너리를 직접 받아 설치할 수도 있습니다.


구성

OpenCode는 API 키를 설정하면 원하는 LLM 제공자를 사용할 수 있습니다.

LLM 제공자를 처음 사용한다면 OpenCode Zen 사용을 권장합니다.
OpenCode 팀이 테스트하고 검증한 모델 목록입니다.

  1. TUI에서 /connect 명령을 실행하고 opencode를 선택한 다음 opencode.ai/auth로 이동합니다.

    txt
    /connect
  2. 로그인하고 결제 정보를 추가한 뒤 API 키를 복사합니다.

  3. API 키를 붙여 넣습니다.

    txt
    ┌ API key
    │
    │
    └ enter

또는 다른 제공자 중 하나를 선택할 수도 있습니다. 더 알아보기.


초기화

이제 제공자 구성을 마쳤으니 작업하려는 프로젝트로 이동합니다.

bash
cd /path/to/project

그리고 OpenCode를 실행합니다.

bash
opencode

다음 명령을 실행해 프로젝트에서 OpenCode를 초기화합니다.

bash frame="none"
/init

이 명령을 실행하면 OpenCode가 프로젝트를 분석하고 프로젝트 루트에 AGENTS.md 파일을 생성합니다.

:::tip
프로젝트의 AGENTS.md 파일은 Git에 커밋하는 것을 권장합니다.
:::

이렇게 하면 OpenCode가 프로젝트 구조와 사용 중인 코딩 패턴을 더 잘 이해할 수 있습니다.


사용법

이제 OpenCode로 프로젝트 작업을 시작할 준비가 되었습니다. 무엇이든 물어보세요.

AI coding agent를 처음 사용한다면 도움이 될 수 있는 예시를 소개합니다.


질문하기

OpenCode에 코드베이스 설명을 요청할 수 있습니다.

:::tip
프로젝트 파일은 @ 키로 퍼지 검색할 수 있습니다.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

이 방법은 직접 작업하지 않은 코드 영역을 이해할 때 유용합니다.


기능 추가

OpenCode에 프로젝트의 새 기능 추가를 요청할 수 있습니다. 다만 먼저 계획을 만들도록 요청하는 것을 권장합니다.

  1. 계획 만들기

    OpenCode에는 변경 작업 기능을 비활성화하고 기능을 구현할 방법만 제안하는 Plan mode가 있습니다.

    Tab 키를 눌러 전환하세요. 화면 오른쪽 아래에서 모드 표시를 확인할 수 있습니다.

    bash frame="none" title="switch to plan mode"
    <TAB>

    이제 수행하길 원하는 작업을 설명해 보겠습니다.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    OpenCode가 원하는 작업을 이해할 수 있도록 충분한 세부 정보를 제공해야 합니다. 팀의 주니어 개발자에게 말하듯이 설명하면 도움이 됩니다.

    :::tip
    OpenCode가 원하는 작업을 이해하도록 충분한 맥락과 예시를 제공하세요.
    :::

  2. 계획 다듬기

    계획이 나오면 피드백을 주거나 세부 사항을 더 추가할 수 있습니다.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    이미지를 터미널에 드래그 앤 드롭해 prompt에 추가하세요.
    :::

    OpenCode는 제공한 이미지를 스캔해 prompt에 추가할 수 있습니다. 이미지를 터미널에 드래그 앤 드롭하면 됩니다.

  3. 기능 구현

    계획이 충분히 마음에 들면 Tab 키를 다시 눌러 Build mode로 전환하세요.

    bash frame="none"
    <TAB>

    그리고 변경을 적용해 달라고 요청하세요.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

바로 변경하기

비교적 간단한 변경은 계획을 먼저 검토하지 않고 바로 구현하도록 요청할 수 있습니다.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

OpenCode가 올바른 변경을 하도록 충분한 세부 정보를 제공해야 합니다.


변경 되돌리기

예를 들어 OpenCode에 변경을 요청했다고 해보겠습니다.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

그런데 원하는 결과가 아니었다면 /undo 명령으로 변경을 되돌릴 수 있습니다.

bash frame="none"
/undo

OpenCode가 방금 적용한 변경을 되돌리고 원래 메시지를 다시 보여줍니다.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

여기에서 prompt를 수정해 다시 요청할 수 있습니다.

:::tip
/undo는 여러 번 연속으로 실행할 수 있습니다.
:::

또는 /redo 명령으로 변경을 다시 적용할 수 있습니다.

bash frame="none"
/redo

사용자 지정

이제 OpenCode 사용법을 익혔습니다.

원하는 방식에 맞추려면 테마 선택, 키바인드 사용자 지정, 코드 formatter 설정, custom command 만들기, OpenCode config 설정을 권장합니다.


Packages Web Src Content Docs Nb Index (`packages/web/src/content/docs/nb/index.mdx`)


title: Introduksjon

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode er en åpen kildekode AI kodeagent. Den er tilgjengelig som et terminalbasert grensesnitt, skrivebordsapp eller IDE-utvidelse.

La oss komme i gang.


Forutsetninger

For å bruke OpenCode i terminalen din trenger du:

  1. En moderne terminalemulator som:

  2. API-nøkler for LLM-leverandørene du vil bruke.


Installasjon

Den enkleste måten å installere OpenCode på er gjennom installasjonsskriptet.

bash
curl -fsSL https://opencode.ai/install | bash

Du kan også installere den med følgende kommandoer:

  • Bruke Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Bruke Homebrew på macOS og Linux

    bash
    brew install anomalyco/tap/opencode

    Vi anbefaler å bruke OpenCode-tappen for de mest oppdaterte utgivelsene. Den offisielle brew install opencode-formelen vedlikeholdes av Homebrew-teamet og oppdateres sjeldnere.

  • Bruke Paru på Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Anbefalt: Bruk WSL]
For den beste opplevelsen på Windows anbefaler vi å bruke Windows Subsystem for Linux (WSL). Det gir bedre ytelse og full kompatibilitet med funksjonene i OpenCode.
:::

  • Bruke Chocolatey

    bash
    choco install opencode
  • Bruke Scoop

    bash
    scoop install opencode
  • Bruke npm

    bash
    npm install opencode-ai
  • Bruke Mise

    bash
    mise use -g github:anomalyco/opencode
  • Bruke Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Støtte for installasjon av OpenCode på Windows med Bun er under arbeid.

Du kan også hente binæren fra Releases.


Konfigurasjon

Med OpenCode kan du bruke hvilken som helst LLM-leverandør ved å konfigurere deres API-nøkler.

Hvis du er ukjent med LLM-leverandører, anbefaler vi å bruke OpenCode Zen.
Det er en kuratert liste over modeller som har blitt testet og verifisert av OpenCode-teamet.

  1. Kjør kommandoen /connect i TUI, velg OpenCode og gå til opencode.ai/auth.

    txt
    /connect
  2. Logg på, legg til faktureringsdetaljene dine og kopier API-nøkkelen.

  3. Lim inn API-nøkkelen.

    txt
    ┌ API key
    │
    │
    └ enter

Alternativt kan du velge en av de andre leverandørene. Finn ut mer.


Initialisering

Nå som du har konfigurert en leverandør, kan du navigere til et prosjekt som
du vil jobbe med.

bash
cd /path/to/project

Og kjør OpenCode.

bash
opencode

Deretter initialiserer du OpenCode for prosjektet ved å kjøre følgende kommando.

bash frame="none"
/init

Dette vil få OpenCode til å analysere prosjektet ditt og opprette en AGENTS.md-fil i
prosjektroten.

:::tip
Du bør overgi prosjektets AGENTS.md-fil til Git.
:::

Dette hjelper OpenCode med å forstå prosjektstrukturen og kodingsmønstrene
brukt.


Bruk

Du er nå klar til å bruke OpenCode for å jobbe med prosjektet ditt. Spør det gjerne
noe!

Hvis du er ukjent med AI-kodeagenter, her er noen eksempler som kan
hjelpe.


Still spørsmål

Du kan be OpenCode forklare kodebasen for deg.

:::tip
Bruk @-tasten for uklart søk etter filer i prosjektet.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Dette er nyttig hvis det er en del av kodebasen du ikke har jobbet med.


Legg til funksjonalitet

Du kan be OpenCode legge til nye funksjoner i prosjektet ditt. Selv om vi først anbefaler å be den om å lage en plan.

  1. Lag en plan

    OpenCode har en Plan-modus som deaktiverer muligheten til å gjøre endringer og
    foreslår i stedet hvordan den vil implementere funksjonen.

    Bytt til den ved å bruke Tab-tasten. Du vil se en indikator for dette i nedre høyre hjørne.

    bash frame="none" title="switch to plan mode"
    <TAB>

    La oss nå beskrive hva vi vil at den skal gjøre.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    Du bør gi OpenCode nok detaljer til å forstå hva du ønsker. Det hjelper
    å snakke med det som om du snakker med en juniorutvikler på laget ditt.

    :::tip
    Gi OpenCode mye kontekst og eksempler for å hjelpe den å forstå hva du
    ønsker.
    :::

  2. Iterer på planen

    Når du får en plan, kan du gi den tilbakemelding eller legge til flere detaljer.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    Dra og slipp bilder i terminalen for å legge dem til ledeteksten.
    :::

    OpenCode kan skanne alle bilder du gir den og legge dem til i ledeteksten. Du kan
    gjør dette ved å dra og slippe et bilde inn i terminalen.

  3. Bygg funksjonen

    Når du føler deg komfortabel med planen, bytt tilbake til Byggemodus ved å
    trykke på Tab-tasten igjen.

    bash frame="none"
    <TAB>

    Og be den om å gjøre endringene.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Gjør endringer

For mer enkle endringer kan du be OpenCode om å bygge det direkte
uten å måtte gjennomgå planen først.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Sørg for å gi nok detaljer, slik at OpenCode gjør de rette
endringene.


Angre endringer

La oss si at du ber OpenCode om å gjøre noen endringer.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Men du skjønner at det ikke er det du ønsket. Du kan angre endringene
ved å bruke kommandoen /undo.

bash frame="none"
/undo

OpenCode vil nå tilbakestille endringene du har gjort og vise den opprinnelige meldingen
igjen.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Herfra kan du justere ledeteksten og be OpenCode om å prøve igjen.

:::tip
Du kan kjøre /undo flere ganger for å angre flere endringer.
:::

Eller du kan gjøre om endringene ved å bruke /redo-kommandoen.

bash frame="none"
/redo

Tilpasning

Og det er det! Du er nå en proff på å bruke OpenCode.

For å tilpasse det anbefaler vi å velge et tema, tilpasse tastebindingene, konfigurere kodeformattere, opprette egendefinerte kommandoer eller leke med OpenCode-konfigurasjonen.


Packages Web Src Content Docs Pl Index (`packages/web/src/content/docs/pl/index.mdx`)


title: Wstęp

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

opencode to agent kodujący AI typu open source. Jest dostępny jako interfejs terminalowy, aplikacja desktopowa i rozszerzenie IDE.

Zacznijmy.


Warunki wstępne

Aby uzyskać dostęp do opencode w swoim terminalu, będziesz potrzebować:

  1. Nowoczesny emulator terminala, taki jak:

  2. Klucze API dla dostawców LLM, z których korzystasz.


Instalacja

Najłatwiej zainstalować opencode za pomocą skryptu instalacyjnego.

bash
curl -fsSL https://opencode.ai/install | bash

Możesz też użyć poniższych metod instalacji:

  • Przy użyciu Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Korzystanie z Homebrew na macOS i Linux

    bash
    brew install anomalyco/tap/opencode

    W celu uzyskania najbardziej aktualnej wersji zalecamy korzystanie z opencode. Oficjalna formuła brew install opencode jest utrzymywana przez zespół Homebrew i jest aktualizowana.

  • Korzystanie z Paru na Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Zalecane: Uruchamianie w WSL]
Aby najlepiej wykorzystać działanie w systemie Windows, zalecamy włączenie Podsystemu Windows dla systemu Linux (WSL). Zapewnia to pełną kompatybilność z funkcjami opencode.
:::

  • Używając Chocolatey

    bash
    choco install opencode
  • Korzystanie z Scoop

    bash
    scoop install opencode
  • Przy użyciu NPM

    bash
    npm install opencode-ai
  • Używając Mise’a

    bash
    mise use -g github:anomalyco/opencode
  • Korzystanie z Dockera

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

Obecnie pracujemy nad instalacją opencode w systemie Windows za pomocą Bun.

Możesz także pobrać plik binarny z Releases.


Konfiguracja

Dzięki opencode możesz korzystać z dowolnego dostawcy LLM, konfigurując jego klucze API.

Jeśli będziesz korzystać z wielu dostawców LLM, zalecamy skorzystanie z OpenCode Zen.
Aby uzyskać dostęp do wyselekcjonowanej listy modeli, które zostały zatwierdzone i zweryfikowane przez zespół opencode.

  1. Uruchom polecenie /connect w TUI, wybierz opencode i przejdź do opencode.ai/auth.

    txt
    /connect
  2. Zaloguj się, dodaj szczegóły rozliczeniowe i skopiuj klucz API.

  3. Wklej swój klucz API.

    txt
    ┌ API key
    │
    │
    └ enter

Alternatywnie możesz wybrać jednego z dodatkowych dostawców. Dowiedz się więcej.


Inicjalizacja

Po skonfigurowaniu dostawcy możesz przejść do projektu, nad którym chcesz pracować.

bash
cd /path/to/project

Uruchom opencode.

bash
opencode

Następnie zainicjuj opencode dla projektu, uruchamiając odpowiednie polecenie.

bash frame="none"
/init

Spowoduje to, że opencode przeanalizuje Twój projekt i utworzy plik AGENTS.md w katalogu głównym projektu.

:::tip
Powinieneś zacommitować plik AGENTS.md swojego projektu w Git.
:::

Pomaga to opencode zrozumieć strukturę projektu i stosowane wzorce kodowania.


Użycie

Teraz możesz pracować nad swoim projektem. Możesz zapytać o wszystko!

Jeśli dopiero zaczynasz korzystać z agenta kodującego AI, oto kilka wskazówek, które mogą być pomocne.


Zadawaj pytania

Możesz poprosić opencode o wyjaśnienie bazy kodu.

:::tip
Użyj @ do wyszukiwania rozmytego plików w projekcie.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Jest to pomocne, jeśli istnieje część bazy kodu, nad którą nie pracowałeś.


Dodaj funkcje

Możesz poprosić opencode o dodanie nowej funkcji do Twojego projektu. Najpierw zalecamy poproszenie o przygotowanie planu.

  1. Stwórz Plan

    opencode ma Plan Mode, który umożliwia wyłączenie zmian i
    zamiast tego zasugeruje, jak zaimplementować tę funkcję.

    Przejdź do niego za pomocą klawisza Tab. Zobaczysz odpowiedni wskaźnik w prawym dolnym rogu.

    bash frame="none" title="switch to plan mode"
    <TAB>

    Opiszmy teraz, co chcemy, żeby zrobił.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    Wersja opencode jest bardzo inteligentna, aby zrozumieć, czego chcesz. To pomaga
    rozmawiaj z nim tak, jakbyś rozmawiał z młodszym programistą w swoim zespole.

    :::tip
    Podaj opencode kontekst, aby zrozumiał, czego chcesz.
    :::

  2. Udoskonalanie planu

    Gdy będziesz mieć plan, możesz zostawić go lub dodać więcej.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    Przeciągnij i upuść obrazy do terminala, aby dodać je do monitu.
    :::

    opencode może zeskanować obrazy, które mu przekażesz i zrozumieć je. Możesz to zrobić, przeciągając i upuszczając obraz do terminala.

  3. Wprowadź zmiany

    Kiedy już będziesz zadowolony z planu, przełącz się z powrotem do Act Mode naciskając klawisz Tab.

    bash frame="none"
    <TAB>

    Poproś o wprowadzenie zmian.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Wprowadź zmiany

Aby wprowadzić kolejną zmianę, możesz poprosić opencode lub zrobić to bezpośrednio bez konieczności wcześniejszego przeglądania planu.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Musisz upewnić się, że dostarczyłeś odpowiednie pliki, aby opencode mógł wprowadzić zmiany.


Cofnij zmiany

Załóżmy, że prosisz opencode o wprowadzenie zmian.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Ale zdajesz sobie sprawę, że to nie jest to, czego chciałeś. Możesz cofnąć zmiany
za pomocą polecenia /undo.

bash frame="none"
/undo

opencode cofnie teraz zmiany i wyświetli wiadomość ponownie.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Możesz edytować monit i poprosić opencode o ponowną próbę.

:::tip
Możesz użyć /undo wiele razy, aby cofnąć wiele zmian.
:::

Możesz też przywrócić zmianę za pomocą polecenia /redo.

bash frame="none"
/redo

Dostosuj

To tyle! Jesteś teraz profesjonalistą w korzystaniu z opencode.

Aby dostosować go do potrzeb, zalecamy wybranie motywu, dostosowanie skrótów klawiaturowych, konfigurowanie programów formatujących kod, tworzenie niestandardowych poleceń lub zabawę z konfiguracją opencode.


Packages Web Src Content Docs Pt Br Index (`packages/web/src/content/docs/pt-br/index.mdx`)


title: Introdução

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

opencode é um agente de codificação de IA de código aberto. Está disponível como uma interface baseada em terminal, aplicativo desktop ou extensão de IDE.

Vamos começar.


Pré-requisitos

Para usar o opencode no seu terminal, você precisará de:

  1. Um emulador de terminal moderno como:

  2. Chaves de API para os provedores de LLM que você deseja usar.


Instalação

A maneira mais fácil de instalar o opencode é através do script de instalação.

bash
curl -fsSL https://opencode.ai/install | bash

Você também pode instalá-lo com os seguintes comandos:

  • Usando Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Usando Homebrew no macOS e Linux

    bash
    brew install anomalyco/tap/opencode

    Recomendamos usar o tap do opencode para as versões mais atualizadas. A fórmula oficial brew install opencode é mantida pela equipe do Homebrew e é atualizada com menos frequência.

  • Usando Paru no Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Recomendado: Use WSL]
Para a melhor experiência no Windows, recomendamos usar o Windows Subsystem for Linux (WSL). Ele oferece melhor desempenho e total compatibilidade com os recursos do opencode.
:::

  • Usando Chocolatey

    bash
    choco install opencode
  • Usando Scoop

    bash
    scoop install opencode
  • Usando NPM

    bash
    npm install opencode-ai
  • Usando Mise

    bash
    mise use -g github:anomalyco/opencode
  • Usando Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

O suporte para instalar o opencode no Windows usando Bun está atualmente em andamento.

Você também pode baixar o binário na seção Releases.


Configuração

Com o opencode, você pode usar qualquer provedor de LLM configurando suas chaves de API.

Se você é novo no uso de provedores de LLM, recomendamos usar o OpenCode Zen.
É uma lista selecionada de modelos que foram testados e verificados pela equipe do opencode.

  1. Execute o comando /connect no TUI, selecione opencode e acesse opencode.ai/auth.

    txt
    /connect
  2. Faça login, adicione seus dados de cobrança e copie sua chave de API.

  3. Cole sua chave de API.

    txt
    ┌ API key
    │
    │
    └ enter

Alternativamente, você pode selecionar um dos outros provedores. Saiba mais.


Inicialização

Agora que você configurou um provedor, pode navegar até um projeto no qual deseja trabalhar.

bash
cd /path/to/project

E execute o opencode.

bash
opencode

Em seguida, inicialize o opencode para o projeto executando o seguinte comando.

bash frame="none"
/init

Isso fará com que o opencode analise seu projeto e crie um arquivo AGENTS.md na raiz do projeto.

:::tip
Você deve commitar o arquivo AGENTS.md do seu projeto no Git.
:::

Isso ajuda o opencode a entender a estrutura do projeto e os padrões de codificação utilizados.


Uso

Agora você está pronto para usar o opencode para trabalhar em seu projeto. Sinta-se à vontade para perguntar qualquer coisa!

Se você é novo no uso de um agente de codificação de IA, aqui estão alguns exemplos que podem ajudar.


Fazendo perguntas

Você pode pedir ao opencode para explicar a base de código para você.

:::tip
Use a tecla @ para buscar arquivos no projeto.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Isso é útil se houver uma parte da base de código na qual você não trabalhou.


Adicionando recursos

Você pode pedir ao opencode para adicionar novos recursos ao seu projeto. Embora primeiro recomendemos pedir para ele criar um plano.

  1. Criar um plano

    O opencode tem um Modo de Plano que desabilita sua capacidade de fazer alterações e, em vez disso, sugere como implementará o recurso.

    Mude para ele usando a tecla Tab. Você verá um indicador para isso no canto inferior direito.

    bash frame="none" title="switch to plan mode"
    <TAB>

    Agora vamos descrever o que queremos que ele faça.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    Você quer dar ao opencode detalhes suficientes para entender o que você deseja. Ajuda conversar com ele como se você estivesse falando com um desenvolvedor júnior da sua equipe.

    :::tip
    Dê ao opencode bastante contexto e exemplos para ajudá-lo a entender o que você deseja.
    :::

  2. Iterar sobre o plano

    Uma vez que ele lhe der um plano, você pode dar feedback ou adicionar mais detalhes.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    Arraste e solte imagens no terminal para adicioná-las ao prompt.
    :::

    O opencode pode escanear qualquer imagem que você fornecer e adicioná-la ao prompt. Você pode fazer isso arrastando e soltando uma imagem no terminal.

  3. Construir o recurso

    Uma vez que você se sinta confortável com o plano, volte para o Modo de Construção pressionando a tecla Tab novamente.

    bash frame="none"
    <TAB>

    E peça para ele fazer as alterações.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Fazendo alterações

Para alterações mais simples, você pode pedir ao opencode para construí-las diretamente sem precisar revisar o plano primeiro.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Você quer ter certeza de fornecer uma boa quantidade de detalhes para que o opencode faça as alterações corretas.


Desfazendo alterações

Vamos supor que você peça ao opencode para fazer algumas alterações.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Mas você percebe que não era isso que você queria. Você pode desfazer as alterações usando o comando /undo.

bash frame="none"
/undo

O opencode agora reverterá as alterações que você fez e mostrará sua mensagem original novamente.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

A partir daqui, você pode ajustar o prompt e pedir ao opencode para tentar novamente.

:::tip
Você pode executar /undo várias vezes para desfazer várias alterações.
:::

Ou você pode refazer as alterações usando o comando /redo.

bash frame="none"
/redo

Personalização

E é isso! Agora você é um profissional em usar o opencode.

Para torná-lo seu, recomendamos escolher um tema, personalizar os atalhos de teclado, configurar formatadores de código, criar comandos personalizados ou brincar com a configuração do opencode.


Packages Web Src Content Docs Ru Index (`packages/web/src/content/docs/ru/index.mdx`)


title: Введение

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

opencode — это агент кодирования искусственного интеллекта с открытым исходным кодом. Он доступен в виде интерфейса на базе терминала, настольного приложения или расширения IDE.

Давайте начнем.


Системные требования

Чтобы использовать opencode в вашем терминале, вам понадобится:

  1. Современный эмулятор терминала, например:

    • WezTerm, кроссплатформенный
    • Alacritty, кроссплатформенный
    • Ghostty, Linux и macOS
    • Kitty, Linux и macOS
  2. Ключи API для поставщиков LLM, которых вы хотите использовать.


Установка

Самый простой способ установить opencode — через сценарий установки.

bash
curl -fsSL https://opencode.ai/install | bash

Вы также можете установить его с помощью следующих команд:

  • Использование Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Использование Homebrew в macOS и Linux

    bash
    brew install anomalyco/tap/opencode

    Мы рекомендуем использовать tap opencode для получения самых последних версий. Официальная формула brew install opencode поддерживается командой Homebrew и обновляется реже.

  • Использование Paru в Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Рекомендуется: используйте WSL]
Для наилучшей работы в Windows мы рекомендуем использовать Подсистема Windows для Linux (WSL). Он обеспечивает лучшую производительность и полную совместимость с функциями opencode.
:::

  • Используя Chocolatey

    bash
    choco install opencode
  • Использование Scoop

    bash
    scoop install opencode
  • Использование NPM

    bash
    npm install opencode-ai
  • Использование Mise

    bash
    mise use -g github:anomalyco/opencode
  • Использование Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

В настоящее время добавляется поддержка установки opencode в Windows с помощью Bun.

Вы также можете получить бинарный файл в разделе Releases.


Настроить

С opencode вы можете использовать любого поставщика LLM, настроив его ключи API.

Если вы новичок в использовании поставщиков LLM, мы рекомендуем использовать OpenCode Zen.
Это тщательно подобранный список моделей, протестированных и проверенных opencode.

  1. Запустите команду /connect в TUI, выберите opencode и перейдите по адресу opencode.ai/auth.

    txt
    /connect
  2. Войдите в систему, добавьте свои платежные данные и скопируйте ключ API.

  3. Вставьте свой ключ API.

    txt
    ┌ API key
    │
    │
    └ enter

Альтернативно вы можете выбрать одного из других поставщиков. Подробнее.


Инициализация

Теперь, когда вы настроили поставщика, вы можете перейти к проекту, который
над которым вы хотите работать.

bash
cd /path/to/project

И запустите opencode.

bash
opencode

Затем инициализируйте opencode для проекта, выполнив следующую команду.

bash frame="none"
/init

Это позволит opencode проанализировать ваш проект и создать файл AGENTS.md в
корень проекта.

:::tip
Вам следует зафиксировать файл AGENTS.md вашего проекта в Git.
:::

Это помогает opencode понять структуру проекта и шаблоны кодирования.
использовал.


Использование

Теперь вы готовы использовать opencode для работы над своим проектом. Не стесняйтесь спрашивать о чем угодно!

Если вы новичок в использовании агента кодирования ИИ, вот несколько примеров, которые могут вам помочь.


Задавайте вопросы

Вы можете попросить opencode объяснить вам кодовую базу.

:::tip
Используйте ключ @ для нечеткого поиска файлов в проекте.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Это полезно, если есть часть кодовой базы, над которой вы не работали.


Добавление функций

Вы можете попросить opencode добавить новые функции в ваш проект. Хотя мы сначала рекомендуем попросить его создать план.

  1. Составьте план

    opencode имеет режим планирования, который отключает возможность вносить изменения и
    вместо этого предложите как реализовать эту функцию.

    Переключитесь на него с помощью клавиши Tab. Вы увидите индикатор этого в правом нижнем углу.

    bash frame="none" title="switch to plan mode"
    <TAB>

    Теперь давайте опишем, что мы хотим от него.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    Нужно предоставить opencode достаточно подробностей, чтобы ему понять, чего вы хотите. Это помогает
    поговорить с ним так, как будто вы разговариваете с младшим разработчиком в своей команде.

    :::tip
    Дайте opencode много контекста и примеров, чтобы помочь ему понять, что вы
    хотеть.
    :::

  2. Итерация плана

    Как только он предоставит вам план, вы можете оставить ему отзыв или добавить более подробную информацию.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    Перетащите изображения в терминал, чтобы добавить их в подсказку.
    :::

    opencode может сканировать любые изображения, которые вы ему предоставляете, и добавлять их в командную строку. Вы можете
    сделать это, перетащив изображение в терминал.

  3. Создайте функцию

    Как только вы почувствуете себя комфортно с планом, вернитесь в режим сборки,
    снова нажав клавишу Tab.

    bash frame="none"
    <TAB>

    И попросите его внести изменения.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Внесение изменений

Для более простых изменений вы можете попросить opencode создать их напрямую.
без необходимости предварительного рассмотрения плана.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

Убедитесь, что предоставили достаточно деталей, чтобы opencode внес корректные изменения.


Отмена изменений

Допустим, вы просите opencode внести некоторые изменения.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Но вы понимаете, что это не то, чего вы хотели. Вы можете отменить изменения
с помощью команды /undo.

bash frame="none"
/undo

opencode отменит внесенные вами изменения и покажет исходное сообщение.
снова.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Отсюда вы можете настроить подсказку и попросить opencode повторить попытку.

:::tip
Вы можете запустить /undo несколько раз, чтобы отменить несколько изменений.
:::

Или вы можете повторить изменения с помощью команды /redo.

bash frame="none"
/redo

Настроить

И все! Теперь вы профессионал в использовании opencode.

Чтобы создать свою собственную, мы рекомендуем выбрать тему, настроить привязки клавиш, настроить средства форматирования кода, создать собственные команды или поиграться с файлом opencode config.


Packages Web Src Content Docs Th Index (`packages/web/src/content/docs/th/index.mdx`)


title: บทนำ

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode คือเอเจนต์การเข้ารหัส AI แบบโอเพ่นซอร์ส มีให้บริการในรูปแบบอินเทอร์เฟซบน terminal แอปเดสก์ท็อป หรือส่วนขยาย IDE

มาเริ่มกันเลย


ข้อกำหนดเบื้องต้น

หากต้องการใช้ OpenCode ใน terminal คุณจะต้องมี:

  1. terminal อีมูเลเตอร์ที่ทันสมัยเช่น:

    • WezTerm ข้ามแพลตฟอร์ม
    • Alacritty ข้ามแพลตฟอร์ม
    • Ghostty, Linux และ macOS
    • Kitty, Linux และ macOS
  2. API Key สำหรับผู้ให้บริการ LLM ที่คุณต้องการใช้


ติดตั้ง

วิธีที่ง่ายที่สุดในการติดตั้ง OpenCode คือการใช้สคริปต์การติดตั้ง

bash
curl -fsSL https://opencode.ai/install | bash

คุณยังสามารถติดตั้งได้ด้วยคำสั่งต่อไปนี้:

  • ใช้ Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • ใช้ Homebrew บน macOS และ Linux

    bash
    brew install anomalyco/tap/opencode

    เราขอแนะนำให้ใช้ OpenCode tap เพื่อเผยแพร่ข้อมูลล่าสุด สูตร brew install opencode อย่างเป็นทางการได้รับการดูแลโดยทีมงาน Homebrew และมีการอัปเดตไม่บ่อยนัก

  • ใช้ Paru บน Arch Linux

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[แนะนำ: ใช้ WSL]
เพื่อประสบการณ์ที่ดีที่สุดบน Windows เราขอแนะนำให้ใช้ ระบบย่อย Windows สำหรับ Linux (WSL) ให้ประสิทธิภาพที่ดีขึ้นและความเข้ากันได้เต็มรูปแบบกับคุณสมบัติของ OpenCode
:::

  • ใช้ Chocolatey

    bash
    choco install opencode
  • ใช้ Scoop

    bash
    scoop install opencode
  • การใช้ NPM

    bash
    npm install opencode-ai
  • ใช้ Mise

    bash
    mise use -g github:anomalyco/opencode
  • ใช้ Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

ขณะนี้การสนับสนุนสำหรับการติดตั้ง OpenCode บน Windows โดยใช้ Bun อยู่ระหว่างดำเนินการ

คุณยังสามารถคว้าไบนารี่ได้จาก เผยแพร่


กำหนดค่า

ด้วย OpenCode คุณสามารถใช้ผู้ให้บริการ LLM ใดก็ได้โดยกำหนดค่าคีย์ API

หากคุณยังใหม่ต่อการใช้ผู้ให้บริการ LLM เราขอแนะนำให้ใช้ OpenCode Zen
เป็นรายการโมเดลที่ได้รับการดูแลจัดการซึ่งได้รับการทดสอบและตรวจสอบโดย OpenCode
ทีม.

  1. เรียกใช้คำสั่ง /connect ใน TUI เลือก opencode และไปที่ opencode.ai/auth

    txt
    /connect
  2. ลงชื่อเข้าใช้ เพิ่มรายละเอียดการเรียกเก็บเงินของคุณ และคัดลอกรหัส API ของคุณ

  3. วางคีย์ API ของคุณ

    txt
    ┌ API key
    │
    │
    └ enter

หรือคุณสามารถเลือกหนึ่งในผู้ให้บริการรายอื่นได้ เรียนรู้เพิ่มเติม


เริ่มต้น

เมื่อคุณได้กำหนดค่าผู้ให้บริการแล้ว คุณสามารถนำทางไปยังโปรเจ็กต์นั้นได้
คุณอยากทำงานต่อ

bash
cd /path/to/project

และเรียกใช้ OpenCode

bash
opencode

จากนั้น เริ่มต้น OpenCode สำหรับโปรเจ็กต์โดยการรันคำสั่งต่อไปนี้

bash frame="none"
/init

นี่จะได้รับ OpenCode เพื่อวิเคราะห์โครงการของคุณและสร้างไฟล์ AGENTS.md
รากของโครงการ

:::tip
คุณควรคอมมิตไฟล์ AGENTS.md ของโปรเจ็กต์ของคุณไปที่ Git
:::

ซึ่งจะช่วยให้ OpenCode เข้าใจโครงสร้างโปรเจ็กต์และรูปแบบการเขียนโค้ด
ใช้แล้ว.


การใช้งาน

ตอนนี้คุณพร้อมที่จะใช้ OpenCode เพื่อทำงานในโครงการของคุณแล้ว อย่าลังเลที่จะถามมัน
อะไรก็ตาม!

หากคุณยังใหม่ต่อการใช้เอเจนต์การเข้ารหัส AI ต่อไปนี้คือตัวอย่างบางส่วนที่อาจเป็นไปได้
ช่วย.


ถามคำถาม

คุณสามารถขอให้ OpenCode อธิบาย codebase ให้คุณได้

:::tip
ใช้ปุ่ม @ เพื่อค้นหาไฟล์ในโครงการอย่างคลุมเครือ
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

สิ่งนี้มีประโยชน์หากมีส่วนหนึ่งของโค้ดเบสที่คุณไม่ได้ดำเนินการ


เพิ่มคุณสมบัติ

คุณสามารถขอให้ OpenCode เพิ่มคุณสมบัติใหม่ให้กับโครงการของคุณได้ แม้ว่าเราจะแนะนำให้ขอให้สร้างแผนก่อนก็ตาม

  1. สร้างแผน

    OpenCode มีโหมด Plan ที่ปิดการใช้งานความสามารถในการเปลี่ยนแปลงและ
    แนะนำ how ว่าจะใช้งานฟีเจอร์นี้แทน

    เปลี่ยนไปใช้ปุ่ม Tab คุณจะเห็นตัวบ่งชี้นี้ที่มุมขวาล่าง

    bash frame="none" title="switch to plan mode"
    <TAB>

    ตอนนี้เรามาอธิบายสิ่งที่เราต้องการให้ทำ

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    คุณต้องการให้รายละเอียด OpenCode เพียงพอเพื่อทำความเข้าใจสิ่งที่คุณต้องการ มันช่วยได้
    เพื่อพูดคุยเหมือนคุณกำลังพูดคุยกับนักพัฒนารุ่นน้องในทีมของคุณ

    :::tip
    ให้บริบทและตัวอย่างมากมายแก่ OpenCode เพื่อช่วยให้เข้าใจสิ่งที่คุณ
    ต้องการ.
    :::

  2. ทบทวนแผน

    เมื่อมีแผนแล้ว คุณสามารถให้ข้อเสนอแนะหรือเพิ่มรายละเอียดเพิ่มเติมได้

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    ลากและวางรูปภาพลงใน terminal เพื่อเพิ่มลงในพรอมต์
    :::

    OpenCode สามารถสแกนรูปภาพที่คุณให้มาและเพิ่มลงในข้อความแจ้งได้ คุณสามารถ
    ทำได้โดยลากและวางรูปภาพลงใน terminal

  3. สร้างฟีเจอร์

    เมื่อคุณรู้สึกพอใจกับแผนแล้ว ให้เปลี่ยนกลับเป็น Build mode ภายใน
    กดปุ่ม Tab อีกครั้ง

    bash frame="none"
    <TAB>

    และขอให้ทำการเปลี่ยนแปลง

    bash frame="none"
    Sounds good! Go ahead and make the changes.

ทำการเปลี่ยนแปลง

หากต้องการการเปลี่ยนแปลงที่ตรงไปตรงมามากขึ้น คุณสามารถขอให้ OpenCode สร้างมันโดยตรงได้
โดยไม่ต้องทบทวนแผนก่อน

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

คุณต้องการให้แน่ใจว่าคุณให้รายละเอียดในปริมาณที่เหมาะสมเพื่อให้ OpenCode ดำเนินการได้ถูกต้อง
การเปลี่ยนแปลง


เลิกทำการเปลี่ยนแปลง

สมมติว่าคุณขอให้ OpenCode ทำการเปลี่ยนแปลงบางอย่าง

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

แต่คุณก็รู้ว่ามันไม่ใช่สิ่งที่คุณต้องการ คุณ สามารถยกเลิก การเปลี่ยนแปลงได้
โดยใช้คำสั่ง /undo

bash frame="none"
/undo

OpenCode จะคืนค่าการเปลี่ยนแปลงที่คุณทำและแสดงข้อความต้นฉบับของคุณ
อีกครั้ง.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

จากที่นี่ คุณสามารถปรับแต่งข้อความแจ้งและขอให้ OpenCode ลองอีกครั้ง

:::tip
คุณสามารถเรียกใช้ /undo ได้หลายครั้งเพื่อเลิกทำการเปลี่ยนแปลงหลายรายการ
:::

หรือคุณสามารถ สามารถทำซ้ำ การเปลี่ยนแปลงโดยใช้คำสั่ง /redo

bash frame="none"
/redo

ปรับแต่ง

แค่นั้นแหละ! ตอนนี้คุณเป็นมืออาชีพในการใช้ OpenCode แล้ว

หากต้องการทำให้เป็นของคุณเอง เราขอแนะนำให้ เลือกธีม, ปรับแต่งปุ่มลัด, กำหนดค่าตัวจัดรูปแบบโค้ด, สร้างคำสั่งที่กำหนดเอง หรือลองใช้ การกำหนดค่า OpenCode


Packages Web Src Content Docs Tr Index (`packages/web/src/content/docs/tr/index.mdx`)


title: Giriş

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode açık kaynaklı bir AI kodlama ajanıdır. Terminal tabanlı bir arayüz, masaüstü uygulaması veya IDE uzantısı olarak mevcuttur.

Başlayalım.


Ön koşullar

OpenCode'u terminalinizde kullanmak için ihtiyacınız olacak:

  1. Şu gibi modern bir terminal emülatörü:

  2. Kullanmak istediğiniz LLM sağlayıcılarının API anahtarları.


Kurulum

OpenCode'u kurmanın en kolay yolu kurulum betiğidir.

bash
curl -fsSL https://opencode.ai/install | bash

Ayrıca aşağıdaki komutlarla da yükleyebilirsiniz:

  • Node.js'yi kullanma

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • Homebrew'u macOS ve Linux'ta kullanma

    bash
    brew install anomalyco/tap/opencode

    En güncel sürümler için OpenCode tap'ini kullanmanızı öneririz. Resmi brew install opencode formülü Homebrew ekibi tarafından korunur ve daha sık güncellenir.

  • Paru'yu Arch Linux'ta kullanma

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[Önerilen: WSL kullanın]
Windows'ta en iyi deneyim için Windows Subsystem for Linux (WSL) kullanılmasını öneririz. Daha iyi performans ve OpenCode'un özellikleriyle tam uyumluluğu sağlar.
:::

  • Chocolatey Kullanımı

    bash
    choco install opencode
  • Scoop Kullanımı

    bash
    scoop install opencode
  • NPM kullanarak

    bash
    npm install opencode-ai
  • Mise Kullanımı

    bash
    mise use -g github:anomalyco/opencode
  • Docker'ı kullanma

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

OpenCode'un Bun kullanılarak Windows'a yüklenmesine yönelik destek şu anda devam etmektedir.

İkili dosyayı Releases'dan da alabilirsiniz.


Yapılandırma

OpenCode ile herhangi bir LLM sağlayıcısının API anahtarlarını yapılandırarak kullanabilirsiniz.

LLM sağlayıcılarını kullanmaya yeni başlıyorsanız, OpenCode Zen kullanmanızı öneririz.
OpenCode ekibi tarafından test edilmiş ve doğrulanmış modellerin seçilmiş bir listesidir.

  1. TUI'de /connect komutunu çalıştırın, OpenCode'u seçin ve opencode.ai/auth'ye gidin.

    txt
    /connect
  2. Oturum açın, fatura ayrıntılarınızı ekleyin ve API anahtarınızı kopyalayın.

  3. API anahtarınızı yapıştırın.

    txt
    ┌ API key
    │
    │
    └ enter

Alternatif olarak diğer sağlayıcılardan birini seçebilirsiniz. Daha fazla bilgi.


Başlatma

Artık bir sağlayıcı yapılandırdığınıza göre, üzerinde çalışmak istediğiniz bir projeye gidebilirsiniz.

bash
cd /path/to/project

Ve OpenCode'u çalıştırın.

bash
opencode

Daha sonra aşağıdaki komutu çalıştırarak proje için OpenCode'u başlatın.

bash frame="none"
/init

Bu, OpenCode'un projenizi analiz etmesini ve bir AGENTS.md proje kökünde dosyası oluşturmasını sağlayacaktır.

:::tip
Projenizin AGENTS.md dosyasını Git'e göndermelisiniz.
:::

Bu, OpenCode'un proje yapısını ve kullanılan kodlama kalıplarını anlamasına yardımcı olur.


Kullanım

Artık projeniz üzerinde çalışmak için OpenCode'u kullanmaya hazırsınız. Dilediğiniz soruyu sorabilirsiniz.

AI kodlama ajanını kullanmaya yeniyseniz aşağıdaki örnekler yardımcı olabilir.


Soru Sorma

OpenCode'dan kod tabanını size açıklamasını isteyebilirsiniz.

:::tip
Projedeki dosyaları bulanık aramak için @ tuşunu kullanın.
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

Kod tabanının üzerinde çalışmadığınız bir kısmı varsa bu yararlı olur.


Özellik Ekleme

OpenCode'dan projenize yeni özellikler eklemesini isteyebilirsiniz. Yine de öncelikle ondan bir plan oluşturmasını istemenizi öneririz.

  1. Bir plan oluşturun

    OpenCode, değişiklik yapma özelliğini kapatan bir _Plan modu_\na sahiptir.
    Bu modda, özelliğin nasıl uygulanacağını önerir.

    Tab tuşunu kullanarak buna geçin. Bunun için sağ alt köşede bir gösterge göreceksiniz.

    bash frame="none" title="plan moduna geç"
    <TAB>

    Şimdi ne yapmasını istediğimizi anlatalım.

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    OpenCode'un isteğinizi anlaması için yeterli ayrıntı verin.
    Ekibinizdeki junior bir geliştiriciyle konuşur gibi yazmak genelde iyi sonuç verir.

    :::tip
    OpenCode'a ne istediğinizi anlamasına yardımcı olacak bol miktarda bağlam ve örnek verin.
    :::

  2. Planı yineleyin

    Size bir plan sunduğunda ona geri bildirimde bulunabilir veya daha fazla ayrıntı ekleyebilirsiniz.

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    İsteme eklemek için görüntüleri terminale sürükleyip bırakın.
    :::

    OpenCode verdiğiniz görselleri tarayıp prompt'a ekleyebilir.
    Bunu bir görseli terminale sürükleyip bırakarak yapabilirsiniz.

  3. Özelliği oluşturun

    Planı yeterli bulduğunuzda Tab tuşuna tekrar basarak _Build modu_\na dönün.

    bash frame="none"
    <TAB>

    Ardından değişiklikleri yapmasını isteyin.

    bash frame="none"
    Sounds good! Go ahead and make the changes.

Değişiklik Yapma

Daha basit değişikliklerde, önce planı incelemeden OpenCode'dan doğrudan değişiklik yapmasını isteyebilirsiniz.

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

OpenCode'un doğru değişiklikleri yapması için yeterli ayrıntı verdiğinizden emin olun.


Değişiklikleri Geri Alma

Diyelim ki OpenCode'dan bazı değişiklikler yapmasını istediniz.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Ama istediğinin bu olmadığını anlıyorsun. /undo komutunu kullanarak değişiklikleri geri alabilirsiniz.

bash frame="none"
/undo

OpenCode değişiklikleri geri alır ve orijinal mesajınızı tekrar gösterir.

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

Buradan komut isteminde ince ayar yapabilir ve OpenCode'dan tekrar denemesini isteyebilirsiniz.

:::tip
Birden çok değişikliği geri almak için /undo komutunu birden çok kez çalıştırabilirsiniz.
:::

Veya /redo komutunu kullanarak değişiklikleri yeniden yapabilirsiniz.

bash frame="none"
/redo

Özelleştirme

İşte bu kadar! Artık OpenCode'u kullanma konusunda profesyonelsiniz.

Kendinize göre uyarlamak için tema seçebilir, tuş atamalarını özelleştirebilir, kod biçimlendirici ayarlayabilir, özel komutlar oluşturabilir veya OpenCode config ile oynayabilirsiniz.


Packages Web Src Content Docs Zh Cn Index (`packages/web/src/content/docs/zh-cn/index.mdx`)


title: 简介

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode 是一个开源的 AI 编码代理。它提供终端界面、桌面应用和 IDE 扩展等多种使用方式。

让我们开始吧。


前提条件

要在终端中使用 OpenCode,你需要:

  1. 一款现代终端模拟器,例如:

  2. 你想使用的 LLM 提供商的 API 密钥。


安装

安装 OpenCode 最简单的方法是通过安装脚本。

bash
curl -fsSL https://opencode.ai/install | bash

你也可以使用以下方式安装:

  • 使用 Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • 在 macOS 和 Linux 上使用 Homebrew

    bash
    brew install anomalyco/tap/opencode

    我们推荐使用 OpenCode tap 以获取最新版本。官方的 brew install opencode formula 由 Homebrew 团队维护,更新频率较低。

  • 在 Arch Linux 上安装

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[推荐:使用 WSL]
为了在 Windows 上获得最佳体验,我们推荐使用 Windows Subsystem for Linux (WSL)。它提供更好的性能,并完全兼容 OpenCode 的所有功能。
:::

  • 使用 Chocolatey

    bash
    choco install opencode
  • 使用 Scoop

    bash
    scoop install opencode
  • 使用 NPM

    bash
    npm install opencode-ai
  • 使用 Mise

    bash
    mise use -g github:anomalyco/opencode
  • 使用 Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

在 Windows 上通过 Bun 安装 OpenCode 的支持目前正在开发中。

你也可以从 Releases 页面直接下载二进制文件。


配置

通过 OpenCode,你可以配置 API 密钥来使用任意 LLM 提供商。

如果你刚开始接触 LLM 提供商,我们推荐使用 OpenCode Zen。这是一组经过 OpenCode 团队测试和验证的精选模型。

  1. 在 TUI 中运行 /connect 命令,选择 opencode,然后前往 opencode.ai/auth。

    txt
    /connect
  2. 登录并添加账单信息,然后复制你的 API 密钥。

  3. 粘贴你的 API 密钥。

    txt
    ┌ API key
    │
    │
    └ enter

你也可以选择其他提供商。了解更多。


初始化

配置好提供商后,导航到你想要处理的项目目录。

bash
cd /path/to/project

然后运行 OpenCode。

bash
opencode

接下来,运行以下命令为项目初始化 OpenCode。

bash frame="none"
/init

OpenCode 会分析你的项目并在项目根目录创建一个 AGENTS.md 文件。

:::tip
你应该将项目的 AGENTS.md 文件提交到 Git。
:::

这有助于 OpenCode 理解项目结构和编码规范。


使用

现在你已经准备好使用 OpenCode 来处理项目了,尽管提问吧!

如果你是第一次使用 AI 编码代理,以下示例可能会对你有所帮助。


提问

你可以让 OpenCode 为你讲解代码库。

:::tip
使用 @ 键可以模糊搜索项目中的文件。
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

当你遇到不熟悉的代码时,这个功能非常有用。


添加功能

你可以让 OpenCode 为项目添加新功能。不过我们建议先让它制定一个计划。

  1. 制定计划

    OpenCode 有一个计划模式,该模式下它不会进行任何修改,而是建议如何实现该功能。

    使用 Tab 键切换到计划模式。你会在右下角看到模式指示器。

    bash frame="none" title="switch to plan mode"
    <TAB>

    接下来描述你希望它做什么。

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    你需要提供足够的细节,让 OpenCode 理解你的需求。可以把它当作团队中的一名初级开发者来沟通。

    :::tip
    为 OpenCode 提供充足的上下文和示例,帮助它理解你的需求。
    :::

  2. 迭代计划

    当它给出计划后,你可以提供反馈或补充更多细节。

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    将图片拖放到终端中即可将其添加到提示词中。
    :::

    OpenCode 可以扫描你提供的图片并将其添加到提示词中。只需将图片拖放到终端窗口即可。

  3. 构建功能

    当你对计划满意后,再次按 Tab 键切换回构建模式。

    bash frame="none"
    <TAB>

    然后让它开始实施。

    bash frame="none"
    Sounds good! Go ahead and make the changes.

直接修改

对于比较简单的修改,你可以直接让 OpenCode 实施,无需先审查计划。

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

请确保提供足够的细节,以便 OpenCode 做出正确的修改。


撤销修改

假设你让 OpenCode 做了一些修改。

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

但你发现结果不是你想要的。你可以使用 /undo 命令来撤销修改。

bash frame="none"
/undo

OpenCode 会还原所做的修改,并重新显示你之前的消息。

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

你可以调整提示词,让 OpenCode 重新尝试。

:::tip
你可以多次运行 /undo 来撤销多次修改。
:::

你也可以使用 /redo 命令来重做修改。

bash frame="none"
/redo

个性化

以上就是全部内容!你现在已经是 OpenCode 的使用高手了。

要让它更符合你的习惯,我们推荐选择一个主题、自定义快捷键、配置代码格式化工具、创建自定义命令,或者探索 OpenCode 配置。


Packages Web Src Content Docs Zh Tw Index (`packages/web/src/content/docs/zh-tw/index.mdx`)


title: 簡介

import { Tabs, TabItem } from "@astrojs/starlight/components"
import config from "../../../../config.mjs"
export const console = config.console

OpenCode 是一個開源的 AI 編碼代理。它提供終端機介面、桌面應用程式和 IDE 擴充功能等多種使用方式。

讓我們開始吧。


前提條件

要在終端機中使用 OpenCode,您需要:

  1. 一款現代終端機模擬器,例如:

  2. 您想使用的 LLM 供應商的 API 金鑰。


安裝

安裝 OpenCode 最簡單的方法是透過安裝指令碼。

bash
curl -fsSL https://opencode.ai/install | bash

您也可以使用以下方式安裝:

  • 使用 Node.js

    text
    <Tabs>
    
    <TabItem label="npm">
    ```bash
    npm install opencode-ai
    ```
    
        </TabItem>
    
      <TabItem label="Bun">
      ```bash
      bun install -g opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="pnpm">
      ```bash
      pnpm install opencode-ai
      ```
    
        </TabItem>
    
      <TabItem label="Yarn">
      ```bash
      yarn global add opencode-ai
      ```
    
    </TabItem>
  • 在 macOS 和 Linux 上使用 Homebrew

    bash
    brew install anomalyco/tap/opencode

    我們推薦使用 OpenCode tap 以取得最新版本。官方的 brew install opencode formula 由 Homebrew 團隊維護,更新頻率較低。

  • 在 Arch Linux 上安裝

    bash
    sudo pacman -S opencode           # Arch Linux (Stable)
    paru -S opencode-bin              # Arch Linux (Latest from AUR)

Windows

:::tip[推薦:使用 WSL]
為了在 Windows 上獲得最佳體驗,我們推薦使用 Windows Subsystem for Linux (WSL)。它提供更好的效能,並完全相容 OpenCode 的所有功能。
:::

  • 使用 Chocolatey

    bash
    choco install opencode
  • 使用 Scoop

    bash
    scoop install opencode
  • 使用 NPM

    bash
    npm install opencode-ai
  • 使用 Mise

    bash
    mise use -g github:anomalyco/opencode
  • 使用 Docker

    bash
    docker run -it --rm ghcr.io/anomalyco/opencode

在 Windows 上透過 Bun 安裝 OpenCode 的支援目前正在開發中。

您也可以從 Releases 頁面直接下載二進位檔案。


設定

透過 OpenCode,您可以設定 API 金鑰來使用任意 LLM 供應商。

如果您剛開始接觸 LLM 供應商,我們推薦使用 OpenCode Zen。這是一組經過 OpenCode 團隊測試和驗證的精選模型。

  1. 在 TUI 中執行 /connect 指令,選擇 opencode,然後前往 opencode.ai/auth。

    txt
    /connect
  2. 登入並新增帳單資訊,然後複製您的 API 金鑰。

  3. 貼上您的 API 金鑰。

    txt
    ┌ API key
    │
    │
    └ enter

您也可以選擇其他供應商。了解更多。


初始化

設定好供應商後,導覽到您想要處理的專案目錄。

bash
cd /path/to/project

然後執行 OpenCode。

bash
opencode

接下來,執行以下指令為專案初始化 OpenCode。

bash frame="none"
/init

OpenCode 會分析您的專案並在專案根目錄建立一個 AGENTS.md 檔案。

:::tip
您應該將專案的 AGENTS.md 檔案提交到 Git。
:::

這有助於 OpenCode 理解專案結構和編碼規範。


使用

現在您已經準備好使用 OpenCode 來處理專案了,儘管提問吧!

如果您是第一次使用 AI 編碼代理,以下範例可能會對您有所幫助。


提問

您可以讓 OpenCode 為您講解程式碼庫。

:::tip
使用 @ 鍵可以模糊搜尋專案中的檔案。
:::

txt frame="none" "@packages/functions/src/api/index.ts"
How is authentication handled in @packages/functions/src/api/index.ts

當您遇到不熟悉的程式碼時,這個功能非常有用。


新增功能

您可以讓 OpenCode 為專案新增新功能。不過我們建議先讓它制定一個計畫。

  1. 制定計畫

    OpenCode 有一個計畫模式,該模式下它不會進行任何修改,而是建議如何實作該功能。

    使用 Tab 鍵切換到計畫模式。您會在右下角看到模式指示器。

    bash frame="none" title="switch to plan mode"
    <TAB>

    接下來描述您希望它做什麼。

    txt frame="none"
    When a user deletes a note, we'd like to flag it as deleted in the database.
    Then create a screen that shows all the recently deleted notes.
    From this screen, the user can undelete a note or permanently delete it.

    您需要提供足夠的細節,讓 OpenCode 理解您的需求。可以把它當作團隊中的一名初級開發者來溝通。

    :::tip
    為 OpenCode 提供充足的上下文和範例,幫助它理解您的需求。
    :::

  2. 迭代計畫

    當它給出計畫後,您可以提供回饋或補充更多細節。

    txt frame="none"
    We'd like to design this new screen using a design I've used before.
    [Image #1] Take a look at this image and use it as a reference.

    :::tip
    將圖片拖放到終端機中即可將其新增到提示詞中。
    :::

    OpenCode 可以掃描您提供的圖片並將其新增到提示詞中。只需將圖片拖放到終端機視窗即可。

  3. 建置功能

    當您對計畫滿意後,再次按 Tab 鍵切換回建置模式。

    bash frame="none"
    <TAB>

    然後讓它開始實施。

    bash frame="none"
    Sounds good! Go ahead and make the changes.

直接修改

對於比較簡單的修改,您可以直接讓 OpenCode 實施,無需先審查計畫。

txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts"
We need to add authentication to the /settings route. Take a look at how this is
handled in the /notes route in @packages/functions/src/notes.ts and implement
the same logic in @packages/functions/src/settings.ts

請確保提供足夠的細節,以便 OpenCode 做出正確的修改。


復原修改

假設您讓 OpenCode 做了一些修改。

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

但您發現結果不是您想要的。您可以使用 /undo 指令來復原修改。

bash frame="none"
/undo

OpenCode 會還原所做的修改,並重新顯示您之前的訊息。

txt frame="none" "@packages/functions/src/api/index.ts"
Can you refactor the function in @packages/functions/src/api/index.ts?

您可以調整提示詞,讓 OpenCode 重新嘗試。

:::tip
您可以多次執行 /undo 來復原多次修改。
:::

您也可以使用 /redo 指令來重做修改。

bash frame="none"
/redo

個人化

以上就是全部內容!您現在已經是 OpenCode 的使用高手了。

要讓它更符合您的習慣,我們推薦選擇一個主題、自訂快捷鍵、設定程式碼格式化器、建立自訂指令,或者探索 OpenCode 設定。


Services Www Src Docs Content Build Index (`services/www/src/docs/content/build/index.mdx`)


title: "Intro"

OpenCode is used by millions every day. Build on top of it to create your own
applications, integrations, and agent experiences without starting from
scratch.

We also offer Effect APIs for plugins,
clients, and embedded apps.

Build plugins that add tools, integrations, commands, agents, and custom behavior while keeping the rest of OpenCode intact. Connect to OpenCode with the same client used by the TUI and desktop app, then build any interface, workflow, or agent experience around it. Embed OpenCode directly into your application and build a completely custom agent, interface, or developer product around it.

Services Www Src Docs Content Cli Index (`services/www/src/docs/content/cli/index.mdx`)


title: "Intro"

Run the CLI in a project to open the full-screen terminal interface:

bash
opencode

Pass a directory to work in a different project:

bash
opencode ~/code/my-project

Suggested terminals:

Truecolor support gives themes their most accurate colors; terminals without it use an approximation of the available
palette.

Automation

Use opencode run to submit a prompt without opening the interactive interface. It is designed for scripts, CI jobs, and
other workflows that need model output directly in the terminal.

bash
opencode run "Explain this repository"

Mini

Use opencode mini to start OpenCode's minimal interactive interface instead of the full-screen TUI.

bash
opencode mini

Run opencode mini --help to see its session, model, agent, prompt, and replay options.

Background service

By default, OpenCode discovers or starts one shared background server for your user account. Every local OpenCode client
connects to that server, which owns sessions, configuration, integrations, permissions, and tool execution.

Use --standalone to run with a private server, or --server to connect to a specific server URL:

bash
opencode --standalone
opencode --server http://localhost:4096

To make private servers the default for CLI commands instead of starting the shared service, disable it:

bash
opencode service set disabled true
opencode

This stops the running background service. --server still connects to an explicitly selected server; opencode service start
can still start the shared service explicitly. To return to automatic service use, run opencode service unset disabled.
Pairing requires the shared service and is unavailable while it is disabled.

See Troubleshooting for shared service diagnostics and the API reference for server endpoints.

Paths

Print a specific local path for use with other tools:

bash
opencode debug paths db
sqlite3 "$(opencode debug paths db)"

The optional selector accepts db, home, data, config, cache, state, tmp, bin, log, or repos and prints
only the path and a newline. The database path respects the release channel and OPENCODE_DB; relative database overrides
resolve under the data directory, and :memory: is printed as-is. This command does not start a server or open the database.

Omit the selector to show all paths with labels:

bash
opencode debug paths

Uninstall

Preview the files and installation that will be removed:

bash
opencode uninstall --dry-run

Run opencode uninstall to confirm removal. OpenCode stops registered background services and persistent terminals before
removing the global cache directory, which is shared by OpenCode versions and channels. Session data, configuration, and
state are never removed.

  • --force (-f) skips confirmation; use it for noninteractive removal.
  • Package-manager installations use the detected package manager. Curl installations print the final command to remove
    the executable manually.

Services Www Src Docs Content Console Index (`services/www/src/docs/content/console/index.mdx`)


title: "Intro"

The OpenCode Console is an optional service that provides additional benefits to
using OpenCode, on your own or as a team.

  • Workspaces for sharing access with your team
  • Inference for both proprietary and open source models
  • Providers for connecting your own provider accounts through the Console gateway
  • Usage tracking and budget controls
  • Deploy team wide policies to control OpenCode behavior
  • Web search
  • Harnesses for using Console models from Claude Code, Codex, and other agents
  • OpenCode Go and Go Plus, $10 and $40 monthly subscriptions for open source model access

Get started

You don't need a team to use the Console. Every account starts with a Personal workspace where you are the only
member.

  1. Sign in to the Console.
  2. Subscribe to Go, add credits, or connect a provider.
  3. Run /connect in OpenCode and choose the workspace.
  4. Optionally, invite your team.
text
/connect

Policies

Providers and Tools rules from the Policies page apply to every OpenCode V2 client
connected to the workspace. They are delivered as policy
statements with final authority over the member's own configuration and take effect
within about a minute.


Services Www Src Docs Content Build Client Index (`services/www/src/docs/content/build/client/index.mdx`)


title: "JavaScript"

@opencode/client is the TypeScript client for the OpenCode HTTP
API. Use it when your application connects to an OpenCode server over the
network. Its native types and methods are generated from the same contract as the
API reference. Plugin RPC types come from imported RPC definitions.

Install

sh
bun add @opencode/client

Create a client

Create a client with the server URL, then call methods grouped by API resource:

ts
import { OpenCode } from "@opencode/client"

const client = OpenCode.make({
  baseUrl: "http://localhost:4096",
})

const session = await client.session.create({
  location: { directory: "/workspace" },
})

await client.session.prompt({
  sessionID: session.id,
  text: "Review the current changes",
})

Headers and requests

Pass default authentication or application headers to OpenCode.make with
headers. You can also supply a custom fetch implementation. Each operation
accepts request options as its final argument for an AbortSignal or
per-request headers. Event subscriptions are the exception: they accept only
subscriber-local cancellation and use the base client's headers.

ts
const client = OpenCode.make({
  baseUrl: "https://opencode.example.com",
  headers: {
    authorization: `Bearer ${process.env.OPENCODE_TOKEN}`,
  },
})

await client.session.list(undefined, {
  signal: AbortSignal.timeout(10_000),
})

Stream events

Streaming endpoints return async iterables:

ts
for await (const event of client.event.subscribe()) {
  console.log(event.type)
}

Native and RPC event subscribers share one lazy connection per client. Client,
handle, and iterable creation open no event connection; consumption starts it.
Breaking iteration or aborting a subscriber ends only that iterator. The last
subscriber leaving closes the connection. The shared source waits for active
subscribers to accept each event; consumers should buffer before performing slow work.

Subscriptions are live-only, with no replay or automatic reconnection. A source
failure ends current subscriptions; subscribe again after recovery. A late native
subscriber receives the current server.connected marker, not past business events.

Plugin RPC

Import a plugin's shared contract and pass it to client.rpc:

ts
import { OpenCode } from "@opencode/client"
import { Acme } from "opencode-acme-plugin/rpc"

const acme = client.rpc(Acme)
const result = await acme.search(
  { query: "hello" },
  { location: { directory: "/workspace" }, signal: AbortSignal.timeout(10_000) },
)

const unsubscribe = acme.events.on("updated", (event) => {
  console.log(event.type, event.location.directory, event.data.text)
})

The second optional method argument holds location, signal, and headers,
separate from the plugin-defined input. Omitted location follows native request
defaults: base location headers, then the server's working directory. No location
is selected when constructing the subclient.

Methods infer arguments and results from the definition. Schema parsing belongs
to the contract boundary; callers send the accepted input representation, while
handlers receive parsed values. The Promise client accepts Standard Schema or
plain JSON Schema definitions and does
not run schema parsers locally: the server returns already parsed and transformed
output. Effect Schema definitions require the Effect client.

Declared method errors reject like errors from other Promise client endpoints,
and caught errors remain untyped. Generic HTTP RPC error wrappers are removed by
the typed subclient. Reserved rpc.* framework failures remain plain RPC failures,
while unrelated authentication, transport, and protocol errors keep their normal
client representations.

RPC subscriptions use local names and receive that RPC's events across all
locations. Inspect the required event.location to filter them. events.subscribe
matches the native async iterable API:

ts
for await (const event of acme.events.subscribe("updated")) {
  console.log(event.data.text)
}

events.on is a convenience wrapper over the same source. It returns unsubscribe;
async callbacks are awaited sequentially. Callback or source failures are logged
and end that listener. Native and typed subscriptions receive the same normal
rpc.<rpcID>.<event> envelope with direct object event data. Live subscriptions
do not replay missed events.

The server plugin must be configured and implement the RPC; importing a
definition does not register it. See plugin RPC for the
definition and registration API. Any HTTP client can also invoke the generic
POST /api/rpc/{rpcID}/{method} route with { "input": ... } and receive
{ "output": ... }. Omitted input/output fields represent no value.

Local background service

The main client entrypoints are browser-compatible and do not include local
process management. In a Node application, import the native Promise service
API from @opencode/client/service.

  • Service.discover() returns a healthy registered endpoint without starting
    a process.
  • Service.ensure() returns a compatible service, starting one when needed.
  • Service.stop() stops the exact registered service instance.
  • Service.headers(endpoint) creates the authentication headers for a client.
ts
import { OpenCode } from "@opencode/client"
import { Service } from "@opencode/client/service"

const endpoint = await Service.ensure()
const client = OpenCode.make({
  baseUrl: endpoint.url,
  headers: Service.headers(endpoint),
})

const info = await client.server.info()

Service.ensure() accepts an optional registration file, version, service
command, and onStart callback. version accepts either an exact value or a
compatibility predicate:

ts
const endpoint = await Service.ensure({
  file: "/var/run/opencode/service.json",
  version: (version) => version.startsWith("2."),
  command: ["opencode", "serve", "--service"],
  onStart(reason, previousVersion) {
    console.log(reason, previousVersion)
  },
})

Omit these options to use the standard registration path and
opencode serve --service command.


Services Www Src Docs Content Build Plugins Index (`services/www/src/docs/content/build/plugins/index.mdx`)


title: "Overview"

Plugins can modify OpenCode's behavior and add new features. To change the terminal UI, build a CLI
plugin
.

Migrating an existing OpenCode 1 plugin? Follow the V1 plugin migration guide.

ts title=".opencode/plugins/example/index.ts"
import { Plugin } from "@opencode/plugin"

export default Plugin.define({
  id: "example",
  async setup(ctx) {
    await ctx.storage.set("loaded", true)
  },
})

Plugins under .opencode/plugins/ are loaded automatically, like the local example above. To load published packages
or plugin directories from other locations, add them to plugins in opencode.json(c):

jsonc title="opencode.jsonc"
{
  "$schema": "https://opencode.ai/config.json",
  "plugins": [
    "opencode-acme-plugin",
    "[email protected]",
    "@acme/opencode-plugin",
    "./plugins/local",
    "../shared/plugin",
    "/absolute/path/plugin",
    "file:///home/me/plugins/local",
    {
      "package": "@acme/opencode-plugin",
      "options": {
        "agent": "reviewer",
        "strict": true,
      },
    },
  ],
}

See Configure plugins for more loading and configuration options.

Lifecycle

setup runs when the plugin loads. It may return a cleanup function that runs when the plugin unloads.

ts
import { Plugin } from "@opencode/plugin"

export default Plugin.define({
  id: "example",
  setup(ctx) {
    console.log(`loaded in OpenCode ${ctx.app.version}`)
    return () => console.log("unloaded")
  },
})

Context

The plugin context is essentially an OpenCode server client.
Its read and action methods use the same inputs and responses as the client. It
adds plugin-only methods for transforms, runtime hooks, reloads, registrations,
and plugin options.

ts
setup(ctx) {
  console.log(ctx.app.version)
}

ctx.location describes the location where this plugin instance is loaded. It
includes directory, optional workspaceID, and project metadata (id,
directory, and canonical). It is available in both Promise and Effect plugins.
This is the plugin instance's location, not the location of every session it can
access or event it receives.

ts
setup(ctx) {
  console.log(ctx.location.directory)
  console.log(ctx.location.project.canonical)
}

Options

Pass plugin options with the object form in opencode.json(c).

jsonc title="opencode.jsonc"
{
  "plugins": [
    {
      "package": "./plugins/company",
      "options": {
        "strict": true,
      },
    },
  ],
}

Read those values from ctx.options during setup.

ts title="plugins/company/index.ts"
import { Plugin } from "@opencode/plugin"

export default Plugin.define({
  id: "company",
  setup(ctx) {
    const strict = ctx.options.strict === true
  },
})

Transforms

Transforms are synchronous edits to OpenCode's domain state, and each builds on earlier registrations in its domain.
Registry reads such as ctx.model.list() reflect every registration so far, including during plugin setup;
startup batching only coalesces update notifications and never delays what a read returns. Resource status APIs still
report the state of running resources: a registered definition does not mean its connection or other resource work has
completed.

Sources contribute providers and immutable model definitions through ctx.provider.transform.

ts title="plugins/models/index.ts"
import { Model, Plugin, Provider } from "@opencode/plugin"

export default Plugin.define({
  id: "company.models",
  async setup(ctx) {
    const providerID = Provider.ID.make("acme")
    const models = [{ ...Model.Info.default(providerID, Model.ID.make("reasoner")), name: "Acme Reasoner" }]
    await ctx.provider.transform((editor) => {
      editor.add({
        info: {
          ...Provider.Info.empty(providerID),
          name: "Acme",
          activation: "enabled",
          package: "@opencode/ai/providers/openai-compatible",
          settings: { baseURL: "http://127.0.0.1:8000/v1" },
        },
        models,
      })
    })

    const available = await ctx.model.list()
  },
})

Any registration, removal, or reload() marks the registry changed; the next read rebuilds it by replaying every
active transform in registration order onto a fresh value. Keep transforms cheap and repeatable. A value you have
already read is never modified by later rebuilds.

After provider transforms and availability are resolved, OpenCode materializes the active providers' models and replays
every model transform in order. A model policy can inspect the whole candidate collection, including newly refreshed
sources.

ts title="plugins/model-budget/index.ts"
import { Plugin } from "@opencode/plugin"

export default Plugin.define({
  id: "company.model-budget",
  async setup(ctx) {
    await ctx.model.transform((editor) => {
      editor
        .list()
        .filter((model) => model.cost.some((tier) => tier.output > 20))
        .forEach((model) => {
          editor.remove(model.providerID, model.id)
        })
    })
  },
})

Captured inputs are not watched automatically. Load external data before the synchronous callback, then call
reload() after those inputs change. Here, loadFromSource() returns
{ info: Provider.Info, models: readonly Model.Info[] } entries.

ts title="plugins/models/index.ts"
import { Plugin } from "@opencode/plugin"

export default Plugin.define({
  id: "company.models",
  async setup(ctx) {
    const source = { providers: await loadFromSource() }

    await ctx.provider.transform((editor) => {
      source.providers.forEach((provider) => editor.add(provider))
    })

    const refresh = async () => {
      source.providers = await loadFromSource()
      await ctx.provider.reload()
    }

    const timer = setInterval(() => void refresh().catch(console.error), 60_000)
    return () => clearInterval(timer)
  },
})

Provider changes invalidate the whole active model result, so the output-price policy still filters the refreshed models.
Use ctx.model.reload() when only an input captured by a model transform changes.

API

Agent

Read all agents or fetch one by ID.

ts
const agents = await ctx.agent.list()
const build = await ctx.agent.get({ agentID: "build" })

Register a transform to inspect, update, remove, or select the default agent.

ts
await ctx.agent.transform((editor) => {
  const agents = editor.list()
  const build = editor.get("build")

  editor.default("build")
  editor.update("build", (agent) => {
    agent.description = "Builds features and fixes bugs"
  })
  editor.remove("legacy")
})

Reload agents after external state used by a transform changes.

ts
await ctx.agent.reload()

Reference

Schema: Agent.Info

ts
interface AgentContext {
  list(input?: AgentListInput, requestOptions?: RequestOptions): Promise<AgentListOutput>
  get(input: AgentGetInput, requestOptions?: RequestOptions): Promise<AgentGetOutput>
  transform(callback: (editor: AgentEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface AgentEditor {
  list(): readonly AgentInfo[]
  get(id: string): AgentInfo | undefined
  default(id: string | undefined): void
  update(id: string, update: (agent: AgentInfo) => void): void
  remove(id: string): void
}

interface Registration {
  dispose(): Promise<void>
}

Providers

Read available providers or inspect one provider's metadata by ID.

ts
const providers = await ctx.provider.list()
const provider = await ctx.provider.get({ providerID: "anthropic" })

Provider transforms edit provider settings and source definitions. Editor reads include inactive providers and expose
immutable definitions; models.update edits an owned copy of a source model.

ts
await ctx.provider.transform((editor) => {
  editor.update("anthropic", (provider) => {
    provider.headers = { ...provider.headers, "x-company": "engineering" }
  })
  editor.models.update("anthropic", "claude-sonnet-4-5", (model) => {
    model.name = "Team Sonnet"
  })
  editor.models.remove("anthropic", "legacy-model")
  editor.remove("legacy-provider")
})

Replace a provider's source inventory with models.set, then reload after the captured definitions change.

ts
const source = { models: await loadModels() }
await ctx.provider.transform((editor) => {
  editor.models.set("acme", source.models)
})

source.models = await loadModels()
await ctx.provider.reload()

For account-specific discovery, pass the connection used to load the inventory as sourceConnection. OpenCode excludes
that provider while another connection is selected, until your plugin publishes its refreshed inventory.

ts
const connection = await ctx.integration.connection.active("acme")
if (!connection) return
const inventory = await loadInventory(connection)
await ctx.provider.transform((editor) => {
  editor.add({ info: inventory.provider, models: inventory.models, sourceConnection: connection })
})

Reference

Schemas: Provider.Info, Model.Info

ts
interface ProviderDomain extends ProviderApi {
  transform(callback: (editor: ProviderEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface ProviderRecord {
  readonly provider: Provider.Info
  readonly models: ReadonlyMap<string, Model.Info>
  readonly sourceConnection?: ConnectionInfo
}

interface ProviderEditor {
  list(): readonly ProviderRecord[]
  get(providerID: string): ProviderRecord | undefined
  add(input: { info: Provider.Info; models: readonly Model.Info[]; sourceConnection?: ConnectionInfo }): void
  update(providerID: string, update: (provider: DeepMutable<Provider.Info>) => void): void
  remove(providerID: string): void
  readonly models: {
    set(providerID: string, models: readonly Model.Info[]): void
    update(providerID: string, modelID: string, update: (model: DeepMutable<Model.Info>) => void): void
    remove(providerID: string, modelID: string): void
  }
}

Models

Read available models and the default selection.

ts
const models = await ctx.model.list()
const selected = await ctx.model.default()

Model transforms edit the entire active-provider candidate collection. Disabled candidates remain editable until all
transforms finish; update can add a model only under an available provider.

ts
await ctx.model.transform((editor) => {
  editor.list("anthropic").forEach((model) => {
    editor.update(model.providerID, model.id, (draft) => {
      draft.enabled = draft.capabilities.tools
    })
  })
  editor.default.set("anthropic", "claude-sonnet-4-5")
  editor.remove("anthropic", "legacy-model")
})

Callbacks edit raw model overrides. Provider defaults are merged once when OpenCode commits the result; unchanged reads
reuse that result. editor.provider exposes immutable source definitions, including inactive templates, rather than
model-transform output.

ts
await ctx.model.transform((editor) => {
  const source = editor.provider.get("anthropic")?.models.get("claude-sonnet-4-5")
  if (!source) return
  editor.update("anthropic", source.id, (model) => {
    model.limit.context = Math.min(model.limit.context, source.limit.context)
  })
})

await ctx.model.reload()

Reference

Schema: Model.Info

ts
interface ModelDomain extends ModelApi {
  transform(callback: (editor: ModelEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface ModelEditor {
  list(providerID?: string): readonly DeepMutable<Model.Info>[]
  get(providerID: string, modelID: string): DeepMutable<Model.Info> | undefined
  update(providerID: string, modelID: string, update: (model: DeepMutable<Model.Info>) => void): void
  remove(providerID: string, modelID: string): void
  readonly default: {
    get(): { providerID: string; modelID: string } | undefined
    set(providerID: string, modelID: string): void
  }
  readonly provider: {
    list(): readonly ProviderRecord[]
    get(providerID: string): ProviderRecord | undefined
  }
}

Commands

Read the commands available at a location.

ts
const commands = await ctx.command.list()

Register commands with a transform. The executor receives the session, prompt attachments, and requested delivery mode.

ts
await ctx.command.transform((editor) => {
  editor.add({
    name: "security-review",
    description: "Review changes for security issues",
    execute: async ({ sessionID, prompt, delivery }) => {
      await ctx.session.prompt({
        ...prompt,
        sessionID,
        text: `Review these changes for security issues.\n\n${prompt.text}`,
        delivery,
      })
    },
  })
})

Reload commands after external state used by a transform changes.

ts
await ctx.command.reload()

Reference

Schemas: Command.Info,
Session.Inbox.Delivery

ts
interface CommandContext {
  list(input?: CommandListInput, requestOptions?: RequestOptions): Promise<CommandListOutput>
  transform(callback: (editor: CommandEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface CommandEditor {
  add(definition: CommandDefinition): void
}

interface CommandDefinition {
  name: string
  description?: string
  execute(input: CommandInvocation): Promise<void>
}

interface CommandInvocation {
  sessionID: string
  prompt: PromptInput
  delivery: "steer" | "queue"
}

Integrations

Read integrations and inspect active credentials.

ts
const integrations = await ctx.integration.list()
const github = await ctx.integration.get({ integrationID: "github" })
const connection = await ctx.integration.connection.active("github")
const credential = connection ? await ctx.integration.connection.resolve(connection) : undefined

Connect integrations with an API key.

ts
await ctx.integration.connect.key({
  integrationID: "github",
  key: process.env.GITHUB_TOKEN!,
})

Start, inspect, complete, or cancel an OAuth connection attempt.

ts
const attempt = await ctx.integration.oauth.connect({ integrationID: "github", methodID: "oauth" })
const status = await ctx.integration.oauth.status({ integrationID: "github", attemptID: attempt.data.attemptID })
await ctx.integration.oauth.complete({ integrationID: "github", attemptID: attempt.data.attemptID, code })
await ctx.integration.oauth.cancel({ integrationID: "github", attemptID: attempt.data.attemptID })

Command-based connections expose the same start, status, and cancel flow.

ts
const attempt = await ctx.integration.command.connect({ integrationID: "acme", methodID: "cli" })
const status = await ctx.integration.command.status({ integrationID: "acme", attemptID: attempt.data.attemptID })
await ctx.integration.command.cancel({ integrationID: "acme", attemptID: attempt.data.attemptID })

Register a transform to inspect integrations and manage their authentication methods.

ts
await ctx.integration.transform((editor) => {
  const integrations = editor.list()
  const acme = editor.get("acme")

  editor.update("acme", (integration) => {
    integration.name = "Acme"
  })
  editor.method.update({
    integrationID: "acme",
    method: { id: "cli", type: "command", label: "Sign in with Acme CLI", command: ["acme", "login"] },
  })

  const methods = editor.method.list("acme")
  const legacy = methods.find((method) => method.type === "command" && method.id === "legacy")
  if (legacy) editor.method.remove("acme", legacy)
  editor.remove("legacy")
})

Reload integrations after external state used by a transform changes.

ts
await ctx.integration.reload()

Reference

Schemas: Integration.Info, Integration.Method,
Connection.Info, Form.Answer

text
/* Detailed source-code truncated for AI context efficiency. */

Credentials

Make a saved credential the active one for its integration.

ts
await ctx.credential.activate({ credentialID })

Reference

ts
interface CredentialContext {
  activate(input: CredentialActivateInput, requestOptions?: RequestOptions): Promise<void>
}

MCP

List MCP servers and their current connection state.

ts
const servers = await ctx.mcp.list()

Plugins manage MCP servers only through transforms. Use editor.set to add or replace a server, editor.update to
change its configuration, and editor.remove to remove it. Inspect configuration with editor.list and editor.get.

ts
await ctx.mcp.transform((editor) => {
  const servers = editor.list()
  const docs = editor.get("docs")
  editor.set("docs", { type: "remote", url: "https://mcp.example.com" })
  editor.update("docs", (server) => {
    server.disabled = false
  })
  editor.remove("legacy")
})

Set disabled: true in a transform to disable a server and disconnect it, or disabled: false to enable it and allow
OpenCode to connect. OpenCode reconciles server lifecycle from the transformed configuration.

Call reload() after external state used by a transform changes to reapply transforms and reconcile the servers.

ts
await ctx.mcp.reload()

Reference

Schemas: Mcp.Server, Mcp.LocalConfigEncoded,
Mcp.RemoteConfigEncoded

ts
interface MCPContext {
  list(input?: McpListInput, requestOptions?: RequestOptions): Promise<McpListOutput>
  transform(callback: (editor: MCPEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface MCPEditor {
  list(): readonly (readonly [string, McpServerConfig])[]
  get(name: string): McpServerConfig | undefined
  set(name: string, config: McpServerConfig): void
  update(name: string, update: (config: McpServerConfig) => void): void
  remove(name: string): void
}

Plugins

List the plugins currently active for a location.

ts
const plugins = await ctx.plugin.list()

Reference

Schemas: Plugin.Info, Plugin.Source

ts
interface PluginContext {
  list(input?: PluginListInput, requestOptions?: RequestOptions): Promise<PluginListOutput>
}

References

Read the references available at a location.

ts
const references = await ctx.reference.list()

Register a transform to inspect, add, or remove local and Git references. get(name) returns the current configured source,
or undefined when the name is absent.

ts
await ctx.reference.transform((editor) => {
  const references = editor.list()
  editor.add("handbook", { type: "local", path: "/workspace/docs/handbook" })
  editor.add("standards", { type: "git", repository: "https://github.com/acme/standards", branch: "main" })
  const handbook = editor.get("handbook")
  editor.remove("legacy")
})

Reload references after external state used by a transform changes.

ts
await ctx.reference.reload()

Reference

Schemas: Reference.Info, Reference.LocalSource,
Reference.GitSource

ts
interface ReferenceContext {
  list(input?: ReferenceListInput, requestOptions?: RequestOptions): Promise<ReferenceListOutput>
  transform(callback: (editor: ReferenceEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface ReferenceEditor {
  list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
  get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
  add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
  remove(name: string): void
}

Generate

Generate text with a selected model without creating a session, invoking tools, or adding to session history.

ts
const review = await ctx.generate.text({
  model: { providerID: "anthropic", id: "claude-sonnet-4-6" },
  prompt: "Review this proposed action.",
})

Permissions

Ask for permission before performing an action. assert evaluates the session's permission rules,
including saved approvals, and prompts the user when a rule resolves to ask. It resolves once the action is allowed.

ts
execute: async (input, context) => {
  await ctx.permission.assert({
    sessionID: context.sessionID,
    agent: context.agent,
    source: { type: "tool", messageID: context.messageID, id: context.id },
    action: "deploy",
    resources: [input.environment],
    save: [input.environment],
  })
  return { content: await deploy(input.environment) }
}
  • action and resources are matched against the rules. Any deny blocks the action; otherwise any ask prompts.
  • save lists the patterns stored when the user chooses to always allow.
  • agent selects whose rules apply and defaults to the session's agent. source attaches the prompt to a tool call.
  • metadata passes extra detail to permission prompts and evaluate hooks.

A deny rule or a rejection with feedback rejects with a Tool.Error that carries the reason, so the model sees it and
continues. A plain rejection ends the current step. Let these errors propagate rather than returning them as tool
output.

Inspect or resolve pending permission requests.

ts
const pending = await ctx.permission.list({ sessionID })
const request = await ctx.permission.get({ sessionID, requestID })
await ctx.permission.reply({ sessionID, requestID, reply: "once" })

Replace the session-scoped permission rules. They are evaluated after the agent's rules, and the
last matching rule wins. Child sessions inherit the rules in effect when they are created.

ts
await ctx.session.update({
  sessionID,
  permissions: [{ action: "edit", resource: "/path/to/original/checkout/**", effect: "deny" }],
})

Sessions

Create or read a session.

ts
const created = await ctx.session.create({ title: "Review" })
const session = await ctx.session.get({ sessionID })
const messages = await ctx.session.context({ sessionID })

List sessions a page at a time. To get the next page, pass cursor.next back as cursor. The cursor remembers your
filters, so you don't need to repeat them.

ts
const page = await ctx.session.list({ directory: ctx.location.directory, limit: 20 })
const next = page.cursor.next ? await ctx.session.list({ cursor: page.cursor.next, limit: 20 }) : undefined

Change the agent or model used by subsequent requests.

ts
await ctx.session.switchAgent({ sessionID, agent: "build" })
await ctx.session.switchModel({ sessionID, model: { providerID: "anthropic", id: "claude-sonnet-4-5" } })

Send user prompts, transient generation requests, commands, or synthetic messages.

ts
const prompt = await ctx.session.prompt({ sessionID, text: "Review the current changes" })
const generated = await ctx.session.generate({ sessionID, prompt: "Summarize this project" })
const command = await ctx.session.command({ sessionID, command: "review", arguments: "--staged" })
const synthetic = await ctx.session.synthetic({ sessionID, text: "Deployment completed" })

Rename, interrupt, or wait for a session.

ts
await ctx.session.update({ sessionID, title: "Review" })
await ctx.session.interrupt({ sessionID, continue: false })
await ctx.session.wait({ sessionID })

Remove a temporary session with remove. Removal stops active execution and recursively deletes child sessions.

ts
await ctx.session.remove({ sessionID })

Request compaction with compact. It returns the admitted inbox item, not a completed summary; compaction runs at
the next step boundary by default. Pass delivery: "queue" to preserve queue order instead.

ts
const compaction = await ctx.session.compact({ sessionID })

Reference

Schemas: Session.Info, Model.Ref,
Session.Inbox.User, Session.Inbox.Synthetic

ts
interface SessionContext {
  create(input?: SessionCreateInput, requestOptions?: RequestOptions): Promise<SessionInfo>
  get(input: SessionGetInput, requestOptions?: RequestOptions): Promise<SessionInfo>
  remove(input: SessionRemoveInput, requestOptions?: RequestOptions): Promise<void>
  context(input: SessionContextInput, requestOptions?: RequestOptions): Promise<readonly SessionMessageInfo[]>
  switchAgent(input: SessionSwitchAgentInput, requestOptions?: RequestOptions): Promise<void>
  switchModel(input: SessionSwitchModelInput, requestOptions?: RequestOptions): Promise<void>
  update(input: SessionUpdateInput, requestOptions?: RequestOptions): Promise<void>
  move(input: SessionMoveInput, requestOptions?: RequestOptions): Promise<void>
  prompt(input: SessionPromptInput, requestOptions?: RequestOptions): Promise<SessionInboxUser>
  generate(input: SessionGenerateInput, requestOptions?: RequestOptions): Promise<{ text: string }>
  command(input: SessionCommandInput, requestOptions?: RequestOptions): Promise<SessionInboxUser>
  compact(input: SessionCompactInput, requestOptions?: RequestOptions): Promise<SessionInboxCompaction>
  synthetic(input: SessionSyntheticInput, requestOptions?: RequestOptions): Promise<SessionInboxSynthetic>
  interrupt(input: SessionInterruptInput, requestOptions?: RequestOptions): Promise<void>
  wait(input: SessionWaitInput, requestOptions?: RequestOptions): Promise<void>
}

Skills

Read the skills available at a location.

ts
const skills = await ctx.skill.list()

Register a transform to inspect, add, update, or remove skills. get(id) returns the current editor entry, or undefined
when the skill is absent.

ts
await ctx.skill.transform((editor) => {
  const skills = editor.list()
  editor.add({
    id: "review",
    name: "Review",
    description: "Review the current changes",
    path: "/workspace/.opencode/skills/review/SKILL.md",
    content: "Review the current changes for correctness and missing tests.",
  })
  const review = editor.get("review")
  editor.update("review", (skill) => {
    skill.autoinvoke = true
  })
  editor.remove("legacy")
})

Reload skills after external state used by a transform changes.

ts
await ctx.skill.reload()

Reference

Schema: Skill.Info

ts
interface SkillContext {
  list(input?: SkillListInput, requestOptions?: RequestOptions): Promise<SkillListOutput>
  transform(callback: (editor: SkillEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface SkillEditor {
  list(): readonly SkillInfo[]
  get(id: string): SkillInfo | undefined
  add(skill: SkillInfo): void
  update(id: string, update: (skill: SkillInfo) => void): void
  remove(id: string): void
}

Storage

Store, read, or remove durable JSON values scoped to the plugin.

ts
await ctx.storage.set("settings", { strict: true })
const settings = await ctx.storage.get("settings")
await ctx.storage.remove("settings")

Scan keys by prefix with optional cursor pagination.

ts
const page = await ctx.storage.scan({ prefix: "cache/", limit: 100 })
const next = page.next

Reference

ts
interface StorageContext {
  get(key: string): Promise<Json | undefined>
  set(key: string, value: Json): Promise<void>
  remove(key: string): Promise<void>
  scan(options: StorageScanOptions): Promise<StorageScanResult>
}

interface StorageScanOptions {
  prefix: string
  after?: string
  limit?: number
}

interface StorageScanResult {
  entries: readonly { key: string; value: Json }[]
  next?: string
}

Tools

Read the tools currently registered, after every transform, outside of a transform callback. Each tool has an id
containing its effective name.

ts
const tools = await ctx.tool.list()
const read = tools.find((tool) => tool.id === "read")

Register, update, and remove tools with a synchronous transform, including in Promise plugins. Load external data
before registering or reloading. A later valid registration overrides the same effective tool name.

ts
const registration = await ctx.tool.transform((editor) => {
  editor.namespace({
    name: "acme",
    description: "Customer account tools",
  })
  editor.add({
    name: "greeting",
    description: "Create a greeting",
    input: {
      type: "object",
      properties: { name: { type: "string" } },
      required: ["name"],
      additionalProperties: false,
    },
    options: { namespace: "acme", codemode: true },
    execute: async (input, context) => {
      await context.progress({ status: "greeting" })
      return { content: `Hello ${(input as { name: string }).name}!` }
    },
  })
})

Promise tool executors receive context.signal. Pass it to cancellable work such as fetch so stopping the Session
also stops the underlying operation.

ts
execute: async ({ url }, context) => {
  const response = await fetch(url, { signal: context.signal })
  return { content: await response.text() }
}

Call reload() after changing source data captured by the callback. Reload replays the active transforms without
changing their order; it does not rerun plugin setup.

ts
await ctx.tool.reload()

Use list() and get() to inspect tools currently in the editor. Tools have an id containing their effective name,
and get() returns undefined when that ID is not present. Use update and remove with the effective tool name,
including its namespace (acme_greeting above). Dots in
namespaces and unsupported characters in tool names become _. Missing names are ignored; creating a tool requires
add with a complete definition. Updates preserve the name and namespace. Assign new schemas or options to replace
them rather than mutating nested values. Invalid updates are logged and leave the previous definition intact.

ts
await ctx.tool.transform((editor) => {
  editor.update("acme_greeting", (tool) => {
    tool.description = "Greet the user by name"
  })
  editor.remove("acme_obsolete")
})

Updates and removals replay in order with additions, including after MCP catalog refreshes. Disposing their
registration removes those changes and rebuilds from the remaining transforms.

Dispose a registration to remove its transform and rebuild from the remaining transforms, revealing any earlier
definition it overrode. Disposal is idempotent, and unloading the plugin also disposes its registrations.

ts
await registration.dispose()

Each model request captures a stable, executable tool snapshot. Later transforms, reloads, and disposal affect future
snapshots, not the definitions, Code Mode namespace descriptions, or executors already captured. Executors that close
over mutable plugin data still observe that data; capture a value inside the transform when it must remain tied to
that definition.

Reference

Schemas: Tool.Content, Tool.TextContent,
Tool.FileContent

ts
interface ToolContext {
  list(): Promise<readonly (ToolInfo & { readonly id: string })[]>
  transform(callback: (editor: ToolEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface ToolEditor {
  list(): readonly (ToolInfo & { readonly id: string })[]
  get(id: string): (ToolInfo & { readonly id: string }) | undefined
  namespace(namespace: { name: string; description: string }): void
  add(tool: ToolInfo): void
  update(id: string, update: (tool: Types.Mutable<ToolInfo>) => void): void
  remove(id: string): void
}

VCS

Read repository information, working-copy status, or file diffs.

ts
const info = await ctx.vcs.get()
const branches = await ctx.vcs.branches({ search: "feature", limit: 10 })
const changes = await ctx.vcs.status()
const diff = await ctx.vcs.diff({ mode: "working", context: 3 })

Register a location-scoped VCS provider with a transform. A provider matching the detected repository type is selected
automatically; use editor.default.set to select a different provider.

ts
await ctx.vcs.transform((editor) => {
  editor.add({
    id: "custom",
    name: "Custom VCS",
    info: async () => ({ branch: { current: "feature", default: "main" } }),
    branches: async (input, { signal }) => readBranches(input, signal),
    status: async (scope, { signal }) => readStatus(scope.worktree, signal),
    diff: async (input, { signal }) => readDiff(input, signal),
  })
  editor.default.set("custom")
})

Provider callbacks receive the current location, working-copy root, canonical project root, and optional repository
store. Diff callbacks also receive the selected mode, requested context, and output byte budget. Repository discovery
continues to use OpenCode's built-in Git and Mercurial detectors.

Providers can optionally implement init(scope, { signal }) to create a repository in scope.worktree. Initialization
selects the provider by ID (Git by default), not by the detected repository type. Register a provider with init even
when the location has no repository yet; OpenCode checks that the directory exists and has no repository before calling
it, then rediscovers the project. New repository formats still need discovery support beyond this callback.

Reference

Schemas: Vcs.Info, Vcs.FileStatus,
FileDiff.Info

ts
interface VcsContext {
  get(input?: VcsGetInput, requestOptions?: RequestOptions): Promise<VcsGetOutput>
  branches(input?: VcsBranchesInput, requestOptions?: RequestOptions): Promise<VcsBranchesOutput>
  status(input?: VcsStatusInput, requestOptions?: RequestOptions): Promise<VcsStatusOutput>
  diff(input: VcsDiffInput, requestOptions?: RequestOptions): Promise<VcsDiffOutput>
  transform(callback: (editor: VcsEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface VcsEditor {
  add(definition: VcsDefinition): void
  default: {
    get(): string | undefined
    set(providerID: string): void
  }
}

interface VcsDefinition {
  init?(scope: VcsScope, context: { signal: AbortSignal }): Promise<void>
  // Existing info, branches, status, and diff callbacks are required.
}

Worktrees

Register a local worktree strategy using the normal plugin lifecycle. The implementation module in this example owns
option validation and the backend's create, remove, and list operations.

ts title="plugins/worktrees/index.ts"
import { Plugin } from "@opencode/plugin"
import { makeStrategy } from "./strategy"

export default Plugin.define({
  id: "company.worktrees",
  async setup(ctx) {
    const strategy = makeStrategy(ctx.options)
    await ctx.worktree.transform((editor) => {
      editor.add(strategy)
    })
  },
})

Load the plugin through plugins and configure the common destination separately:

jsonc title="opencode.jsonc"
{
  "worktree": { "directory": "../worktrees" },
  "plugins": [{ "package": "./plugins/worktrees", "options": {} }],
}
  • Adding a strategy selects it automatically. The last active registration wins; no strategy-selection config is needed.
  • Disposing its registration or unloading the plugin restores the previous implementation, ultimately the bundled Git strategy.
  • reload() replays transforms after captured inputs change; it does not rerun plugin setup.
  • Creation failures do not retry through Git. Existing worktrees retain their recorded owner even when the default changes.
  • Strategies manage local directories. Remote workspace provisioning is not part of this interface.

Operations

The plugin context exposes the same project-based worktree operations as the client. Every operation requires a
projectID. list reads only saved inventory, including known checkouts of the same project; it does not load
configuration, start plugins, or discover filesystem changes.

ts
const projectID = ctx.location.project.id
const created = await ctx.worktree.create({ projectID, name: "task" })
const inventory = await ctx.worktree.list({ projectID })
await ctx.worktree.refresh({ projectID })
await ctx.worktree.remove({ projectID, directory: created.directory, force: false })

Create loads configuration and plugins from the project's saved canonical directory and uses their selected strategy.
It accepts an optional parent directory, source from, starting branch, and name.
The source defaults to the canonical checkout, and a from override must belong to that project. Choosing a source
does not change the configuration root.
A supplied starting ref must be supported by the selected strategy;
Rift's native snapshot operation, for example, has no ref-selection option.

Create and refresh wait for the canonical checkout's plugins to activate. Calls made during that checkout's plugin
setup see registrations made so far and do not wait for their own activation.

Remove loads the canonical configuration and activates its plugins, then uses the worktree's recorded strategy rather
than the currently selected default. An unavailable recorded owner produces an error. The worktree's destination can
be elsewhere:

ts
await ctx.worktree.remove({
  directory: "/worktrees/task",
  projectID,
  force: false,
})

Missing owners fail removal rather than falling back to Git. A strategy can throw new Worktree.OperationError({ message: "Uncommitted changes", forceRequired: true }), importing Worktree from @opencode/plugin, to request
force confirmation without depending on Core or Git errors.

Refresh loads canonical configuration and asks all available strategies to find worktrees across known checkout roots.
It combines results, preserves recorded ownership, and prunes missing directories. A failed discovery source is logged
while other sources continue. Existing directories remain saved even if no available strategy reports them. Observe
worktree.updated and call list again to read changed inventory.

ts
await ctx.worktree.refresh({ projectID })

Reference

Implementations receive a suggested destination after naming and collision handling. Return the actual directory from
create; it may differ when a backend requires its own layout. OpenCode resolves the returned path and uses it for
inventory, startup commands, and the API result. The returned directory must exist.

Strategies choosing another destination handle naming collisions there. OpenCode still creates the suggested parent
directory before calling the strategy. list must report only directories the strategy owns, plus any repository roots.

ts
interface WorktreeDefinition {
  readonly id: string
  create(
    input: { sourceDirectory: string; directory: string; branch?: string },
    context: { signal: AbortSignal },
  ): Promise<{ directory: string }>
  remove(input: { directory: string; force: boolean }, context: { signal: AbortSignal }): Promise<void>
  list(
    sourceDirectory: string,
    context: { signal: AbortSignal },
  ): Promise<readonly { directory: string; type: "root" | "worktree" }[]>
}

interface WorktreeEditor {
  add(definition: WorktreeDefinition): void
}

interface WorktreeDomain extends WorktreeApi {
  transform(callback: (editor: WorktreeEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

Promise callbacks must cooperate with signal cancellation. Effect callbacks return Effects and use Effect interruption
instead. Registrations remain scoped to the plugin runtime; project operations use the canonical checkout's registry.
Core configuration adapters feed directory settings into that registry.

Websearch

List websearch providers or run a query through the selected provider.

ts
const providers = await ctx.websearch.providers()
const results = await ctx.websearch.query({ query: "OpenCode plugins", providerID: "internal" })

Register a provider and select the default provider with a transform.

ts
await ctx.websearch.transform((editor) => {
  editor.add({
    id: "internal",
    name: "Internal search",
    execute: async ({ query }, { signal }) => {
      const response = await fetch(`https://search.example.com?q=${encodeURIComponent(query)}`, { signal })
      const result = await response.json()
      return [{ url: result.url, title: result.title, content: result.content, time: {} }]
    },
  })
  editor.default.set("internal")
})

Disable websearch by selecting false, or reload providers after external state changes.

ts
await ctx.websearch.transform((editor) => editor.default.set(false))
await ctx.websearch.reload()

Reference

Schemas: WebSearch.Provider, WebSearch.Result

ts
interface WebSearchContext {
  providers(input?: WebsearchProvidersInput, requestOptions?: RequestOptions): Promise<WebsearchProvidersOutput>
  query(input: WebsearchQueryInput, requestOptions?: RequestOptions): Promise<WebsearchQueryOutput>
  transform(callback: (editor: WebSearchEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

interface WebSearchEditor {
  add(provider: WebSearchDefinition): void
  default: {
    get(): string | false | undefined
    set(providerID: string | false): void
  }
}

Events

Subscribe to the connected server's public event stream. Abort the stream during plugin cleanup.

ts
const controller = new AbortController()
void (async () => {
  for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
    console.log(event.type)
  }
})()
return () => controller.abort()

Reference

Schema: V2EventEncoded

ts
interface EventContext {
  subscribe(options?: { signal?: AbortSignal }): AsyncIterable<OpenCodeEvent>
}

Hooks

Hooks intercept live operations. Register a hook on its domain and dispose the
returned registration when it is no longer needed.

ts
const registration = await ctx.session.hook("context", () => {})
await registration.dispose()

Multiple plugins can register the same hook. OpenCode runs them in plugin order,
so later hooks see changes made by earlier hooks.

Sessions

Session hooks intercept prompt admission, model calls, native HTTP, and retries.

Prompt admission

Intercept incoming user prompts before attachment and skill resolution and durable inbox admission:

ts
await ctx.session.hook("prompt", (event) => {
  event.prompt.text = event.prompt.text.replaceAll("company-secret", "[redacted]")
  event.prompt.files ??= []
  event.prompt.files.push({ uri: "file:///project/policy.md" })
  event.metadata = { ...event.metadata, source: "company-policy" }
  event.delivery = "queue"
})

The hook receives an owned, mutable draft:

  • prompt contains text, files, agent mentions in agents, and selected skills.
  • metadata contains application-defined admission metadata.
  • delivery is "steer" by default and can be changed to "queue".
  • Session and message IDs are readonly; a hook cannot redirect admission.

Files and skills added by a hook follow the normal resolution and validation
path. When rewriting text, update or remove attachment mention offsets that no
longer match. Agent mentions do not switch the session's active agent.

Prompt hooks run under these conditions:

  • Hooks run in registration order after the session's location plugins are ready.
  • Commands that submit through session.prompt run the hook.
  • Synthetic messages, shell messages, compaction controls, and move controls do not.
  • The hook runs once during admission, not before every model call.
  • Provider scoping is unavailable because model resolution happens after admission.

Edits become the canonical persisted user input. If preparation fails or is
interrupted, OpenCode does not admit the prompt.

Keep prompt hooks retry-safe. They are not an exactly-once side-effect boundary:

  • Retrying an ID already pending or delivered returns the original admission without rerunning hooks.
  • Concurrent submissions can run hooks more than once, but only the first successful admission wins.
  • Prompt hooks transform input and do not expose a typed rejection API.

Model requests

Modify assembled system instructions, messages, tools, or request options immediately before model dispatch. Each
kind of request a session issues has its own hook, so a plugin can treat the agent loop and auxiliary requests
differently:

  • context runs for the agent loop, including tool-driven continuations.
  • compaction runs for checkpoint summaries. messages is the transcript being summarized; OpenCode appends its
    summary prompt after hooks run. Set result to record the compaction yourself and skip the model call; it takes the
    same fields as a completed compaction message.
  • generate runs for transient ctx.session.generate calls.
  • title runs for title generation. It has no agent or tools. Set result to supply the title yourself.
ts
await ctx.session.hook("context", (event) => {
  event.system.push({ type: "text", text: "Keep the review focused on correctness." })
  delete event.tools.write
  event.options.temperature = 0.2
  event.options.maxTokens = 8_000
})

await ctx.session.hook("compaction", async (event) => {
  event.result = { summary: await summarize(event.messages) }
})

Changes affect only the outgoing model call, not persisted history or configuration. A hook that should apply to
every request must register for each kind.

Request overrides follow these rules:

  • options starts empty for each model call; it does not contain resolved model settings.
  • Typed keys are generation settings; any other key is passed to the selected protocol as a provider option.
  • Hooks run in registration order and see overrides made by earlier hooks.
  • Request overrides take precedence over model defaults, which take precedence over route defaults.
  • Provider option objects merge recursively; arrays and scalar values replace earlier values.
  • Deleting an override or setting it to undefined falls back to configured defaults rather than removing them.
  • Raw HTTP body overlays apply after protocol lowering and can override the resulting fields.

Provider options

Provider options use the selected protocol's semantic option names, not raw HTTP body fields. Scope provider-specific
settings to the matching provider. For example, OpenAI Responses uses reasoningEffort:

ts
await ctx.session.hook(
  "context",
  (event) => {
    event.options.reasoningEffort = "high"
  },
  { providerID: "openai" },
)

Generation options depend on the selected protocol and model:

  • maxTokens is the semantic output-token limit.
  • Gemini supports topK; OpenAI Responses does not expose it.

Model request

Modify model request settings and optionally scope the hook to one provider. The event carries the same kind
as the HTTP hooks below.

ts
await ctx.session.hook(
  "model.request",
  (event) => {
    event.headers["x-plugin"] = "review"
  },
  { providerID: "anthropic" },
)

Native HTTP

Modify native provider requests or responses. Their bodies are one-shot streams; clone or replace a body before reading
it.

Both hooks run for every request a session issues. event.kind says which flow issued it: "primary" for the agent
loop, "compaction" for checkpoint summaries, "title" for title generation, and "generate" for transient
ctx.session.generate calls. Use it instead of the agent ID to tell auxiliary requests apart.

ts
await ctx.session.hook("http.request", (event) => {
  event.request.headers.set("x-session-id", event.sessionID)
  if (event.kind === "title") event.request.headers.set("x-priority", "background")
})

await ctx.session.hook("http.response", (event) => {
  event.response = new Response(event.response.body, {
    status: event.response.status,
    headers: { ...Object.fromEntries(event.response.headers), "x-plugin": "review" },
  })
})

Native WebSocket (experimental)

Providers that stream over a WebSocket open one connection per session and reuse it across requests, so
http.request and http.response never see that traffic. The experimental.ws.handshake hook runs once per model
call before the connection is selected. It carries the same sessionID, agent, model, and kind as the HTTP
hooks, plus the connection url and headers. Changing url or headers changes which socket the request uses, so a
rotated bearer token reopens the connection.

HTTP hooks still run for every HTTP request, including the request a WebSocket route falls back to.

ts
await ctx.session.hook(
  "experimental.ws.handshake",
  async (event) => {
    event.headers.authorization = `Bearer ${await mintToken(event.url)}`
    delete event.headers["api-key"]
  },
  { providerID: "azure" },
)

experimental.ws.send and experimental.ws.receive expose the frames themselves, the WebSocket counterpart of
editing an HTTP request or response body. send runs after the provider driver builds an outbound frame and before it
is written; receive runs on each inbound frame before the driver observes it. Both carry the frame as a string and
send whatever frame holds when the hook returns.

OpenCode does not validate rewritten frames. The driver tracks state from the provider's replies, so a rewrite that
changes protocol meaning is the plugin's responsibility, just as a rewritten HTTP body is.

ts
await ctx.session.hook(
  "experimental.ws.send",
  (event) => {
    const body = JSON.parse(event.frame)
    if (body.type === "response.create") body.metadata = { ...body.metadata, session: event.sessionID }
    event.frame = JSON.stringify(body)
  },
  { providerID: "openai" },
)

await ctx.session.hook("experimental.ws.receive", (event) => {
  if (event.frame.includes('"type":"error"')) console.error(event.frame)
})

These hooks are experimental and their names or shapes may change.

Retry policy

Override the retry decision for a provider failure or replace its delay in milliseconds. The hook runs after OpenCode
classifies the failure and proposes its policy, but before any retry is scheduled. It does not expose how OpenCode
internally performs the next attempt.

ts
await ctx.session.hook("retry", (event) => {
  if (event.error.status === 429) {
    event.decision = { retry: true, delay: 10_000 }
    return
  }
  if (event.error.type === "provider.invalid-request" && event.attempt === 2) {
    event.decision = { retry: true, delay: 0 }
    return
  }
  if (event.attempt >= 3) event.decision = { retry: false }
})

Retry hooks can change OpenCode's initial decision by making a terminal failure
retryable or vetoing a proposed retry.

Retry decisions follow these rules:

  • Multiple hooks run in registration order, and later hooks see the current decision.
  • The built-in maximum attempt count remains a hard limit.
  • attempt is the physical attempt under consideration. The initial request is 1, so the first retry is 2.
  • Invalid delays such as NaN, infinity, or negative values fall back to the computed delay.
  • Context-overflow recovery is separate because it compacts the conversation instead of retrying the same request.

Session reference

text
/* Detailed source-code truncated for AI context efficiency. */

Permissions

Review permission decisions after configured rules are evaluated and before an
action runs or a permission prompt is published.

ts
await ctx.permission.hook("evaluate", async (event) => {
  if (event.action === "read") return

  const messages = await ctx.session.context({ sessionID: event.sessionID })
  const review = await ctx.generate.text({
    model: { providerID: "anthropic", id: "claude-sonnet-4-6" },
    prompt: buildSafetyPrompt({ messages, action: event.action, resources: event.resources }),
  })
  const decision = parseDecision(review.text)

  event.effect = decision.effect
  event.message = decision.reason
})

Permission hooks follow these rules:

  • Hooks run for allow and ask decisions.
  • An explicit configured deny is final and does not invoke the hook.
  • A hook may change effect to allow, ask, or deny.
  • message appears in an escalated permission request or becomes the denial reason.

Reference

ts
interface PermissionEvaluation {
  readonly sessionID: string
  readonly agent?: string
  readonly action: string
  readonly resources: readonly string[]
  readonly metadata?: Record<string, unknown>
  readonly source?: { type: "tool"; messageID: string; id: string }
  effect: "allow" | "ask" | "deny"
  message?: string
}

Shell

Modify shell commands, working directories, timeouts, executables, or environment variables before execution.

ts
await ctx.shell.hook("create.before", (event) => {
  event.timeout = Math.min(event.timeout, 60_000)
  event.env.COMPANY_ENV = "development"
})

Reference

ts
interface ShellHookContext {
  hook(name: "create.before", callback: (event: ShellCreateBefore) => Promise<void> | void): Promise<Registration>
}

interface ShellCreateBefore {
  command: string
  cwd: string
  timeout: number
  shell: string
  env: Record<string, string | undefined>
}

Tools

Inspect or replace tool input before execution.

ts
await ctx.tool.hook("execute.before", (event) => {
  if (event.tool === "read") console.log(event.input)
})

Inspect successful results or failures after execution.

ts
await ctx.tool.hook("execute.after", (event) => {
  if (event.status === "completed") event.result = { ...event.result, metadata: { observed: true } }
  if (event.status === "error") console.error(event.error.message)
})

Reference

ts
interface ToolHooks {
  "execute.before": ToolExecuteBefore
  "execute.after": ToolExecuteCompleted | ToolExecuteFailed
}

interface ToolHookContext {
  hook<Name extends keyof ToolHooks>(
    name: Name,
    callback: (event: ToolHooks[Name]) => Promise<void> | void,
  ): Promise<Registration>
}

Publish

A package plugin uses the same default export as a local plugin. A minimal
manifest is:

json title="package.json"
{
  "name": "opencode-acme-plugin",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": "./src/index.ts",
    "./rpc": "./src/rpc.ts"
  },
  "dependencies": {
    "@opencode/plugin": "latest"
  }
}

The ./rpc export is optional; include it when publishing a shared
RPC contract for other plugins and clients to import
without loading your implementation.

Use versions compatible with the OpenCode release you target and test the
installed package, not only a workspace-linked copy. Publish a compatible
plugin update when you adopt a newer API contract.

Support V1

A plugin can support V1 and V2 from the same package entrypoint. Default export
one object with a V1 server() function and a V2 setup() function:

ts title="src/index.ts"
import { Plugin } from "@opencode/plugin"

export default {
  ...Plugin.define({
    id: "example",
    async setup(ctx) {
      await ctx.tool.hook("execute.before", () => {
        console.log("A tool is about to run")
      })
    },
  }),
  async server() {
    return {
      "tool.execute.before": async () => {
        console.log("A tool is about to run")
      },
    }
  },
}
  • V1 calls server() and uses the returned hooks.
  • V2 reads the default export's id and setup() (or effect() for Effect plugins), ignoring server().
  • Keep each implementation on its own API; sharing an export does not translate V1 hooks into V2 hooks.
  • Spread Plugin.define(...) into the exported object so it type-checks the V2 definition separately from server().

The V1 object form is supported in OpenCode 1.18.29. Older V1 releases may
expect function exports instead; test the installed package with the oldest V1
release you intend to support and with V2.


Services Www Src Docs Content Build Sdk Index (`services/www/src/docs/content/build/sdk/index.mdx`)


title: "Overview"

@opencode/sdk hosts OpenCode directly inside your application. Unlike the
network client, it assembles the OpenCode server and routes API
calls through its HTTP router in memory. It opens no HTTP listener and adds no
network hop between the client and server.

For Cloudflare Durable Objects, see the Cloudflare guide.

Install the SDK:

sh
bun add @opencode/sdk

Create a host

OpenCode.create() returns an explicitly owned host. Use await using to
release its router, Location services, fibers, and scoped plugin registrations:

ts
import { OpenCode } from "@opencode/sdk"

await using opencode = await OpenCode.create()
const session = await opencode.sessions.create({
  location: { directory: "/workspace" },
})

await opencode.sessions.prompt({
  sessionID: session.id,
  text: "Review the current changes",
})

Call await opencode.close() explicitly when explicit resource management is
not available.

The embedded host uses the same Promise values, declared errors, request
options, and AsyncIterable streams as @opencode/client. It exposes the
full generated client and adds the convenience aliases sessions and events
for the session and event groups.

Worktrees

Worktree operations require a projectID. Create and refresh load configuration and plugins from the project's saved
canonical checkout. List reads saved inventory only; remove activates canonical plugins and uses the recorded strategy,
failing if that strategy is unavailable.

ts
const projectID = session.projectID
const worktree = await opencode.worktree.create({ projectID, name: "task" })
await opencode.worktree.refresh({ projectID })
await opencode.worktree.remove({ projectID, directory: worktree.directory, force: false })

Refresh discovers worktrees across known checkout roots using all available strategies. Register a custom strategy
through a plugin's worktree transform.

Stream events

ts
for await (const event of opencode.events.subscribe()) {
  console.log(event.type)
}

Pass an AbortSignal through the generated request options, or leave an
iteration to cancel its response body.

Customize

Customize your OpenCode instance by registering plugins. Pass plugins to
OpenCode.create() to customize agents, models, tools, and other behavior when
the embedded host starts:

ts
import { Plugin } from "@opencode/plugin"
import { OpenCode } from "@opencode/sdk"

const plugin = Plugin.define({
  id: "customize-agent",
  async setup(ctx) {
    await ctx.agent.transform((agents) => {
      agents.update("build", (agent) => {
        agent.description = "Builds features and fixes bugs for our team"
      })
    })
  },
})

await using opencode = await OpenCode.create({ plugins: [plugin] })

Call await opencode.plugin(plugin) to register another plugin after startup.

See the full plugins documentation for plugin hooks,
transforms, tools, and the complete plugin context.


Services Www Src Docs Content Console Api Index (`services/www/src/docs/content/console/api/index.mdx`)


title: "API Overview"

The Console API lets your scripts and integrations call models and manage budgets. Every request authenticates with
an API key.

bash
curl --fail-with-body "https://opencode.ai/console/api/v1/budgets/members" \
  --header "Authorization: Bearer oc_sk_..."
API Endpoints
Inference https://opencode.ai/inference/...
Providers https://opencode.ai/inference/custom/...
Budgets /api/v1/budgets/members

API keys

Both workspace members and service accounts can have API keys. Send a key as a bearer token.

text
Authorization: Bearer oc_sk_...
Personal API key Service account key
Created by Any member, for themselves Owners and admins
Created in Account › Personal API keys Settings › Service accounts
Acts as The member who created it The service account
Usage counted to The member's budget The service account's budget
Best for Your own scripts and harnesses CI, shared machines, and integrations
  • Each key works in one workspace, chosen when it is created. No workspace header is needed.
  • The full key is shown only once, right after you create it. Afterward Console shows only its prefix.
  • Expiration is optional: Never, 1 day, 7 days, 30 days, or Custom (1 to 365 days). An expired
    key can't be renewed, so create a new one.

Personal API keys

A personal key acts as you. Your role, budgets, and model rules apply to it.

  1. Open Account from the account menu and find Personal API keys.
  2. Click Add API key.
  3. Choose the Workspace, a Key name, and an optional Expiration. Owners and admins also choose
    Permissions.
  4. Click Create and copy the key.
text
oc_sk_1a2b3c4d5e6f_...

The key follows your current access to the workspace. If your role changes, so does what the key can do. If the
workspace enforces SSO, the key works only while you have an active SSO session, unless
you are an owner.

Service accounts

A service account is a non-human member of the workspace with its own API keys, usage, and
budget. Use one for automation, so usage isn't tied to a person. Owners and
admins manage them.

  1. Open Settings › Service accounts and click Add Service Account, then name it, for example CI Pipeline.
  2. Open the service account and click Add API Key.
  3. Choose a Key name, an optional Expiration, and Permissions, then click Create.
  4. Copy the key.
bash
export SERVICE_API_KEY="oc_sk_..."

Owners and admins can rename a service account key or change its permissions later with Edit… in the key's actions
menu.

Permissions

Each key has a permission level, chosen under Permissions when you create it.

Permissions Allows
All Everything the member or service account can do, except This account's API keys.
Restricted Only the resources you choose.
Read only Read access to every resource. The key can list models but not call them.

A key never does more than whoever it acts as. A personal key is capped by the member's current role, and a service
account key by what service accounts can do.

Restricted keys

Set each resource to None, Read, or Write. Write includes Read.

Resource Levels
Models Read, Request
Usage Read
Budgets Read, Write
Members Read, Write
Providers Read, Write
Billing Read, Write
Workspace settings Read, Write
SSO Read
Service accounts Read
This account's API keys Write

Models › Read lists models, and Models › Request also calls them through the Inference
and Providers APIs. For example, a key for a budget integration only needs:

text
Permissions: Restricted
Budgets:     Write

Keys created as Inference only before scoped permissions show as Restricted with Models set to Request.

Who can grant what

  • Members can only create personal keys that list and call models. Console shows "This key can list and call
    models as you." instead of permission choices.
  • Owners and admins can give their personal keys All, Restricted, or Read only, up to their own role.
    The default is Restricted with Models set to Request. If they are later demoted, their keys shrink to
    match.
  • Service account keys default to All. Owners and admins choose their permissions.

Limitations

Some actions always need a person signed in to the Console, and creating keys with a key is tightly limited.

  • No API key can change SSO settings or delete the workspace.
  • Service account keys can't invite members, change roles, remove members, manage billing, change workspace settings,
    manage models, or create or remove service accounts, even with All.
  • This account's API keys is only available on service account keys, and All doesn't include it. A key with it
    can create and revoke keys for its own service account only. New keys must be Restricted, stay within the
    creating key's permissions, and can't include This account's API keys.
  • Personal keys can never get This account's API keys, and no API key can create or revoke personal API keys.

Requests outside a key's permissions return HTTP 403.

Revocation

Key Who can revoke it Where
Personal API key The member who owns it Account › Personal API keys, then Revoke
Personal API key Owners and admins The member's page in Settings › Members, under API Keys
Service account key Owners and admins The service account's page in Settings › Service accounts, under API Keys

Keys are also revoked automatically:

  • Leaving or being removed from a workspace, or being deprovisioned through SCIM, revokes every key
    that person created in it, including service account keys. Other keys on the same service account keep working.
  • Removing a service account revokes all its keys.

Revoked and expired keys stop working immediately and return HTTP 401.


Services Www Src Docs Content Console Harnesses Index (`services/www/src/docs/content/console/harnesses/index.mdx`)


title: "Harnesses"

Console works with coding agents other than OpenCode. Point a harness at the Console gateway with an API key, and usage
is billed to your workspace like any other request.

Harness Pay-as-you-go Go Models MCP
Claude Code Yes Yes Anthropic Messages models Yes
Codex Yes Yes OpenAI Responses models Yes
Hermes Built in Built in All models Yes
Pi Built in Built in All models Yes
Raycast Extension Extension All models Yes

Get an API key

Harnesses authenticate with a Console API key. The quickest option is a
personal API key, which calls models as you.

  1. Open Account from the account menu in the Console.
  2. Under Personal API keys, click Add API key.
  3. Choose the workspace, name the key, and click Create.
  4. Copy the key. It is shown only once.
text
oc_sk_1a2b3c4d5e6f_...

Usage counts toward your member budget. Use a key from a workspace with credits for
pay-as-you-go, or from a workspace subscribed to Go for Go.

For shared machines or CI, owners and admins can create a service account key instead,
so usage isn't tied to one person.

Base URLs

Pay-as-you-go and Go are served from different base URLs. Use the one that matches your plan.

Plan Base URL
Pay-as-you-go https://opencode.ai/inference
Go https://opencode.ai/inference/go

Append the path for the API your harness speaks.

API Path
OpenAI Responses /openai/v1/responses
OpenAI Chat Completions /openai/v1/chat/completions
Anthropic Messages /anthropic/v1/messages
Gemini /google/v1beta/models/<model>:generateContent
text
https://opencode.ai/inference/go/openai/v1/chat/completions

Choose an API

A harness can only use the models that accept the API it speaks. Most models accept one API, and some accept several.
The endpoint column in the Console and Go tables lists one API per
model, so check the harness page for the full list.

Hermes, Pi, and the Raycast extension pick the right API for each model, so they can use every model. Claude Code and
Codex speak a single API and only reach part of the catalog.

Harness API Models
Claude Code Anthropic Messages Claude and Qwen, plus Kimi K3, DeepSeek V4, and MiniMax M3 on Go
Codex OpenAI Responses GPT, Grok, and Muse Spark, plus DeepSeek V4 on Go

Support for every model in every harness is coming soon.

Sessions

Send a stable session ID with every request so Console can route a conversation consistently and reuse its prompt
cache. Go requires it.

text
x-opencode-session: ses_...

Console also recognizes the native session headers sent by Claude Code, Codex, Hermes, and Pi, so they need no extra
configuration.

Console MCP

Harnesses with MCP support can manage your workspace through the Console MCP server. It uses OAuth with dynamic client
registration, so you sign in from the browser instead of pasting a key.

text
https://opencode.ai/console/mcp

Each harness page shows how to add it.


Packages Util Docs Layer Node (`packages/util/docs/layer-node.md`)

Layer Graphs

LayerNode describes replaceable wiring for ordinary Effect Layers. Declarations
and compilation do not acquire resources. Effect still owns acquisition,
memoization, scopes, and finalization.

There are three values to compose:

  • A Node is a replaceable declaration with a fixed output, error, and tag
    contract. make supplies its default implementation; unbound leaves that
    implementation for the caller to supply.
  • A Graph is a node or an ordered group of graphs. Grouping exposes the
    selected roots, not their transitive dependencies. Groups are not replacement
    targets.
  • A Replacement is a checked instruction made by node.replace(...).
    Replacement arrays can be stored and concatenated without losing their checks.
ts
import { Context, Effect, Layer } from "effect"
import { LayerNode } from "@opencode/util/effect/layer-node"

class Database extends Context.Service<Database, { readonly name: string }>()("example/Database") {}
class Users extends Context.Service<Users, { readonly name: string }>()("example/Users") {}

const tags = LayerNode.tags({ global: [], location: ["global"] })
const global = tags.make("global")
const location = tags.make("location")

const database = global({
  service: Database,
  layer: Layer.succeed(Database, { name: "live" }),
  deps: [],
})
const users = location({
  service: Users,
  layer: Layer.effect(
    Users,
    Effect.map(Database, (db) => ({ name: db.name })),
  ),
  deps: [database],
})

const replacements: LayerNode.Replacements = [database.replace(Layer.succeed(Database, { name: "test" }))]

const layer = LayerNode.compile(LayerNode.group([database, users]), {
  replacements,
  shared: tags.values.global,
})
// Layer<Database | Users>: both selected roots remain available.

Substitution

Replacements target the exact declaration, not its display name or service key.
Two independently declared nodes can provide the same service in different
branches without capturing each other's overrides.

Keep the original declaration as the target when configuring a default:

ts
const replacements = [Database.node.replace(Database.configured(options.database)), ...profile.replacements]

The replacement may be a closed Layer or another node. It must provide all the
source's outputs, may provide additional outputs, must not introduce new errors,
and must retain the source's tag. An open Layer must first be wired into a node.
Replacing a node prunes its original dependencies; replacing it with another node
uses that node's dependencies instead.

The rules are:

  • The last replacement for the same source wins, before any traversal.
  • Replacements also apply inside replacement dependency graphs and through
    replacement chains.
  • Replacing a node with itself is the identity operation.
  • Unreachable replacements neither acquire resources nor traverse their graphs.
  • Unbound nodes and cycles in the effective graph fail during compilation.

A node's contract is invariant. It cannot be widened or narrowed to authorize a
replacement that would violate another use of the original declaration. A graph
can forget outputs like an ordinary Layer, but cannot be used as a weaker
replacement handle.

Choice and composition are different: group([a, b]) provides both roots, while
group([condition ? a : b]) promises only outputs common to both alternatives.
The same rule applies to conditional implementation Layers. Use tuples for known
roots; a dynamic array can be empty and therefore guarantees no service outputs.
Every alternative of a conditional replacement must satisfy the source contract.

Decoration

Use mapLayer to decorate a default implementation without duplicating or
inspecting its dependencies:

ts
const observed = database.mapLayer((layer) => layer.pipe(Layer.tap(() => Effect.logDebug("database ready"))))
const replacements = [database.replace(observed)]

The callback is parametric in the Layer's requirements: it must preserve the
declared wiring and service/error contract. mapLayer returns a new node; it does
not mutate or automatically override the original. Only implemented nodes offer
this operation, not unbound slots or groups.

Lifetimes

Without shared, compilation uses Effect's enclosing memo map throughout.
With shared: tag, matching nodes and their dependency subgraphs use that map;
remaining wiring uses one fresh map per build. A shared service's dependencies
must live at least as long as the service, including untagged helpers. This keeps application globals shared while isolating each
Location, without exposing incomplete graphs or losing shared root outputs.

The enclosing memo map remains ambient during construction, so a lazy LayerMap
captures the shared ancestry rather than a Location's private cache. Cache
selection is internal metadata, not an extra service output of each dependency.

Native Layer identity still controls acquisition within each memo map. Use a
distinct implementation Layer for differently wired definitions; compilation
rejects conflicting wiring of the same Layer within one graph's memo domain.
Compiled wiring is memoized once per build and memo domain, so a shared dependency
graph is not expanded into a tree during acquisition. Original Layer identities
still determine service sharing across separately compiled builds. An explicitly
fresh implementation refreshes its acquisition when its wiring is built.

Groups preserve root startup order and associate transparently. A node's
dependencies are built concurrently through native Layer.provide. Named
startup actions and Context references are supported even when their required
service output type is never.

Migration

Previous API Current API
[source, replacement] source.replace(replacement)
compile(graph, replacements) compile(graph, { replacements })
hoist, compile both halves, fresh, provide compile(graph, { replacements, shared: tag })
Spread a node and overwrite implementation node.mapLayer(transform)
Generic root parameter Node<A, E, any> Graph<A, E>

An application can prepend a default binding and append caller overrides instead
of inspecting the original graph with hasUnbound. Unused defaults are pruned,
and defaults introduced as dependencies by an override are found naturally.

Code that reconstructed a replacement source by name must retain the original
declaration instead. Compiler representation fields are no longer public.

PersistentPty.configured(options) now returns a wired node, like the other Core
configuration factories. PersistentPty.layer remains the default raw Layer.

Verification

Run bun run typecheck:dist in packages/util to build the package and check the
same positive and negative contract tests against its emitted declarations.
This ensures package consumers receive the same inference and replacement checks
as callers importing the source.


Services Www Src Docs AGENTS (`services/www/src/docs/AGENTS.md`)

Documentation feature guide

Structure

  • This folder owns the documentation data model, content, frontend, and styling.
  • Documentation content lives in content/ and is loaded by ../content.config.ts.
  • lib/navigation.ts is the source of truth for header sections and sidebar ordering.
  • The thin route entrypoints live in ../pages/docs/; keep docs implementation details here.
  • Do not add a documentation frontend framework; this folder owns the UI directly.
  • Keep internal Markdown links docs-root-relative, for example /config; remark-links.ts applies the site and docs base paths.

Writing Style

  • Keep prose sections brief and focused on one idea. Prefer one to three sentences over large paragraphs.
  • Interleave explanations with concrete code, configuration, command, or output examples so pages do not become walls of text.
  • Put the relevant example immediately after the text that introduces it, following content/build/plugins/cli.mdx as the reference pattern.
  • Every subsection that explains syntax, fields, or an API concept must include its own minimal example. A larger example earlier on the page does not count.
  • Split long explanations with meaningful headings and examples rather than accumulating caveats in one paragraph.
  • Lead with the common task and working example; place edge cases and supporting details afterward.
  • Do not stack several prose paragraphs without a visual break. After introducing a concept, use an example, list, table, or task-oriented subheading before covering the next concern.
  • Use bullets or tables for independent rules, options, and constraints. Do not hide reference material in narrative paragraphs.
  • Organize workflow documentation in the order readers perform it, with a working example at each major step.

Validation

  • Run bun typecheck and bun run build from services/www after changes.
  • Check desktop and mobile layouts when changing navigation or shared styles.

Packages Web Src Content Docs Acp (`packages/web/src/content/docs/acp.mdx`)


title: ACP Support

OpenCode supports the Agent Client Protocol or (ACP), allowing you to use it directly in compatible editors and IDEs.

:::tip
For a list of editors and tools that support ACP, check out the ACP progress report.
:::

ACP is an open protocol that standardizes communication between code editors and AI coding agents.


Configure

To use OpenCode via ACP, configure your editor to run the opencode acp command.

The command starts OpenCode as an ACP-compatible subprocess that communicates with your editor over JSON-RPC via stdio.

Below are examples for popular editors that support ACP.


Zed

Install OpenCode from the Zed ACP Registry by running zed: acp registry in the Command Palette.

To use a custom OpenCode executable instead, add it to your Zed configuration (~/.config/zed/settings.json):

json title="~/.config/zed/settings.json"
{
  "agent_servers": {
    "OpenCode": {
      "type": "custom",
      "command": "opencode",
      "args": ["acp"]
    }
  }
}

To open it, use the agent: new thread action in the Command Palette.

You can also bind a keyboard shortcut by editing your keymap.json:

json title="keymap.json"
[
  {
    "bindings": {
      "cmd-alt-o": [
        "agent::NewExternalAgentThread",
        {
          "agent": {
            "custom": {
              "name": "OpenCode",
              "command": {
                "command": "opencode",
                "args": ["acp"]
              }
            }
          }
        }
      ]
    }
  }
]

JetBrains IDEs

Add to your JetBrains IDE acp.json according to the documentation:

json title="acp.json"
{
  "agent_servers": {
    "OpenCode": {
      "command": "/absolute/path/bin/opencode",
      "args": ["acp"]
    }
  }
}

To open it, use the new 'OpenCode' agent in the AI Chat agent selector.


Avante.nvim

Add to your Avante.nvim configuration:

lua
{
  acp_providers = {
    ["opencode"] = {
      command = "opencode",
      args = { "acp" }
    }
  }
}

If you need to pass environment variables:

lua {6-8}
{
  acp_providers = {
    ["opencode"] = {
      command = "opencode",
      args = { "acp" },
      env = {
        OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY")
      }
    }
  }
}

CodeCompanion.nvim

To use OpenCode as an ACP agent in CodeCompanion.nvim, add the following to your Neovim config:

lua
require("codecompanion").setup({
  interactions = {
    chat = {
      adapter = {
        name = "opencode",
        model = "claude-sonnet-4",
      },
    },
  },
})

This config sets up CodeCompanion to use OpenCode as the ACP agent for chat.

If you need to pass environment variables (like OPENCODE_API_KEY), refer to Configuring Adapters: Environment Variables in the CodeCompanion.nvim documentation for full details.

Support

OpenCode works the same via ACP as it does in the terminal. All features are supported:

:::note
Some built-in slash commands like /undo and /redo are currently unsupported.
:::

  • Built-in tools (file operations, terminal commands, etc.)
  • Custom tools and slash commands
  • MCP servers configured in your OpenCode config
  • Project-specific rules from AGENTS.md
  • Custom formatters and linters
  • Agents and permissions system

Packages Web Src Content Docs Agents (`packages/web/src/content/docs/agents.mdx`)


title: Agents

Agents are specialized AI assistants that can be configured for specific tasks and workflows. They allow you to create focused tools with custom prompts, models, and tool access.

:::tip
Use the plan agent to analyze code and review suggestions without making any code changes.
:::

You can switch between agents during a session or invoke them with the @ mention.


Types

There are two types of agents in OpenCode; primary agents and subagents.


Primary agents

Primary agents are the main assistants you interact with directly. You can cycle through them using the Tab key, or your configured switch_agent keybind. These agents handle your main conversation. Tool access is configured via permissions — for example, Build has all tools enabled while Plan is restricted.

:::tip
You can use the Tab key to switch between primary agents during a session.
:::

OpenCode comes with two built-in primary agents, Build and Plan. We'll
look at these below.


Subagents

Subagents are specialized assistants that primary agents can invoke for specific tasks. You can also manually invoke them by @ mentioning them in your messages.

OpenCode comes with three built-in subagents, General, Explore, and Scout. We'll look at this below.


Built-in

OpenCode comes with two built-in primary agents and three built-in subagents.


Use build

Mode: primary

Build is the default primary agent with all tools enabled. This is the standard agent for development work where you need full access to file operations and system commands.


Use plan

Mode: primary

A restricted agent designed for planning and analysis. This agent is useful when you want the LLM to analyze code, suggest changes, or create plans without making any actual modifications to your codebase.

By default, Plan:

  • Denies file edits, writes, and patches outside its plan directory, ~/.opencode/plan/. These are refused without prompting.
  • Allows the question tool, so it can ask you clarifying questions.
  • Does not restrict shell commands. They follow your permission config.

Plan's defaults are applied before your top-level permission config, and the last matching rule wins. A global rule such as "edit": "allow" or "*": "allow" therefore also applies to Plan. To keep Plan read-only, or to require approval for its shell commands, set its permissions directly:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "edit": "allow"
  },
  "agent": {
    "plan": {
      "permission": {
        "edit": {
          "*": "deny",
          "~/.opencode/plan/*": "allow"
        },
        "shell": "ask"
      }
    }
  }
}

Use general

Mode: subagent

A general-purpose agent for researching complex questions and executing multi-step tasks. Has full tool access, so it can make file changes when needed. Use this to run multiple units of work in parallel.


Use explore

Mode: subagent

A fast, read-only agent for exploring codebases. Cannot modify files. Use this when you need to quickly find files by patterns, search code for keywords, or answer questions about the codebase.


Use scout

Mode: subagent

A read-only agent for external docs and dependency research. Use this when you need to clone a dependency repository into OpenCode's managed cache, inspect library source, or cross-reference local code against upstream implementations without modifying your workspace.


Use compaction

Mode: primary

Hidden system agent that compacts long context into a smaller summary. It runs automatically when needed and is not selectable in the UI.


Use title

Mode: primary

Hidden system agent that generates short session titles. It runs automatically and is not selectable in the UI.


Use summary

Mode: primary

Hidden system agent that creates session summaries. It runs automatically and is not selectable in the UI.


Usage

  1. For primary agents, use the Tab key to cycle through them during a session. You can also use your configured switch_agent keybind.

  2. Subagents can be invoked:

    • Automatically by primary agents for specialized tasks based on their descriptions.

    • Manually by @ mentioning a subagent in your message. For example.

      txt frame="none"
      @general help me search for this function
  3. Navigation between sessions: When subagents create child sessions, use session_child_first (default: <Leader>+Down) to enter the first child session from the parent.

  4. Once you are in a child session, use:

    • session_child_cycle (default: Right) to cycle to the next child session
    • session_child_cycle_reverse (default: Left) to cycle to the previous child session
    • session_parent (default: Up) to return to the parent session

    This lets you switch between the main conversation and specialized subagent work.


Configure

You can customize the built-in agents or create your own through configuration. Agents can be configured in two ways:


JSON

Configure agents in your opencode.json config file:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "build": {
      "mode": "primary",
      "model": "anthropic/claude-sonnet-4-20250514",
      "prompt": "{file:./prompts/build.txt}",
      "permission": {
        "edit": "allow",
        "shell": "allow"
      }
    },
    "plan": {
      "mode": "primary",
      "model": "anthropic/claude-haiku-4-20250514",
      "permission": {
        "edit": "deny",
        "shell": "deny"
      }
    },
    "code-reviewer": {
      "description": "Reviews code for best practices and potential issues",
      "mode": "subagent",
      "model": "anthropic/claude-sonnet-4-20250514",
      "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.",
      "permission": {
        "edit": "deny"
      }
    }
  }
}

Markdown

You can also define agents using markdown files. Place them in:

  • Global: ~/.config/opencode/agents/
  • Per-project: .opencode/agents/
markdown title="~/.config/opencode/agents/review.md"
---
description: Reviews code for quality and best practices
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.1
permission:
  edit: deny
  shell: deny
---

You are in code review mode. Focus on:

- Code quality and best practices
- Potential bugs and edge cases
- Performance implications
- Security considerations

Provide constructive feedback without making direct changes.

The markdown file name becomes the agent name. For example, review.md creates a review agent.


Options

Let's look at these configuration options in detail.


Description

Use the description option to provide a brief description of what the agent does and when to use it.

json title="opencode.json"
{
  "agent": {
    "review": {
      "description": "Reviews code for best practices and potential issues"
    }
  }
}

This is a required config option.


Temperature

Control the randomness and creativity of the LLM's responses with the temperature config.

Lower values make responses more focused and deterministic, while higher values increase creativity and variability.

json title="opencode.json"
{
  "agent": {
    "plan": {
      "temperature": 0.1
    },
    "creative": {
      "temperature": 0.8
    }
  }
}

Temperature values typically range from 0.0 to 1.0:

  • 0.0-0.2: Very focused and deterministic responses, ideal for code analysis and planning
  • 0.3-0.5: Balanced responses with some creativity, good for general development tasks
  • 0.6-1.0: More creative and varied responses, useful for brainstorming and exploration
json title="opencode.json"
{
  "agent": {
    "analyze": {
      "temperature": 0.1,
      "prompt": "{file:./prompts/analysis.txt}"
    },
    "build": {
      "temperature": 0.3
    },
    "brainstorm": {
      "temperature": 0.7,
      "prompt": "{file:./prompts/creative.txt}"
    }
  }
}

If no temperature is specified, OpenCode uses model-specific defaults; typically 0 for most models, 0.55 for Qwen models.


Max steps

Control the maximum number of agentic iterations an agent can perform before being forced to respond with text only. This allows users who wish to control costs to set a limit on agentic actions.

If this is not set, the agent will continue to iterate until the model chooses to stop or the user interrupts the session.

json title="opencode.json"
{
  "agent": {
    "quick-thinker": {
      "description": "Fast reasoning with limited iterations",
      "prompt": "You are a quick thinker. Solve problems with minimal steps.",
      "steps": 5
    }
  }
}

When the limit is reached, the agent receives a special system prompt instructing it to respond with a summarization of its work and recommended remaining tasks.

:::caution
The legacy maxSteps field is deprecated. Use steps instead.
:::


Disable

Set to true to disable the agent.

json title="opencode.json"
{
  "agent": {
    "review": {
      "disable": true
    }
  }
}

Prompt

Specify a custom system prompt file for this agent with the prompt config. The prompt file should contain instructions specific to the agent's purpose.

json title="opencode.json"
{
  "agent": {
    "review": {
      "prompt": "{file:./prompts/code-review.txt}"
    }
  }
}

This path is relative to where the config file is located. So this works for both the global OpenCode config and the project specific config.


Model

Use the model config to override the model for this agent. Useful for using different models optimized for different tasks. For example, a faster model for planning, a more capable model for implementation.

:::tip
If you don’t specify a model, primary agents use the model globally configured while subagents will use the model of the primary agent that invoked the subagent.
:::

json title="opencode.json"
{
  "agent": {
    "plan": {
      "model": "anthropic/claude-haiku-4-20250514"
    }
  }
}

The model ID in your OpenCode config uses the format provider/model-id. For example, if you're using OpenCode Zen, you would use opencode/gpt-5.1-codex for GPT 5.1 Codex.


Tools (deprecated)

tools is deprecated. Prefer the agent's permission field for new configs, updates and more fine-grained control.

Allows you to control which tools are available in this agent. You can enable or disable specific tools by setting them to true or false. In an agent's tools config, true is equivalent to {"*": "allow"} permission and false is equivalent to {"*": "deny"} permission.

json title="opencode.json" {3-6,9-12}
{
  "$schema": "https://opencode.ai/config.json",
  "tools": {
    "write": true,
    "shell": true
  },
  "agent": {
    "plan": {
      "tools": {
        "write": false,
        "shell": false
      }
    }
  }
}

:::note
The agent-specific config overrides the global config.
:::

You can also use wildcards in legacy tools entries to control multiple tools at once. For example, to disable all tools from an MCP server:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "readonly": {
      "tools": {
        "mymcp_*": false,
        "write": false,
        "edit": false
      }
    }
  }
}

Learn more about tools.


Permissions

You can configure permissions to manage what actions an agent can take. Each permission key can be set to:

  • "ask" — Prompt for approval before running the tool
  • "allow" — Allow all operations without approval
  • "deny" — Disable the tool

The available permission keys are:

Key Tools it gates
read read
edit write, edit, apply_patch
glob glob
grep grep
list list
shell shell
task task
external_directory Any tool that reads or writes files outside the project worktree
webfetch webfetch
websearch websearch
lsp lsp
skill skill
question question
doom_loop Recovery prompts when an agent appears stuck

read, edit, glob, grep, list, shell, task, external_directory, lsp, and skill accept either a shorthand action ("allow" | "ask" | "deny") or an object of glob/pattern → action for fine-grained control. The remaining keys accept the shorthand action only.

:::note
Permission keys are matched as wildcard patterns against the underlying tool name, so the same syntax works for built-ins, custom tools, and MCP tools — for example "mymcp_*": "deny" denies every tool from an MCP server, and "mymcp_search": "ask" targets a single one.
:::

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "edit": "deny"
  }
}

You can override these permissions per agent.

json title="opencode.json" {3-5,8-10}
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "edit": "deny"
  },
  "agent": {
    "build": {
      "permission": {
        "edit": "ask"
      }
    }
  }
}

You can also set permissions in Markdown agents.

markdown title="~/.config/opencode/agents/review.md"
---
description: Code review without edits
mode: subagent
permission:
  edit: deny
  shell:
    "*": ask
    "git diff": allow
    "git log*": allow
    "grep *": allow
  webfetch: deny
---

Only analyze code and suggest changes.

You can set permissions for specific shell commands.

json title="opencode.json" {7}
{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "build": {
      "permission": {
        "shell": {
          "git push": "ask",
          "grep *": "allow"
        }
      }
    }
  }
}

This can take a glob pattern.

json title="opencode.json" {7}
{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "build": {
      "permission": {
        "shell": {
          "git *": "ask"
        }
      }
    }
  }
}

And you can also use the * wildcard to manage permissions for all commands.
Since the last matching rule takes precedence, put the * wildcard first and specific rules after.

json title="opencode.json" {8}
{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "build": {
      "permission": {
        "shell": {
          "*": "ask",
          "git status *": "allow"
        }
      }
    }
  }
}

Learn more about permissions.


Mode

Control the agent's mode with the mode config. The mode option is used to determine how the agent can be used.

json title="opencode.json"
{
  "agent": {
    "review": {
      "mode": "subagent"
    }
  }
}

The mode option can be set to primary, subagent, or all. If no mode is specified, it defaults to all.


Hidden

Hide a subagent from the @ autocomplete menu with hidden: true. Useful for internal subagents that should only be invoked programmatically by other agents via the Task tool.

json title="opencode.json"
{
  "agent": {
    "internal-helper": {
      "mode": "subagent",
      "hidden": true
    }
  }
}

This only affects user visibility in the autocomplete menu. Hidden agents can still be invoked by the model via the Task tool if permissions allow.

:::note
Only applies to mode: subagent agents.
:::


Task permissions

Control which subagents an agent can invoke via the Task tool with permission.task. Uses glob patterns for flexible matching.

json title="opencode.json"
{
  "agent": {
    "orchestrator": {
      "mode": "primary",
      "permission": {
        "task": {
          "*": "deny",
          "orchestrator-*": "allow",
          "code-reviewer": "ask"
        }
      }
    }
  }
}

When set to deny, the subagent is removed from the Task tool description entirely, so the model won't attempt to invoke it.

:::tip
Rules are evaluated in order, and the last matching rule wins. In the example above, orchestrator-planner matches both * (deny) and orchestrator-* (allow), but since orchestrator-* comes after *, the result is allow.
:::

:::tip
Users can always invoke any subagent directly via the @ autocomplete menu, even if the agent's task permissions would deny it.
:::


Color

Customize the agent's visual appearance in the UI with the color option. This affects how the agent appears in the interface.

Use a valid hex color (e.g., #FF5733) or theme color: primary, secondary, accent, success, warning, error, info.

json title="opencode.json"
{
  "agent": {
    "creative": {
      "color": "#ff6b6b"
    },
    "code-reviewer": {
      "color": "accent"
    }
  }
}

Top P

Control response diversity with the top_p option. Alternative to temperature for controlling randomness.

json title="opencode.json"
{
  "agent": {
    "brainstorm": {
      "top_p": 0.9
    }
  }
}

Values range from 0.0 to 1.0. Lower values are more focused, higher values more diverse.


Additional

Any other options you specify in your agent configuration will be passed through directly to the provider as model options. This allows you to use provider-specific features and parameters.

For example, with OpenAI's reasoning models, you can control the reasoning effort:

json title="opencode.json" {6,7}
{
  "agent": {
    "deep-thinker": {
      "description": "Agent that uses high reasoning effort for complex problems",
      "model": "openai/gpt-5",
      "reasoningEffort": "high",
      "textVerbosity": "low"
    }
  }
}

These additional options are model and provider-specific. Check your provider's documentation for available parameters.

:::tip
Run opencode models to see a list of the available models.
:::


Create agents

Create a new agent by adding a markdown file to .opencode/agents/ for the project or ~/.config/opencode/agents/ globally. The file name becomes the agent name, and the frontmatter configures its description, mode, model, and permissions. See Markdown above for the file format.

Run opencode debug agents to list the agents that OpenCode has loaded.


Use cases

Here are some common use cases for different agents.

  • Build agent: Full development work with all tools enabled
  • Plan agent: Analysis and planning without making changes
  • Review agent: Code review with read-only access plus documentation tools
  • Debug agent: Focused on investigation with shell and read tools enabled
  • Docs agent: Documentation writing with file operations but no system commands

Examples

Here are some example agents you might find useful.

:::tip
Do you have an agent you'd like to share? Submit a PR.
:::


Documentation agent

markdown title="~/.config/opencode/agents/docs-writer.md"
---
description: Writes and maintains project documentation
mode: subagent
permission:
  shell: deny
---

You are a technical writer. Create clear, comprehensive documentation.

Focus on:

- Clear explanations
- Proper structure
- Code examples
- User-friendly language

Security auditor

markdown title="~/.config/opencode/agents/security-auditor.md"
---
description: Performs security audits and identifies vulnerabilities
mode: subagent
permission:
  edit: deny
---

You are a security expert. Focus on identifying potential security issues.

Look for:

- Input validation vulnerabilities
- Authentication and authorization flaws
- Data exposure risks
- Dependency vulnerabilities
- Configuration security issues

Packages Web Src Content Docs Cli (`packages/web/src/content/docs/cli.mdx`)


title: CLI

import { Tabs, TabItem } from "@astrojs/starlight/components"

The OpenCode CLI by default starts the TUI when run without any arguments.

bash
opencode

But it also accepts commands as documented on this page. This allows you to interact with OpenCode programmatically.

bash
opencode run "Explain how closures work in JavaScript"

tui

Start the OpenCode terminal user interface.

bash
opencode [project]

Flags

Flag Short Description
{"--continue"} -c Continue the last session
{"--session"} -s Session ID to continue
{"--fork"} Fork the session when continuing (use with --continue or --session)
{"--prompt"} Prompt to use
{"--model"} -m Model to use in the form of provider/model
{"--agent"} Agent to use
{"--auto"} Auto-approve permissions that are not explicitly denied
{"--port"} Port to listen on
{"--hostname"} Hostname to listen on
{"--mdns"} Enable mDNS discovery
{"--mdns-domain"} Custom mDNS domain name
{"--cors"} Additional browser origin(s) to allow CORS

Commands

The OpenCode CLI also has the following commands.


attach

Attach a terminal to an already running OpenCode backend server started via serve or web commands.

bash
opencode attach [url]

This allows using the TUI with a remote OpenCode backend. For example:

bash
# Start the backend server for web/mobile access
opencode web --port 4096 --hostname 0.0.0.0

# In another terminal, attach the TUI to the running backend
opencode attach http://10.20.30.40:4096

Flags

Flag Short Description
{"--dir"} Working directory to start TUI in
{"--continue"} -c Continue the last session
{"--session"} -s Session ID to continue
{"--fork"} Fork the session when continuing (use with --continue or --session)
{"--password"} -p Basic auth password (defaults to OPENCODE_SERVER_PASSWORD)
{"--username"} -u Basic auth username (defaults to OPENCODE_SERVER_USERNAME or opencode)

auth

Command to manage credentials and login for providers.

bash
opencode auth [command]

login

OpenCode is powered by the provider list at Models.dev, so you can use opencode auth login to configure API keys for any provider you'd like to use. This is stored in ~/.local/share/opencode/auth.json.

bash
opencode auth login

When OpenCode starts up it loads the providers from the credentials file. And if there are any keys defined in your environments or a .env file in your project.

Flags

Flag Short Description
{"--provider"} -p Provider ID or name to log in to
{"--method"} -m Login method label to use, skipping method selection

list

Lists all the authenticated providers as stored in the credentials file.

bash
opencode auth list

Or the short version.

bash
opencode auth ls

logout

Logs you out of a provider by clearing it from the credentials file.

bash
opencode auth logout

github

Manage the GitHub agent for repository automation.

bash
opencode github [command]

install

Install the GitHub agent in your repository.

bash
opencode github install

This sets up the necessary GitHub Actions workflow and guides you through the configuration process. Learn more.


run

Run the GitHub agent. This is typically used in GitHub Actions.

bash
opencode github run

Flags

Flag Description
{"--event"} GitHub mock event to run the agent for
{"--token"} GitHub personal access token

mcp

Manage Model Context Protocol servers.

bash
opencode mcp [command]

add

Add an MCP server to your configuration.

bash
opencode mcp add

This command will guide you through adding either a local or remote MCP server.


list

List all configured MCP servers and their connection status.

bash
opencode mcp list

Or use the short version.

bash
opencode mcp ls

auth

Authenticate with an OAuth-enabled MCP server.

bash
opencode mcp auth [name]

If you don't provide a server name, you'll be prompted to select from available OAuth-capable servers.

You can also list OAuth-capable servers and their authentication status.

bash
opencode mcp auth list

Or use the short version.

bash
opencode mcp auth ls

logout

Remove OAuth credentials for an MCP server.

bash
opencode mcp logout [name]

debug

Debug OAuth connection issues for an MCP server.

bash
opencode mcp debug <name>

models

List all available models from configured providers.

bash
opencode models [provider]

This command displays all models available across your configured providers in the format provider/model.

This is useful for figuring out the exact model name to use in your config.

You can optionally pass a provider ID to filter models by that provider.

bash
opencode models anthropic

Flags

Flag Description
{"--refresh"} Refresh the models cache from models.dev
{"--verbose"} Use more verbose model output (includes metadata like costs)

Use the --refresh flag to update the cached model list. This is useful when new models have been added to a provider and you want to see them in OpenCode.

bash
opencode models --refresh

run

Run opencode in non-interactive mode by passing a prompt directly.

bash
opencode run [message..]

This is useful for scripting, automation, or when you want a quick answer without launching the full TUI. For example.

bash "opencode run"
opencode run Explain the use of context in Go

You can also attach to a running opencode serve instance to avoid MCP server cold boot times on every run:

bash
# Start a headless server in one terminal
opencode serve

# In another terminal, run commands that attach to it
opencode run --attach http://localhost:4096 "Explain async/await in JavaScript"

Flags

Flag Short Description
{"--command"} The command to run, use message for args
{"--continue"} -c Continue the last session
{"--session"} -s Session ID to continue
{"--fork"} Fork the session when continuing (use with --continue or --session)
{"--model"} -m Model to use in the form of provider/model
{"--agent"} Agent to use
{"--file"} -f File(s) to attach to message
{"--format"} Format: default (formatted) or json (raw JSON events)
{"--title"} Title for the session (uses truncated prompt if no value provided)
{"--attach"} Attach to a running opencode server (e.g., http://localhost:4096)
{"--password"} -p Basic auth password (defaults to OPENCODE_SERVER_PASSWORD)
{"--username"} -u Basic auth username (defaults to OPENCODE_SERVER_USERNAME or opencode)
{"--dir"} Directory to run in, or path on the remote server when attaching
{"--port"} Port for the local server (defaults to random port)
{"--variant"} Model variant (provider-specific reasoning effort)
{"--thinking"} Show thinking blocks
{"--auto"} Auto-approve permissions that are not explicitly denied

serve

Start a headless OpenCode server for API access. Check out the server docs for the full HTTP interface.

bash
opencode serve

This starts an HTTP server that provides API access to opencode functionality without the TUI interface. Set OPENCODE_SERVER_PASSWORD to enable HTTP basic auth (username defaults to opencode).

Flags

Flag Description
{"--port"} Port to listen on
{"--hostname"} Hostname to listen on
{"--mdns"} Enable mDNS discovery
{"--mdns-domain"} Custom mDNS domain name
{"--cors"} Additional browser origin(s) to allow CORS

session

Manage OpenCode sessions.

bash
opencode session [command]

list

List all OpenCode sessions.

bash
opencode session list

Flags

Flag Short Description
{"--max-count"} -n Limit to N most recent sessions
{"--format"} Output format: table or json (table)

delete

Delete an OpenCode session.

bash
opencode session delete <sessionID>

stats

Show token usage and cost statistics for your OpenCode sessions.

bash
opencode stats

Flags

Flag Description
{"--days"} Show stats for the last N days (all time)
{"--tools"} Number of tools to show (all)
{"--models"} Show model usage breakdown (hidden by default). Pass a number to show top N
{"--project"} Filter by project (all projects, empty string: current project)

export

Export session data as JSON.

bash
opencode export [sessionID]

If you don't provide a session ID, you'll be prompted to select from available sessions.

Flags

Flag Description
{"--sanitize"} Redact sensitive transcript/file data

import

Import session data from a JSON file.

bash
opencode import <file>
bash
opencode import session.json

web

Start a headless OpenCode server with a web interface.

bash
opencode web

This starts an HTTP server and opens a web browser to access OpenCode through a web interface. Set OPENCODE_SERVER_PASSWORD to enable HTTP basic auth (username defaults to opencode).

Flags

Flag Description
{"--port"} Port to listen on
{"--hostname"} Hostname to listen on
{"--mdns"} Enable mDNS discovery
{"--mdns-domain"} Custom mDNS domain name
{"--cors"} Additional browser origin(s) to allow CORS

acp

Start an ACP (Agent Client Protocol) server.

bash
opencode acp

This command starts an ACP server that communicates via stdin/stdout using nd-JSON.

Flags

Flag Description
{"--cwd"} Working directory
{"--port"} Port to listen on
{"--hostname"} Hostname to listen on
{"--mdns"} Enable mDNS discovery
{"--mdns-domain"} Custom mDNS domain name
{"--cors"} Additional browser origin(s) to allow CORS

plugin

Install a plugin and update your config.

bash
opencode plugin <module>

Or use the alias.

bash
opencode plug <module>

Flags

Flag Short Description
{"--global"} -g Install in global config
{"--force"} -f Replace existing plugin version

pr

Fetch and checkout a GitHub PR branch, then run OpenCode.

bash
opencode pr <number>

db

Database tools.

bash
opencode db [query]

Flags

Flag Description
{"--format"} Output format: json or tsv

path

Print the database path.

bash
opencode db path

debug

Debugging and troubleshooting tools.

bash
opencode debug [command]

agents

List all agents.

bash
opencode debug agents

config

List configuration sources.

bash
opencode debug config

paths

Show global paths (data, config, cache, state).

bash
opencode debug paths

Pass a name to print a single path: db, home, data, config, cache, state, tmp, bin, log or repos.

bash
opencode debug paths db

uninstall

Uninstall OpenCode and remove all related files.

bash
opencode uninstall

Flags

Flag Short Description
{"--keep-config"} -c Keep configuration files
{"--keep-data"} -d Keep session data and snapshots
{"--dry-run"} Show what would be removed without removing
{"--force"} -f Skip confirmation prompts

upgrade

Updates opencode to the latest version or a specific version.

bash
opencode upgrade [target]

To upgrade to the latest version.

bash
opencode upgrade

To upgrade to a specific version.

bash
opencode upgrade v0.1.48

Flags

Flag Short Description
{"--method"} -m The installation method that was used; curl, npm, pnpm, bun, brew

Global Flags

The opencode CLI takes the following global flags.

Flag Short Description
{"--help"} -h Display help
{"--version"} -v Print version number
{"--print-logs"} Print logs to stderr
{"--log-level"} Log level (DEBUG, INFO, WARN, ERROR)
{"--pure"} Run without external plugins

Environment variables

OpenCode can be configured using environment variables.

Variable Type Description
OPENCODE_GIT_BASH_PATH string Path to Git Bash executable on Windows
OPENCODE_CONFIG string Path to config file
OPENCODE_TUI_CONFIG string Path to TUI config file
OPENCODE_CONFIG_DIR string Path to config directory
OPENCODE_CONFIG_CONTENT string Inline json config content
OPENCODE_DISABLE_AUTOUPDATE boolean Disable automatic update checks
OPENCODE_DISABLE_PRUNE boolean Disable pruning of old data
OPENCODE_DISABLE_TERMINAL_TITLE boolean Disable automatic terminal title updates
OPENCODE_PERMISSION string Inlined json permissions config
OPENCODE_DISABLE_DEFAULT_PLUGINS boolean Disable default plugins
OPENCODE_DISABLE_LSP_DOWNLOAD boolean Disable automatic LSP server downloads
OPENCODE_ENABLE_EXPERIMENTAL_MODELS boolean Enable experimental models
OPENCODE_DISABLE_AUTOCOMPACT boolean Disable automatic context compaction
OPENCODE_DISABLE_CLAUDE_CODE boolean Disable reading from .claude (prompt + skills)
OPENCODE_DISABLE_CLAUDE_CODE_PROMPT boolean Disable reading ~/.claude/CLAUDE.md
OPENCODE_DISABLE_CLAUDE_CODE_SKILLS boolean Disable loading .claude/skills
OPENCODE_DISABLE_MODELS_FETCH boolean Disable fetching models from remote sources
OPENCODE_DISABLE_MOUSE boolean Disable mouse capture in the TUI
OPENCODE_FAKE_VCS string Fake VCS provider for testing purposes
OPENCODE_CLIENT string Client identifier (defaults to cli)
OPENCODE_ENABLE_EXA boolean Enable Exa web search tools
OPENCODE_ENABLE_PARALLEL boolean Enable Parallel web search tools
OPENCODE_SERVER_PASSWORD string Enable basic auth for serve/web
OPENCODE_SERVER_USERNAME string Override basic auth username (default opencode)
OPENCODE_MODELS_URL string Custom URL for fetching models configuration

Experimental

These environment variables enable experimental features that may change or be removed.

Variable Type Description
OPENCODE_EXPERIMENTAL boolean Enable the experimental umbrella flag
OPENCODE_EXPERIMENTAL_ICON_DISCOVERY boolean Enable icon discovery
OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT boolean Disable copy on select in TUI
OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS number Default timeout for bash commands in ms
OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX number Max output tokens for LLM responses
OPENCODE_EXPERIMENTAL_FILEWATCHER boolean Enable file watcher for entire dir
OPENCODE_EXPERIMENTAL_OXFMT boolean Enable oxfmt formatter
OPENCODE_EXPERIMENTAL_LSP_TOOL boolean Enable experimental LSP tool
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER boolean Disable file watcher
OPENCODE_EXPERIMENTAL_EXA boolean Enable experimental Exa features
OPENCODE_EXPERIMENTAL_LSP_TY boolean Enable TY LSP for python files
OPENCODE_EXPERIMENTAL_PLAN_MODE boolean Enable plan mode
OPENCODE_EXPERIMENTAL_EVENT_SYSTEM boolean Enable experimental event system
OPENCODE_EXPERIMENTAL_NATIVE_LLM boolean Enable native LLM request path
OPENCODE_EXPERIMENTAL_PARALLEL boolean Enable parallel web search execution
OPENCODE_EXPERIMENTAL_SCOUT boolean Enable Scout subagent
OPENCODE_EXPERIMENTAL_WORKSPACES boolean Enable workspace support

Packages Web Src Content Docs Commands (`packages/web/src/content/docs/commands.mdx`)


title: Commands

Custom commands let you specify a prompt you want to run when that command is executed in the TUI.

bash frame="none"
/my-command

Custom commands are in addition to the built-in commands like /init, /undo, /redo, /help. Learn more.


Create command files

Create markdown files in the commands/ directory to define custom commands.

Create .opencode/commands/test.md:

md title=".opencode/commands/test.md"
---
description: Run tests with coverage
agent: build
model: anthropic/claude-3-5-sonnet-20241022
---

Run the full test suite with coverage report and show any failures.
Focus on the failing tests and suggest fixes.

The frontmatter defines command properties. The content becomes the template.

Use the command by typing / followed by the command name.

bash frame="none"
"/test"

Configure

You can add custom commands through the OpenCode config or by creating markdown files in the commands/ directory.


JSON

Use the command option in your OpenCode config:

json title="opencode.jsonc" {4-12}
{
  "$schema": "https://opencode.ai/config.json",
  "command": {
    // This becomes the name of the command
    "test": {
      // This is the prompt that will be sent to the LLM
      "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.",
      // This is shown as the description in the TUI
      "description": "Run tests with coverage",
      "agent": "build",
      "model": "anthropic/claude-3-5-sonnet-20241022"
    }
  }
}

Now you can run this command in the TUI:

bash frame="none"
/test

Markdown

You can also define commands using markdown files. Place them in:

  • Global: ~/.config/opencode/commands/
  • Per-project: .opencode/commands/
markdown title="~/.config/opencode/commands/test.md"
---
description: Run tests with coverage
agent: build
model: anthropic/claude-3-5-sonnet-20241022
---

Run the full test suite with coverage report and show any failures.
Focus on the failing tests and suggest fixes.

The markdown file name becomes the command name. For example, test.md lets
you run:

bash frame="none"
/test

Prompt config

The prompts for the custom commands support several special placeholders and syntax.


Arguments

Pass arguments to commands using the $ARGUMENTS placeholder.

md title=".opencode/commands/component.md"
---
description: Create a new component
---

Create a new React component named $ARGUMENTS with TypeScript support.
Include proper typing and basic structure.

Run the command with arguments:

bash frame="none"
/component Button

And $ARGUMENTS will be replaced with Button.

You can also access individual arguments using positional parameters:

  • $1 - First argument
  • $2 - Second argument
  • $3 - Third argument
  • And so on...

For example:

md title=".opencode/commands/create-file.md"
---
description: Create a new file with content
---

Create a file named $1 in the directory $2
with the following content: $3

Run the command:

bash frame="none"
/create-file config.json src "{ \"key\": \"value\" }"

This replaces:

  • $1 with config.json
  • $2 with src
  • $3 with { "key": "value" }

Shell output

Use !command to inject shell command output into your prompt.

For example, to create a custom command that analyzes test coverage:

md title=".opencode/commands/analyze-coverage.md"
---
description: Analyze test coverage
---

Here are the current test results:
!`npm test`

Based on these results, suggest improvements to increase coverage.

Or to review recent changes:

md title=".opencode/commands/review-changes.md"
---
description: Review recent changes
---

Recent git commits:
!`git log --oneline -10`

Review these changes and suggest any improvements.

Commands run in your project's root directory and their output becomes part of the prompt.


File references

Include files in your command using @ followed by the filename.

md title=".opencode/commands/review-component.md"
---
description: Review component
---

Review the component in @src/components/Button.tsx.
Check for performance issues and suggest improvements.

The file content gets included in the prompt automatically.


Options

Let's look at the configuration options in detail.


Template

The template option defines the prompt that will be sent to the LLM when the command is executed.

json title="opencode.json"
{
  "command": {
    "test": {
      "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes."
    }
  }
}

This is a required config option.


Description

Use the description option to provide a brief description of what the command does.

json title="opencode.json"
{
  "command": {
    "test": {
      "description": "Run tests with coverage"
    }
  }
}

This is shown as the description in the TUI when you type in the command.


Agent

Use the agent config to optionally specify which agent should execute this command.
If this is a subagent the command will trigger a subagent invocation by default.
To disable this behavior, set subtask to false.

json title="opencode.json"
{
  "command": {
    "review": {
      "agent": "plan"
    }
  }
}

This is an optional config option. If not specified, defaults to your current agent.


Subtask

Use the subtask boolean to force the command to trigger a subagent invocation.
This is useful if you want the command to not pollute your primary context and will force the agent to act as a subagent,
even if mode is set to primary on the agent configuration.

json title="opencode.json"
{
  "command": {
    "analyze": {
      "subtask": true
    }
  }
}

This is an optional config option.


Model

Use the model config to override the default model for this command.

json title="opencode.json"
{
  "command": {
    "analyze": {
      "model": "anthropic/claude-3-5-sonnet-20241022"
    }
  }
}

This is an optional config option.


Built-in

opencode includes several built-in commands like /init, /undo, /redo, /help; learn more.

:::note
Custom commands can override built-in commands.
:::

If you define a custom command with the same name, it will override the built-in command.


Packages Web Src Content Docs Config (`packages/web/src/content/docs/config.mdx`)


title: Config

You can configure OpenCode using a JSON config file.


Format

OpenCode supports both JSON and JSONC (JSON with Comments) formats.

jsonc title="opencode.jsonc"
{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-5",
  "autoupdate": true,
  "server": {
    "port": 4096,
  },
}

Locations

You can place your config in a couple of different locations and they have a
different order of precedence.

:::note
Configuration files are merged together, not replaced.
:::

Configuration files are merged together, not replaced. Settings from the following config locations are combined. Later configs override earlier ones only for conflicting keys. Non-conflicting settings from all configs are preserved.

For example, if your global config sets autoupdate: true and your project config sets model: "anthropic/claude-sonnet-4-5", the final configuration will include both settings.


Precedence order

Config sources are loaded in this order (later sources override earlier ones):

  1. Remote config (from .well-known/opencode) - organizational defaults
  2. Global config (~/.config/opencode/opencode.json) - user preferences
  3. Custom config (OPENCODE_CONFIG env var) - custom overrides
  4. Project config (opencode.json in project) - project-specific settings
  5. .opencode directories - agents, commands, plugins
  6. Inline config (OPENCODE_CONFIG_CONTENT env var) - runtime overrides
  7. Managed config files (/Library/Application Support/opencode/ on macOS) - admin-controlled
  8. macOS managed preferences (.mobileconfig via MDM) - highest priority, not user-overridable

This means project configs can override global defaults, and global configs can override remote organizational defaults. Managed settings override everything.

:::note
The .opencode and ~/.config/opencode directories use plural names for subdirectories: agents/, commands/, modes/, plugins/, skills/, tools/, and themes/. Singular names (e.g., agent/) are also supported for backwards compatibility.
:::


Remote

Organizations can provide default configuration via the .well-known/opencode endpoint. This is fetched automatically when you authenticate with a provider that supports it.

Remote config is loaded first, serving as the base layer. All other config sources (global, project) can override these defaults.

For example, if your organization provides MCP servers that are disabled by default:

json title="remote config from .well-known/opencode"
{
  "mcp": {
    "jira": {
      "type": "remote",
      "url": "https://jira.example.com/mcp",
      "enabled": false
    }
  }
}

You can enable specific servers in your local config:

json title="opencode.json"
{
  "mcp": {
    "jira": {
      "type": "remote",
      "url": "https://jira.example.com/mcp",
      "enabled": true
    }
  }
}

Global

Place your global OpenCode config in ~/.config/opencode/opencode.json. Use global config for user-wide server/runtime preferences like providers, models, and permissions.

For TUI-specific settings, use ~/.config/opencode/tui.json.

Global config overrides remote organizational defaults.


Per project

Add opencode.json in your project root. Project config has the highest precedence among standard config files - it overrides both global and remote configs.

For project-specific TUI settings, add tui.json alongside it.

:::tip
Place project specific config in the root of your project.
:::

When OpenCode starts up, it first looks for a config file in the current directory, then traverses up to the nearest Git directory.

This is also safe to be checked into Git and uses the same schema as the global one.


Custom path

Specify a custom config file path using the OPENCODE_CONFIG environment variable.

bash
export OPENCODE_CONFIG=/path/to/my/custom-config.json
opencode run "Hello world"

Custom config is loaded between global and project configs in the precedence order.


Custom directory

Specify a custom config directory using the OPENCODE_CONFIG_DIR
environment variable. This directory will be searched for agents, commands,
modes, and plugins just like the standard .opencode directory, and should
follow the same structure.

bash
export OPENCODE_CONFIG_DIR=/path/to/my/config-directory
opencode run "Hello world"

The custom directory is loaded after the global config and .opencode directories, so it can override their settings.


Managed settings

Organizations can enforce configuration that users cannot override. Managed settings are loaded at the highest priority tier.

File-based

Drop an opencode.json or opencode.jsonc file in the system managed config directory:

Platform Path
macOS /Library/Application Support/opencode/
Linux /etc/opencode/
Windows %ProgramData%\opencode

These directories require admin/root access to write, so users cannot modify them.

macOS managed preferences

On macOS, OpenCode reads managed preferences from the ai.opencode.managed preference domain. Deploy a .mobileconfig via MDM (Jamf, Kandji, FleetDM) and the settings are enforced automatically.

OpenCode checks these paths:

  1. /Library/Managed Preferences//ai.opencode.managed.plist
  2. /Library/Managed Preferences/ai.opencode.managed.plist

The plist keys map directly to opencode.json fields. MDM metadata keys (PayloadUUID, PayloadType, etc.) are stripped automatically.

Creating a .mobileconfig

Use the ai.opencode.managed PayloadType. The OpenCode config keys go directly in the payload dict:

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>PayloadContent</key>
  <array>
    <dict>
      <key>PayloadType</key>
      <string>ai.opencode.managed</string>
      <key>PayloadIdentifier</key>
      <string>com.example.opencode.config</string>
      <key>PayloadUUID</key>
      <string>GENERATE-YOUR-OWN-UUID</string>
      <key>PayloadVersion</key>
      <integer>1</integer>
      <key>server</key>
      <dict>
        <key>hostname</key>
        <string>127.0.0.1</string>
      </dict>
      <key>permission</key>
      <dict>
        <key>*</key>
        <string>ask</string>
        <key>shell</key>
        <dict>
          <key>*</key>
          <string>ask</string>
          <key>rm -rf *</key>
          <string>deny</string>
        </dict>
      </dict>
    </dict>
  </array>
  <key>PayloadType</key>
  <string>Configuration</string>
  <key>PayloadIdentifier</key>
  <string>com.example.opencode</string>
  <key>PayloadUUID</key>
  <string>GENERATE-YOUR-OWN-UUID</string>
  <key>PayloadVersion</key>
  <integer>1</integer>
</dict>
</plist>

Generate unique UUIDs with uuidgen. Customize the settings to match your organization's requirements.

Deploying via MDM

  • Jamf Pro: Computers > Configuration Profiles > Upload > scope to target devices or smart groups
  • FleetDM: Add the .mobileconfig to your gitops repo under mdm.macos_settings.custom_settings and run fleetctl apply

Verifying on a device

Double-click the .mobileconfig to install locally for testing (shows in System Settings > Privacy & Security > Profiles), then run:

bash
opencode debug config

All managed preference keys appear in the resolved config and cannot be overridden by user or project configuration.


Schema

The server/runtime config schema is defined in opencode.ai/config.json.

TUI config uses opencode.ai/tui.json.

Your editor should be able to validate and autocomplete based on the schema.


TUI

Use a dedicated tui.json (or tui.jsonc) file for TUI-specific settings.

json title="tui.json"
{
  "$schema": "https://opencode.ai/tui.json",
  "scroll_speed": 3,
  "scroll_acceleration": {
    "enabled": true
  },
  "diff_style": "auto",
  "cursor": {
    "style": "block",
    "blinking": true
  },
  "mouse": true,
  "attention": {
    "enabled": true,
    "notifications": true,
    "sound": true,
    "volume": 0.4
  }
}

Use OPENCODE_TUI_CONFIG to point to a custom TUI config file.

When cursor.style is "default", the terminal default cursor is restored, so cursor.blinking has no effect.

Set attention.enabled to turn on TUI desktop notifications and sounds. See TUI attention.

Legacy theme, keybinds, and tui keys in opencode.json are deprecated and automatically migrated when possible.


Server

You can configure server settings for the opencode serve and opencode web commands through the server option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "server": {
    "port": 4096,
    "hostname": "0.0.0.0",
    "mdns": true,
    "mdnsDomain": "myproject.local",
    "cors": ["http://localhost:5173"]
  }
}

Available options:

  • port - Port to listen on.
  • hostname - Hostname to listen on. When mdns is enabled and no hostname is set, defaults to 0.0.0.0.
  • mdns - Enable mDNS service discovery. This allows other devices on the network to discover your OpenCode server.
  • mdnsDomain - Custom domain name for mDNS service. Defaults to opencode.local. Useful for running multiple instances on the same network.
  • cors - Additional origins to allow for CORS when using the HTTP server from a browser-based client. Values must be full origins (scheme + host + optional port), eg https://app.example.com.

Learn more about the server here.


Shell

You can configure the shell used for the interactive terminal using the shell option. Compatible shells are also used for agent tool calls.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "shell": "pwsh"
}

If not specified, OpenCode will automatically discover and use a sensible default based on your operating system (e.g. pwsh or cmd.exe on Windows, /bin/zsh or /bin/bash on macOS/Linux). You can provide an absolute path or a short name.


Tools

You can manage the tools an LLM can use through the tools option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "tools": {
    "write": false,
    "shell": false
  }
}

Learn more about tools here.


Models

You can configure the providers and models you want to use in your OpenCode config through the provider, model and small_model options.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {},
  "model": "anthropic/claude-sonnet-4-5",
  "small_model": "anthropic/claude-haiku-4-5"
}

The small_model option configures a separate model for lightweight tasks like title generation. By default, OpenCode tries to use a cheaper model if one is available from your provider, otherwise it falls back to your main model.

Provider options can include timeout, headerTimeout, chunkTimeout, and setCacheKey:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "anthropic": {
      "options": {
        "timeout": 600000,
        "chunkTimeout": 30000,
        "setCacheKey": true
      }
    }
  }
}
  • timeout - Request timeout in milliseconds (default: 300000). Set to false to disable.
  • headerTimeout - Timeout in milliseconds to wait for response headers (default: 300000, or 5 minutes). This timer stops once headers arrive and does not limit the streamed response body. Set to false to disable.
  • chunkTimeout - Timeout in milliseconds between streamed response chunks (default: 900000, or 15 minutes). If no chunk arrives in time, the request is aborted. Set to false to disable.
  • setCacheKey - Ensure a cache key is always set for designated provider.

You can also configure local models. Learn more.


Policies

Use the experimental.policies option to allow or deny OpenCode actions on configured resources. Currently, policies can control which providers OpenCode may use.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "experimental": {
    "policies": [
      {
        "effect": "deny",
        "action": "provider.use",
        "resource": "openai"
      }
    ]
  }
}

Learn more about policies here.


Image attachments

OpenCode normalizes image attachments before sending them to the model. By default, images are resized when they exceed 2000x2000 pixels or 5242880 base64 bytes.

Configure image attachment limits with the attachment.image option:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "attachment": {
    "image": {
      "auto_resize": true,
      "max_width": 2000,
      "max_height": 2000,
      "max_base64_bytes": 5242880
    }
  }
}
  • auto_resize - Resize images that exceed the configured limits before provider requests. Set to false to reject oversized images instead.
  • max_width - Maximum image width in pixels before resizing or rejection.
  • max_height - Maximum image height in pixels before resizing or rejection.
  • max_base64_bytes - Maximum encoded image payload size. This is the base64 payload size, not the original file size.

If an image still cannot fit after resizing, OpenCode omits oversized tool-result images or fails oversized user-provided images with an image size error.


Provider-Specific Options

Some providers support additional configuration options beyond the generic timeout and apiKey settings.

Amazon Bedrock

Amazon Bedrock supports AWS-specific configuration:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "amazon-bedrock": {
      "options": {
        "region": "us-east-1",
        "profile": "my-aws-profile",
        "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com"
      }
    }
  }
}
  • region - AWS region for Bedrock (defaults to AWS_REGION env var or us-east-1)
  • profile - AWS named profile from ~/.aws/credentials (defaults to AWS_PROFILE env var)
  • endpoint - Custom endpoint URL for VPC endpoints. This is an alias for the generic baseURL option using AWS-specific terminology. If both are specified, endpoint takes precedence.

:::note
Bearer tokens (AWS_BEARER_TOKEN_BEDROCK or /connect) take precedence over profile-based authentication. See authentication precedence for details.
:::

Learn more about Amazon Bedrock configuration.


Themes

Set your UI theme in tui.json.

json title="tui.json"
{
  "$schema": "https://opencode.ai/tui.json",
  "theme": "tokyonight"
}

Learn more here.


Agents

You can configure specialized agents for specific tasks through the agent option.

jsonc title="opencode.jsonc"
{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "code-reviewer": {
      "description": "Reviews code for best practices and potential issues",
      "model": "anthropic/claude-sonnet-4-5",
      "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.",
      "tools": {
        // Disable file modification tools for review-only agent
        "write": false,
        "edit": false,
      },
    },
  },
}

You can also define agents using markdown files in ~/.config/opencode/agents/ or .opencode/agents/. Learn more here.


Default agent

You can set the default agent using the default_agent option. This determines which agent is used when none is explicitly specified.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "default_agent": "plan"
}

The default agent must be a primary agent (not a subagent). This can be a built-in agent like "build" or "plan", or a custom agent you've defined. If the specified agent doesn't exist or is a subagent, OpenCode will fall back to "build" with a warning.

This setting applies across all interfaces: TUI, CLI (opencode run), desktop app, and GitHub Action.


Subagent depth

You can control how deeply subagents can invoke other subagents using the subagent_depth option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "subagent_depth": 2
}

The default is 1, which allows primary agents to launch subagents but prevents those subagents from launching additional subagents. Set it to 2 to allow one additional level of nested subagents, or 0 to prevent all subagent launches.


Commands

You can configure custom commands for repetitive tasks through the command option.

jsonc title="opencode.jsonc"
{
  "$schema": "https://opencode.ai/config.json",
  "command": {
    "test": {
      "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.",
      "description": "Run tests with coverage",
      "agent": "build",
      "model": "anthropic/claude-haiku-4-5",
    },
    "component": {
      "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.",
      "description": "Create a new component",
    },
  },
}

You can also define commands using markdown files in ~/.config/opencode/commands/ or .opencode/commands/. Learn more here.


Keybinds

Customize TUI keyboard shortcuts in tui.json with keybinds.

json title="tui.json"
{
  "$schema": "https://opencode.ai/tui.json",
  "keybinds": {
    "command_list": "ctrl+p"
  }
}

keybinds is merged with built-in defaults, so you only need to configure the shortcuts you want to change.

Learn more here.


Snapshot

OpenCode uses snapshots to track file changes during agent operations, enabling you to undo and revert changes within a session. Snapshots are enabled by default.

For large repositories or projects with many submodules, the snapshot system can cause slow indexing and significant disk usage as it tracks all changes using an internal git repository. You can disable snapshots using the snapshot option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "snapshot": false
}

Note that disabling snapshots means changes made by the agent cannot be rolled back through the UI.


Autoupdate

OpenCode will automatically download any new updates when it starts up. You can disable this with the autoupdate option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "autoupdate": false
}

If you don't want updates but want to be notified when a new version is available, set autoupdate to "notify".
Notice that this only works if it was not installed using a package manager such as Homebrew.


Formatters

You can enable and configure code formatters through the formatter option. Omit it to keep formatters disabled.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "formatter": true
}

Use an object to keep built-ins enabled while configuring overrides or custom formatters.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {
    "prettier": {
      "disabled": true
    },
    "custom-prettier": {
      "command": ["npx", "prettier", "--write", "$FILE"],
      "environment": {
        "NODE_ENV": "development"
      },
      "extensions": [".js", ".ts", ".jsx", ".tsx"]
    }
  }
}

Learn more about formatters here.


LSP Servers

You can enable and configure LSP servers through the lsp option. Omit it to keep LSP disabled.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": true
}

Use an object to keep built-ins enabled while configuring overrides or custom LSP servers.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": {
    "typescript": {
      "disabled": true
    }
  }
}

Learn more about LSP servers here.


Permissions

By default, opencode allows all operations without requiring explicit approval. You can change this using the permission option.

For example, to ensure that the edit and shell tools require user approval:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "edit": "ask",
    "shell": "ask"
  }
}

Learn more about permissions here.


Compaction

You can control context compaction behavior through the compaction option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "compaction": {
    "auto": true,
    "prune": false,
    "reserved": 10000
  }
}
  • auto - Automatically compact the session when context is full (default: true).
  • prune - Remove old tool outputs to save tokens (default: false). Set to true to enable pruning.
  • reserved - Token buffer for compaction. Leaves enough window to avoid overflow during compaction.

Watcher

You can configure file watcher ignore patterns through the watcher option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "watcher": {
    "ignore": ["**/generated/**"]
  }
}

Patterns follow glob syntax. Common dependency, VCS, build, and cache directories are ignored automatically at any depth.


MCP servers

You can configure MCP servers you want to use through the mcp option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {}
}

Learn more here.


Plugins

Plugins extend OpenCode with custom tools, hooks, and integrations.

Place plugin files in .opencode/plugins/ or ~/.config/opencode/plugins/. You can also load plugins from npm through the plugin option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]
}

Learn more here.


Instructions

You can configure the instructions for the model you're using through the instructions option.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]
}

This takes an array of paths and glob patterns to instruction files. Learn more
about rules here
.


Disabled providers

You can disable providers that are loaded automatically through the disabled_providers option. This is useful when you want to prevent certain providers from being loaded even if their credentials are available.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "disabled_providers": ["openai", "gemini"]
}

:::note
The disabled_providers takes priority over enabled_providers.
:::

The disabled_providers option accepts an array of provider IDs. When a provider is disabled:

  • It won't be loaded even if environment variables are set.
  • It won't be loaded even if API keys are configured through the /connect command.
  • The provider's models won't appear in the model selection list.

Enabled providers

You can specify an allowlist of providers through the enabled_providers option. When set, only the specified providers will be enabled and all others will be ignored.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "enabled_providers": ["anthropic", "openai"]
}

This is useful when you want to restrict OpenCode to only use specific providers rather than disabling them one by one.

:::note
The disabled_providers takes priority over enabled_providers.
:::

If a provider appears in both enabled_providers and disabled_providers, the disabled_providers takes priority for backwards compatibility.


Experimental

The experimental key contains options that are under active development.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "experimental": {}
}

:::caution
Experimental options are not stable. They may change or be removed without notice.
:::


Variables

You can use variable substitution in your config files to reference environment variables and file contents.


Env vars

Use {env:VARIABLE_NAME} to substitute environment variables:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "model": "{env:OPENCODE_MODEL}",
  "provider": {
    "anthropic": {
      "models": {},
      "options": {
        "apiKey": "{env:ANTHROPIC_API_KEY}"
      }
    }
  }
}

If the environment variable is not set, it will be replaced with an empty string.


Files

Use {file:path/to/file} to substitute the contents of a file:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "instructions": ["./custom-instructions.md"],
  "provider": {
    "openai": {
      "options": {
        "apiKey": "{file:~/.secrets/openai-key}"
      }
    }
  }
}

File paths can be:

  • Relative to the config file directory
  • Or absolute paths starting with / or ~

These are useful for:

  • Keeping sensitive data like API keys in separate files.
  • Including large instruction files without cluttering your config.
  • Sharing common configuration snippets across multiple config files.

Packages Web Src Content Docs Custom Tools (`packages/web/src/content/docs/custom-tools.mdx`)


title: Custom Tools

Custom tools are functions you create that the LLM can call during conversations. They work alongside opencode's built-in tools like read, write, and shell.


Creating a tool

Tools are defined as TypeScript or JavaScript files. However, the tool definition can invoke scripts written in any language — TypeScript or JavaScript is only used for the tool definition itself.


Location

They can be defined:

  • Locally by placing them in the .opencode/tools/ directory of your project.
  • Or globally, by placing them in ~/.config/opencode/tools/.

Structure

The easiest way to create tools is using the tool() helper which provides type-safety and validation.

ts title=".opencode/tools/database.ts" {1}
import { tool } from "@opencode-ai/plugin"

export default tool({
  description: "Query the project database",
  args: {
    query: tool.schema.string().describe("SQL query to execute"),
  },
  async execute(args) {
    // Your database logic here
    return `Executed query: ${args.query}`
  },
})

The filename becomes the tool name. The above creates a database tool.


Multiple tools per file

You can also export multiple tools from a single file. Each export becomes a separate tool with the name <filename>_<exportname>:

ts title=".opencode/tools/math.ts"
import { tool } from "@opencode-ai/plugin"

export const add = tool({
  description: "Add two numbers",
  args: {
    a: tool.schema.number().describe("First number"),
    b: tool.schema.number().describe("Second number"),
  },
  async execute(args) {
    return (args.a + args.b).toString()
  },
})

export const multiply = tool({
  description: "Multiply two numbers",
  args: {
    a: tool.schema.number().describe("First number"),
    b: tool.schema.number().describe("Second number"),
  },
  async execute(args) {
    return (args.a * args.b).toString()
  },
})

This creates two tools: math_add and math_multiply.


Name collisions with built-in tools

Custom tools are keyed by tool name. If a custom tool uses the same name as a built-in tool, the custom tool takes precedence.

For example, this file replaces the built-in shell tool:

ts title=".opencode/tools/shell.ts"
import { tool } from "@opencode-ai/plugin"

export default tool({
  description: "Restricted shell wrapper",
  args: {
    command: tool.schema.string(),
  },
  async execute(args) {
    return `blocked: ${args.command}`
  },
})

:::note
Prefer unique names unless you intentionally want to replace a built-in tool. If you want to disable a built in tool but not override it, use permissions.
:::


Arguments

You can use tool.schema, which is just Zod, to define argument types.

ts "tool.schema"
args: {
  query: tool.schema.string().describe("SQL query to execute")
}

You can also import Zod directly and return a plain object:

ts {6}
import { z } from "zod"

export default {
  description: "Tool description",
  args: {
    param: z.string().describe("Parameter description"),
  },
  async execute(args, context) {
    // Tool implementation
    return "result"
  },
}

Context

Tools receive context about the current session:

ts title=".opencode/tools/project.ts" {8}
import { tool } from "@opencode-ai/plugin"

export default tool({
  description: "Get project information",
  args: {},
  async execute(args, context) {
    // Access context information
    const { agent, sessionID, messageID, directory, worktree } = context
    return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}`
  },
})

Use context.directory for the session working directory.
Use context.worktree for the git worktree root.


Examples

Write a tool in Python

You can write your tools in any language you want. Here's an example that adds two numbers using Python.

First, create the tool as a Python script:

python title=".opencode/tools/add.py"
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])
print(a + b)

Then create the tool definition that invokes it:

ts title=".opencode/tools/python-add.ts" {10}
import { tool } from "@opencode-ai/plugin"
import path from "path"

export default tool({
  description: "Add two numbers using Python",
  args: {
    a: tool.schema.number().describe("First number"),
    b: tool.schema.number().describe("Second number"),
  },
  async execute(args, context) {
    const script = path.join(context.worktree, ".opencode/tools/add.py")
    const result = await Bun.$`python3 ${script} ${args.a} ${args.b}`.text()
    return result.trim()
  },
})

Here we are using the Bun.$ utility to run the Python script.


Packages Web Src Content Docs Ecosystem (`packages/web/src/content/docs/ecosystem.mdx`)


title: Ecosystem

A collection of community projects built on OpenCode.

:::note
Want to add your OpenCode related project to this list? Submit a PR.
:::

You can also check out awesome-opencode and opencode.cafe, a community that aggregates the ecosystem and community.


Plugins

Name Description
opencode-daytona Automatically run OpenCode sessions in isolated Daytona sandboxes with git sync and live previews
opencode-helicone-session Automatically inject Helicone session headers for request grouping
opencode-type-inject Auto-inject TypeScript/Svelte types into file reads with lookup tools
opencode-openai-codex-auth Use your ChatGPT Plus/Pro subscription instead of API credits
opencode-gemini-auth Use your existing Gemini plan instead of API billing
opencode-antigravity-auth Use Antigravity's free models instead of API billing
opencode-devcontainers Multi-branch devcontainer isolation with shallow clones and auto-assigned ports
opencode-google-antigravity-auth Google Antigravity OAuth Plugin, with support for Google Search, and more robust API handling
opencode-dynamic-context-pruning Optimize token usage by pruning obsolete tool outputs
opencode-vibeguard Redact secrets/PII into VibeGuard-style placeholders before LLM calls; restore locally
opencode-websearch-cited Add native websearch support for supported providers with Google grounded style
opencode-pty Enables AI agents to run background processes in a PTY, send interactive input to them.
opencode-shell-strategy Instructions for non-interactive shell commands - prevents hangs from TTY-dependent operations
opencode-wakatime Track OpenCode usage with Wakatime
opencode-md-table-formatter Clean up markdown tables produced by LLMs
opencode-morph-fast-apply 10x faster code editing with Morph Fast Apply API and lazy edit markers
opencode-morph-plugin Fast Apply editing, WarpGrep codebase search, and context compaction via Morph
oh-my-opencode Background agents, pre-built LSP/AST/MCP tools, curated agents, Claude Code compatible
opencode-notificator Desktop notifications and sound alerts for OpenCode sessions
opencode-notifier Desktop notifications and sound alerts for permission, completion, and error events
opencode-zellij-namer AI-powered automatic Zellij session naming based on OpenCode context
opencode-skillful Allow OpenCode agents to lazy load prompts on demand with skill discovery and injection
opencode-supermemory Persistent memory across sessions using Supermemory
@plannotator/opencode Interactive plan review with visual annotation and private/offline sharing
@openspoon/subtask2 Extend opencode /commands into a powerful orchestration system with granular flow control
opencode-scheduler Schedule recurring jobs using launchd (Mac) or systemd (Linux) with cron syntax
opencode-conductor Protocol-Driven Workflow: Automation of the Context -> Spec -> Plan -> Implement lifecycle.
micode Structured Brainstorm → Plan → Implement workflow with session continuity
octto Interactive browser UI for AI brainstorming with multi-question forms
opencode-background-agents Claude Code-style background agents with async delegation and context persistence
opencode-notify Native OS notifications for OpenCode – know when tasks complete
opencode-workspace Bundled multi-agent orchestration harness – 16 components, one install
opencode-worktree Zero-friction git worktrees for OpenCode
opencode-sentry-monitor Trace and debug your AI agents with Sentry AI Monitoring
opencode-firecrawl Web scraping, crawling, and search via the Firecrawl CLI
opencode-jfrog-plugin JFrog Plugin for seamless integration of Opencode users to JFrog platform
opencode-goal-plugin Session-scoped /goal workflow that keeps objectives in context and auto-continues until complete
opencode-tavily Web search, extraction, crawling, and deep research via the Tavily CLI
opencode-supabase Supabase plugin for OpenCode: account login, Management API tools, bundled Supabase agent skills, and guided Supabase MCP setup.

Projects

Name Description
kimaki Discord bot to control OpenCode sessions, built on the SDK
opencode.nvim Neovim plugin for editor-aware prompts, built on the API
portal Mobile-first web UI for OpenCode over Tailscale/VPN
opencode plugin template Template for building OpenCode plugins
opencode.nvim Neovim frontend for opencode - a terminal-based AI coding agent
ai-sdk-provider-opencode-sdk Vercel AI SDK provider for using OpenCode via @opencode-ai/sdk
OpenChamber Web / Desktop App and VS Code Extension for OpenCode
OpenCode-Obsidian Obsidian plugin that embeds OpenCode in Obsidian's UI
OpenWork An open-source alternative to Claude Cowork, powered by OpenCode
ocx OpenCode extension manager with portable, isolated profiles.
CodeNomad Desktop, Web, Mobile and Remote Client App for OpenCode

Agents

Name Description
Agentic Modular AI agents and commands for structured development
opencode-agents Configs, prompts, agents, and plugins for enhanced workflows

Packages Web Src Content Docs Enterprise (`packages/web/src/content/docs/enterprise.mdx`)


title: Enterprise

export const enterprise = "https://opencode.ai/enterprise"

OpenCode Enterprise is for organizations that want to ensure that their code and data never leaves their infrastructure. It can do this by using a centralized config that integrates with your SSO and internal AI gateway.

:::note
OpenCode does not store any of your code or context data.
:::

To get started with OpenCode Enterprise:

  1. Do a trial internally with your team.
  2. Contact us to discuss pricing and implementation options.

Trial

OpenCode is open source and does not store any of your code or context data, so your developers can simply get started and carry out a trial.


Data handling

OpenCode does not store your code or context data. All processing happens locally or through direct API calls to your AI provider.

This means that as long as you are using a provider you trust, or an internal
AI gateway, you can use OpenCode securely.


Code ownership

You own all code produced by OpenCode. There are no licensing restrictions or ownership claims.


Pricing

We use a per-seat model for OpenCode Enterprise. If you have your own LLM gateway, we do not charge for tokens used. For further details about pricing and implementation options, contact us.


Deployment

Once you have completed your trial and you are ready to use OpenCode at
your organization, you can contact us to discuss
pricing and implementation options.


Central Config

We can set up OpenCode to use a single central config for your entire organization.

This centralized config can integrate with your SSO provider and ensures all users access only your internal AI gateway.


SSO integration

Through the central config, OpenCode can integrate with your organization's SSO provider for authentication.

This allows OpenCode to obtain credentials for your internal AI gateway through your existing identity management system.


Internal AI gateway

With the central config, OpenCode can also be configured to use only your internal AI gateway.

You can also disable all other AI providers, ensuring all requests go through your organization's approved infrastructure.


Self-hosting

While we recommend disabling the share pages to ensure your data never leaves
your organization, we can also help you self-host them on your infrastructure.

This is currently on our roadmap. If you're interested, let us know.


FAQ

What is OpenCode Enterprise?

OpenCode Enterprise is for organizations that want to ensure that their code and data never leaves their infrastructure. It can do this by using a centralized config that integrates with your SSO and internal AI gateway.

How do I get started with OpenCode Enterprise?

Simply start with an internal trial with your team. OpenCode by default does not store your code or context data, making it easy to get started.

Then contact us to discuss pricing and implementation options.

How does enterprise pricing work?

We offer per-seat enterprise pricing. If you have your own LLM gateway, we do not charge for tokens used. For further details, contact us for a custom quote based on your organization's needs.

Is my data secure with OpenCode Enterprise?

Yes. OpenCode does not store your code or context data. All processing happens locally or through direct API calls to your AI provider. With central config and SSO integration, your data remains secure within your organization's infrastructure.

Can we use our own private NPM registry?

OpenCode supports private npm registries through Bun's native .npmrc file support. If your organization uses a private registry, such as JFrog Artifactory, Nexus, or similar, ensure developers are authenticated before running OpenCode.

To set up authentication with your private registry:

bash
npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/

This creates ~/.npmrc with authentication details. OpenCode will automatically
pick this up.

:::caution
You must be logged into the private registry before running OpenCode.
:::

Alternatively, you can manually configure a .npmrc file:

bash title="~/.npmrc"
registry=https://your-company.jfrog.io/api/npm/npm-virtual/
//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN}

Developers must be logged into the private registry before running OpenCode to ensure packages can be installed from your enterprise registry.


Packages Web Src Content Docs Formatters (`packages/web/src/content/docs/formatters.mdx`)


title: Formatters

OpenCode can format files after they are written or edited using language-specific formatters. Formatters are disabled by default; enable them in your config before OpenCode will run them.


Built-in

OpenCode comes with several built-in formatters for popular languages and frameworks. Below is a list of the formatters, supported file extensions, and commands or config options it needs.

Formatter Extensions Requirements
air .R air command available
biome .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and more biome.json(c) config file
cargofmt .rs cargo fmt command available
clang-format .c, .cpp, .h, .hpp, .ino, and more .clang-format config file
cljfmt .clj, .cljs, .cljc, .edn cljfmt command available
dart .dart dart command available
dfmt .d dfmt command available
gleam .gleam gleam command available
gofmt .go gofmt command available
htmlbeautifier .erb, .html.erb htmlbeautifier command available
ktlint .kt, .kts ktlint command available
mix .ex, .exs, .eex, .heex, .leex, .neex, .sface mix command available
nixfmt .nix nixfmt command available
ocamlformat .ml, .mli ocamlformat command available and .ocamlformat config file
ormolu .hs ormolu command available
oxfmt (Experimental) .js, .jsx, .ts, .tsx oxfmt dependency in package.json and an experimental env variable flag
pint .php laravel/pint dependency in composer.json
prettier .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and more prettier dependency in package.json
rubocop .rb, .rake, .gemspec, .ru rubocop command available
ruff .py, .pyi ruff command available with config
rustfmt .rs rustfmt command available
shfmt .sh, .bash shfmt command available
standardrb .rb, .rake, .gemspec, .ru standardrb command available
terraform .tf, .tfvars terraform command available
uv .py, .pyi uv command available
zig .zig, .zon zig command available

When formatters are enabled, OpenCode will use prettier for matching files if your project has prettier in package.json.


How it works

When OpenCode writes or edits a file and formatters are enabled, it:

  1. Checks the file extension against all enabled formatters.
  2. Runs the appropriate formatter command on the file.
  3. Applies the formatting changes.

This process happens in the background for enabled formatters.


Configure

You can enable and customize formatters through the formatter section in your OpenCode config.

To enable all built-in formatters, set formatter to true.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "formatter": true
}

Use an object to keep built-ins enabled while configuring overrides or custom formatters.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {}
}

Each formatter configuration supports the following:

Property Type Description
disabled boolean Set this to true to disable the formatter
command string[] The command to run for formatting. Required for custom formatters; optional for built-ins.
environment object Environment variables to set when running the formatter
extensions string[] File extensions this formatter should handle

Let's look at some examples.


Disabling formatters

If formatter is omitted, all formatters are disabled. To disable all formatters after another config enabled them, set formatter to false:

json title="opencode.json" {3}
{
  "$schema": "https://opencode.ai/config.json",
  "formatter": false
}

To disable a specific formatter, set disabled to true:

json title="opencode.json" {5}
{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {
    "prettier": {
      "disabled": true
    }
  }
}

Custom formatters

You can configure built-in formatters with options like environment or extensions. To add a custom formatter, specify a command and extensions:

json title="opencode.json" {4-14}
{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {
    "prettier": {
      "command": ["npx", "prettier", "--write", "$FILE"],
      "environment": {
        "NODE_ENV": "development"
      },
      "extensions": [".js", ".ts", ".jsx", ".tsx"]
    },
    "custom-markdown-formatter": {
      "command": ["deno", "fmt", "$FILE"],
      "extensions": [".md"]
    }
  }
}

The $FILE placeholder in the command will be replaced with the path to the file being formatted.


Packages Web Src Content Docs Github (`packages/web/src/content/docs/github.mdx`)


title: GitHub

OpenCode integrates with your GitHub workflow. Mention /opencode or /oc in your comment, and OpenCode will execute tasks within your GitHub Actions runner.


Features

  • Triage issues: Ask OpenCode to look into an issue and explain it to you.
  • Fix and implement: Ask OpenCode to fix an issue or implement a feature. And it will work in a new branch and submits a PR with all the changes.
  • Secure: OpenCode runs inside your GitHub's runners.

Installation

Run the following command in a project that is in a GitHub repo:

bash
opencode github install

This will walk you through installing the GitHub app, creating the workflow, and setting up secrets.


Manual Setup

Or you can set it up manually.

  1. Install the GitHub app

    Head over to github.com/apps/opencode-agent. Make sure it's installed on the target repository.

  2. Add the workflow

    Add the following workflow file to .github/workflows/opencode.yml in your repo. Make sure to set the appropriate model and required API keys in env.

    yml title=".github/workflows/opencode.yml" {24,26}
    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:
          - name: Checkout repository
            uses: actions/checkout@v6
            with:
              fetch-depth: 1
              persist-credentials: false
    
          - name: Run OpenCode
            uses: anomalyco/opencode/github@latest
            env:
              ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
            with:
              model: anthropic/claude-sonnet-4-20250514
  3. Store the API keys in secrets

    In your organization or project settings, expand Secrets and variables on the left and select Actions. And add the required API keys.


Configuration

  • model: The model to use with OpenCode. Takes the format of provider/model. This is required.

  • agent: The agent to use. Must be a primary agent. Falls back to default_agent from config or "build" if not found.

  • prompt: Optional custom prompt to override the default behavior. Use this to customize how OpenCode processes requests.

  • mentions: Comma-separated list of trigger phrases, case-insensitive. Defaults to /opencode,/oc.

  • variant: Model variant for provider-specific reasoning effort, for example high, max, or minimal.

  • oidc_base_url: Base URL for the OIDC token exchange API. Only needed when running a custom GitHub App install. Defaults to https://api.opencode.ai.

  • use_github_token: Set to true to use a caller-provided GITHUB_TOKEN instead of exchanging an OIDC token for an OpenCode App installation token. Defaults to false.

    Use this mode to run without installing the OpenCode GitHub App. Pass the token through env and grant the permissions required by your workflow:

    yaml
    permissions:
      contents: write
      pull-requests: write
      issues: write
    
    steps:
      - 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

    id-token: write is not required in this mode because OIDC exchange is skipped. To use a personal access token or another GitHub App token, store it as a secret and pass that secret as GITHUB_TOKEN instead.


Supported Events

OpenCode can be triggered by the following GitHub events:

Event Type Triggered By Details
issue_comment Comment on an issue or PR Mention /opencode or /oc in your comment. OpenCode reads context and can create branches, open PRs, or reply.
pull_request_review_comment Comment on specific code lines in a PR Mention /opencode or /oc while reviewing code. OpenCode receives file path, line numbers, and diff context.
issues Issue opened or edited Automatically trigger OpenCode when issues are created or modified. Requires prompt input.
pull_request PR opened or updated Automatically trigger OpenCode when PRs are opened, synchronized, or reopened. Useful for automated reviews.
schedule Cron-based schedule Run OpenCode on a schedule. Requires prompt input. Output goes to logs and PRs (no issue to comment on).
workflow_dispatch Manual trigger from GitHub UI Trigger OpenCode on demand via Actions tab. Requires prompt input. Output goes to logs and PRs.

Schedule Example

Run OpenCode on a schedule to perform automated tasks:

yaml title=".github/workflows/opencode-scheduled.yml"
name: Scheduled OpenCode Task

on:
  schedule:
    - cron: "0 9 * * 1" # Every Monday at 9am UTC

jobs:
  opencode:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: write
      pull-requests: write
      issues: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          persist-credentials: false

      - name: Run OpenCode
        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 any TODO comments and create a summary.
            If you find issues worth addressing, open an issue to track them.

For scheduled events, the prompt input is required since there's no comment to extract instructions from. Scheduled workflows run without a user context to permission-check, so the workflow must grant contents: write and pull-requests: write if you expect OpenCode to create branches or PRs.


Pull Request Example

Automatically review PRs when they are opened or updated:

yaml title=".github/workflows/opencode-review.yml"
name: opencode-review

on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
      pull-requests: read
      issues: 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

For pull_request events, if no prompt is provided, OpenCode defaults to reviewing the pull request.


Issues Triage Example

Automatically triage new issues. This example filters to accounts older than 30 days to reduce spam:

yaml title=".github/workflows/opencode-triage.yml"
name: Issue Triage

on:
  issues:
    types: [opened]

jobs:
  triage:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: write
      pull-requests: write
      issues: write
    steps:
      - name: Check account age
        id: check
        uses: actions/github-script@v7
        with:
          script: |
            const user = await github.rest.users.getByUsername({
              username: context.payload.issue.user.login
            });
            const created = new Date(user.data.created_at);
            const days = (Date.now() - created) / (1000 * 60 * 60 * 24);
            return days >= 30;
          result-encoding: string

      - uses: actions/checkout@v6
        if: steps.check.outputs.result == 'true'
        with:
          persist-credentials: false

      - uses: anomalyco/opencode/github@latest
        if: steps.check.outputs.result == 'true'
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        with:
          model: anthropic/claude-sonnet-4-20250514
          prompt: |
            Review this issue. If there's a clear fix or relevant docs:
            - Provide documentation links
            - Add error handling guidance for code examples
            Otherwise, do not comment.

For issues events, the prompt input is required since there's no comment to extract instructions from.


Custom prompts

Override the default prompt to customize OpenCode's behavior for your workflow.

yaml title=".github/workflows/opencode.yml"
- uses: anomalyco/opencode/github@latest
  with:
    model: anthropic/claude-sonnet-4-5
    prompt: |
      Review this pull request:
      - Check for code quality issues
      - Look for potential bugs
      - Suggest improvements

This is useful for enforcing specific review criteria, coding standards, or focus areas relevant to your project.


Examples

Here are some examples of how you can use OpenCode in GitHub.

  • Explain an issue

    Add this comment in a GitHub issue.

    text
    /opencode explain this issue

    OpenCode will read the entire thread, including all comments, and reply with a clear explanation.

  • Fix an issue

    In a GitHub issue, say:

    text
    /opencode fix this

    And OpenCode will create a new branch, implement the changes, and open a PR with the changes.

  • Review PRs and make changes

    Leave the following comment on a GitHub PR.

    text
    Delete the attachment from S3 when the note is removed /oc

    OpenCode will implement the requested change and commit it to the same PR.

  • Review specific code lines

    Leave a comment directly on code lines in the PR's "Files" tab. OpenCode automatically detects the file, line numbers, and diff context to provide precise responses.

    text
    [Comment on specific lines in Files tab]
    /oc add error handling here

    When commenting on specific lines, OpenCode receives:

    • The exact file being reviewed
    • The specific lines of code
    • The surrounding diff context
    • Line number information

    This allows for more targeted requests without needing to specify file paths or line numbers manually.


Packages Web Src Content Docs Gitlab (`packages/web/src/content/docs/gitlab.mdx`)


title: GitLab

OpenCode integrates with your GitLab workflow through your GitLab CI/CD pipeline or with GitLab Duo.

In both cases, OpenCode will run on your GitLab runners.


GitLab CI

OpenCode works in a regular GitLab pipeline. You can build it into a pipeline as a CI component

Here we are using a community-created CI/CD component for OpenCode — nagyv/gitlab-opencode.


Features

  • Use custom configuration per job: Configure OpenCode with a custom configuration directory, for example ./config/#custom-directory to enable or disable functionality per OpenCode invocation.
  • Minimal setup: The CI component sets up OpenCode in the background, you only need to create the OpenCode configuration and the initial prompt.
  • Flexible: The CI component supports several inputs for customizing its behavior

Setup

  1. Store your OpenCode authentication JSON as a File type CI environment variables under Settings > CI/CD > Variables. Make sure to mark them as "Masked and hidden".

  2. Add the following to your .gitlab-ci.yml file.

    yaml title=".gitlab-ci.yml"
    include:
      - component: $CI_SERVER_FQDN/nagyv/gitlab-opencode/opencode@2
        inputs:
          config_dir: ${CI_PROJECT_DIR}/opencode-config
          auth_json: $OPENCODE_AUTH_JSON # The variable name for your OpenCode authentication JSON
          command: optional-custom-command
          message: "Your prompt here"

For more inputs and use cases check out the docs for this component.


GitLab Duo

OpenCode integrates with your GitLab workflow.
Mention @opencode in a comment, and OpenCode will execute tasks within your GitLab CI pipeline.


Features

  • Triage issues: Ask OpenCode to look into an issue and explain it to you.
  • Fix and implement: Ask OpenCode to fix an issue or implement a feature.
    It will create a new branch and raise a merge request with the changes.
  • Secure: OpenCode runs on your GitLab runners.

Setup

OpenCode runs in your GitLab CI/CD pipeline, here's what you'll need to set it up:

:::tip
Check out the GitLab docs for up to date instructions.
:::

  1. Configure your GitLab environment

  2. Set up CI/CD

  3. Get an AI model provider API key

  4. Create a service account

  5. Configure CI/CD variables

  6. Create a flow config file, here's an example:

    Flow configuration

    text

/* Detailed source-code truncated for AI context efficiency. */

text
You can refer to the [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for detailed instructions.

---

### Examples

Here are some examples of how you can use OpenCode in GitLab.

:::tip
You can configure to use a different trigger phrase than `@opencode`.
:::

- **Explain an issue**

  Add this comment in a GitLab issue.

@opencode explain this issue

text
OpenCode will read the issue and reply with a clear explanation.

- **Fix an issue**

In a GitLab issue, say:

@opencode fix this

text
OpenCode will create a new branch, implement the changes, and open a merge request with the changes.

- **Review merge requests**

Leave the following comment on a GitLab merge request.

@opencode review this merge request

text
OpenCode will review the merge request and provide feedback.

---

### Packages Web Src Content Docs Ide (`packages/web/src/content/docs/ide.mdx`)

---
title: IDE
---

OpenCode integrates with VS Code, Cursor, or any IDE that supports a terminal. Just run `opencode` in the terminal to get started.

---

## Usage

- **Quick Launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open OpenCode in a split terminal view, or focus an existing terminal session if one is already running.
- **New Session**: Use `Cmd+Shift+Esc` (Mac) or `Ctrl+Shift+Esc` (Windows/Linux) to start a new OpenCode terminal session, even if one is already open. You can also click the OpenCode button in the UI.
- **Context Awareness**: Automatically share your current selection or tab with OpenCode.
- **File Reference Shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references. For example, `@File#L37-42`.

---

## Installation

To install OpenCode on VS Code and popular forks like Cursor, Windsurf, VSCodium:

1. Open VS Code
2. Open the integrated terminal
3. Run `opencode` - the extension installs automatically

If on the other hand you want to use your own IDE when you run `/editor` or `/export` from the TUI, you'll need to set `export EDITOR="code --wait"`. [Learn more](/docs/tui/#editor-setup).

---

### Manual Install

Search for **OpenCode** in the Extension Marketplace and click **Install**.

---

### Troubleshooting

If the extension fails to install automatically:

- Ensure you’re running `opencode` in the integrated terminal.
- Confirm the CLI for your IDE is installed:
- For VS Code: `code` command
- For Cursor: `cursor` command
- For Windsurf: `windsurf` command
- For VSCodium: `codium` command
- If not, run `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux) and search for "Shell Command: Install 'code' command in PATH" (or the equivalent for your IDE)
- Ensure VS Code has permission to install extensions

---

### Packages Web Src Content Docs Keybinds (`packages/web/src/content/docs/keybinds.mdx`)

---
title: Keybinds
---

OpenCode has a list of keybinds that you can customize through `tui.json`.

/* Detailed source-code truncated for AI context efficiency. */

text
:::note
On Windows, the defaults for `input_undo` and `terminal_suspend` are different:

- `input_undo` defaults to `ctrl+z,ctrl+-,super+z` when it is not explicitly configured. The `ctrl+z` binding is added because Windows terminals do not support POSIX suspend.
- `terminal_suspend` is forced to `none` because native Windows terminals do not support POSIX suspend.
  :::

---

## Leader Key

OpenCode uses a `leader` key for many keybinds. This avoids conflicts in your terminal.

By default, `ctrl+x` is the leader key and many actions require you to first press the leader key and then the shortcut. For example, to start a new session you first press `ctrl+x` and then press `n`.

You don't need to use a leader key for your keybinds but we recommend doing so.

Some navigation keybinds intentionally do not use the leader key by default. For subagent sessions, the defaults are `session_child_first` = `<leader>down`, `session_child_cycle` = `right`, `session_child_cycle_reverse` = `left`, and `session_parent` = `up`.

`leader_timeout` controls how long OpenCode waits for the next key after the leader key. It defaults to `2000` milliseconds.

---

## Binding Values

A string can contain one shortcut or multiple comma-separated shortcuts. You can also use an array for multiple shortcuts.

For advanced cases, use an object with `key`, `event`, `preventDefault`, or `fallthrough`.

```json title="tui.json"
{
  "$schema": "https://opencode.ai/tui.json",
  "keybinds": {
    "messages_copy": ["<leader>y", "ctrl+shift+c"],
    "input_paste": {
      "key": "ctrl+v",
      "preventDefault": false
    }
  }
}

Disable Keybind

You can disable a keybind by adding the key to tui.json with a value of "none" or false.

json title="tui.json"
{
  "$schema": "https://opencode.ai/tui.json",
  "keybinds": {
    "session_compact": "none"
  }
}

Desktop Prompt Shortcuts

The OpenCode desktop app prompt input supports common Readline/Emacs-style shortcuts for editing text. These are built-in and currently not configurable via opencode.json.

Shortcut Action
ctrl+a Move to start of current line
ctrl+e Move to end of current line
ctrl+b Move cursor back one character
ctrl+f Move cursor forward one character
alt+b Move cursor back one word
alt+f Move cursor forward one word
ctrl+d Delete character under cursor
ctrl+k Kill to end of line
ctrl+u Kill to start of line
ctrl+w Kill previous word
alt+d Kill next word
ctrl+t Transpose characters
ctrl+g Cancel popovers / abort running response

Shift+Enter

Some terminals don't send modifier keys with Enter by default. You may need to configure your terminal to send Shift+Enter as an escape sequence.

Windows Terminal

Open your settings.json at:

text
%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json

Add this to the root-level actions array:

json
"actions": [
  {
    "command": {
      "action": "sendInput",
      "input": "\u001b[13;2u"
    },
    "id": "User.sendInput.ShiftEnterCustom"
  }
]

Add this to the root-level keybindings array:

json
"keybindings": [
  {
    "keys": "shift+enter",
    "id": "User.sendInput.ShiftEnterCustom"
  }
]

Save the file and restart Windows Terminal or open a new tab.


Packages Web Src Content Docs Lsp (`packages/web/src/content/docs/lsp.mdx`)


title: LSP Servers

OpenCode can integrate with Language Server Protocol (LSP) servers to use diagnostics as feedback for the agent.


Built-in

OpenCode comes with several built-in LSP servers for popular languages:

LSP Server Extensions Requirements
astro .astro Auto-installs for Astro projects
bash .sh, .bash, .zsh, .ksh Auto-installs bash-language-server
clangd .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ Auto-installs for C/C++ projects
csharp .cs, .csx .NET SDK installed
clojure-lsp .clj, .cljs, .cljc, .edn clojure-lsp command available
dart .dart dart command available
deno .ts, .tsx, .js, .jsx, .mjs deno command available (auto-detects deno.json/deno.jsonc)
elixir-ls .ex, .exs elixir command available
eslint .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue eslint dependency in project
fsharp .fs, .fsi, .fsx, .fsscript .NET SDK installed
gleam .gleam gleam command available
gopls .go go command available
hls .hs, .lhs haskell-language-server-wrapper command available
jdtls .java Java SDK (version 21+) installed
julials .jl julia and LanguageServer.jl installed
kotlin-ls .kt, .kts Auto-installs for Kotlin projects
lua-ls .lua Auto-installs for Lua projects
nixd .nix nixd command available
ocaml-lsp .ml, .mli ocamllsp command available
oxlint .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte oxlint dependency in project
php intelephense .php Auto-installs for PHP projects
prisma .prisma prisma command available
pyright .py, .pyi pyright dependency installed
razor .razor, .cshtml .NET SDK and VS Code C# extension installed
ruby-lsp (rubocop) .rb, .rake, .gemspec, .ru ruby and gem commands available
rust .rs rust-analyzer command available
sourcekit-lsp .swift, .objc, .objcpp swift installed (xcode on macOS)
svelte .svelte Auto-installs for Svelte projects
terraform .tf, .tfvars Auto-installs from GitHub releases
tinymist .typ, .typc Auto-installs from GitHub releases
typescript .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts typescript dependency in project
vue .vue Auto-installs for Vue projects
yaml-ls .yaml, .yml Auto-installs Red Hat yaml-language-server
zls .zig, .zon zig command available

LSP is disabled by default. When enabled, servers start when one of the above file extensions is detected and the requirements are met.

:::note
You can disable automatic LSP server downloads by setting the OPENCODE_DISABLE_LSP_DOWNLOAD environment variable to true.
:::


How It Works

When LSP is enabled and opencode opens a file, it:

  1. Checks the file extension against all enabled LSP servers.
  2. Starts the appropriate LSP server if not already running.

Best Practices

LSP can help the agent find and fix issues by providing diagnostics from language servers. This is useful in some projects, but it is not always a net positive.

Language servers can get out of sync, use significant memory, vary by version or project, and slow down agent workflows. In many projects it is better to have the agent run lint, typecheck, or other diagnostic CLI tools directly, so errors are fed back into the agent loop without those tradeoffs. Document those commands in instruction files such as AGENTS.md or skills so the agent knows what to run. Enable LSP when your project benefits from additional language-server feedback.


Configure

You can enable and customize LSP servers through the lsp section in your opencode config.

To enable all built-in LSP servers, set lsp to true.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": true
}

Use an object to keep built-ins enabled while configuring overrides or custom servers.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": {}
}

Each configured LSP server entry supports the following:

Server entries need command unless they only disable a server.

Property Type Description
disabled boolean Set this to true to disable the LSP server
command string[] The command to start the LSP server
extensions string[] File extensions this LSP server should handle
env object Environment variables to set when starting server
initialization object Initialization options to send to the LSP server

Let's look at some examples.


Environment variables

Use the env property to set environment variables when starting the LSP server:

json title="opencode.json" {5-8}
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": {
    "rust": {
      "command": ["rust-analyzer"],
      "env": {
        "RUST_LOG": "debug"
      }
    }
  }
}

Initialization options

Use the initialization property to pass initialization options to the LSP server. These are server-specific settings sent during the LSP initialize request:

json title="opencode.json" {5-13}
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": {
    "custom-lsp": {
      "command": ["custom-lsp-server", "--stdio"],
      "extensions": [".custom"],
      "initialization": {
        "preferences": {
          "importModuleSpecifierPreference": "relative"
        }
      }
    }
  }
}

:::note
Initialization options vary by LSP server. Check your LSP server's documentation for available options.
:::


Disabling LSP servers

If lsp is omitted, all LSP servers are disabled. To disable all LSP servers after another config enabled them, set lsp to false:

json title="opencode.json" {3}
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": false
}

To disable a specific LSP server, set disabled to true:

json title="opencode.json" {5}
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": {
    "typescript": {
      "disabled": true
    }
  }
}

Custom LSP servers

You can add custom LSP servers by specifying the command and file extensions:

json title="opencode.json" {4-7}
{
  "$schema": "https://opencode.ai/config.json",
  "lsp": {
    "custom-lsp": {
      "command": ["custom-lsp-server", "--stdio"],
      "extensions": [".custom"]
    }
  }
}

Additional Information

PHP Intelephense

PHP Intelephense offers premium features through a license key. You can provide a license key by placing (only) the key in a text file at:

  • On macOS/Linux: $HOME/intelephense/license.txt
  • On Windows: %USERPROFILE%/intelephense/license.txt

The file should contain only the license key with no additional content.


Packages Web Src Content Docs Mcp Servers (`packages/web/src/content/docs/mcp-servers.mdx`)


title: MCP servers

You can add external tools to OpenCode using the Model Context Protocol, or MCP. OpenCode supports both local and remote servers.

Once added, MCP tools are automatically available to the LLM alongside built-in tools.


Caveats

When you use an MCP server, it adds to the context. This can quickly add up if you have a lot of tools. So we recommend being careful with which MCP servers you use.

:::tip
MCP servers add to your context, so you want to be careful with which ones you enable.
:::

Certain MCP servers, like the GitHub MCP server, tend to add a lot of tokens and can easily exceed the context limit.


Enable

You can define MCP servers in your OpenCode Config under mcp. Add each MCP with a unique name. You can refer to that MCP by name when prompting the LLM.

jsonc title="opencode.jsonc" {6}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "name-of-mcp-server": {
      // ...
      "enabled": true,
    },
    "name-of-other-mcp-server": {
      // ...
    },
  },
}

You can also disable a server by setting enabled to false. This is useful if you want to temporarily disable a server without removing it from your config.


Overriding remote defaults

Organizations can provide default MCP servers via their .well-known/opencode endpoint. These servers may be disabled by default, allowing users to opt-in to the ones they need.

To enable a specific server from your organization's remote config, add it to your local config with enabled: true:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "jira": {
      "type": "remote",
      "url": "https://jira.example.com/mcp",
      "enabled": true
    }
  }
}

Your local config values override the remote defaults. See config precedence for more details.


Local

Add local MCP servers using type to "local" within the MCP object.

jsonc title="opencode.jsonc" {15}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-local-mcp-server": {
      "type": "local",
      // Or ["bun", "x", "my-mcp-command"]
      "command": ["npx", "-y", "my-mcp-command"],
      "enabled": true,
      "environment": {
        "MY_ENV_VAR": "my_env_var_value",
      },
    },
  },
}

The command is how the local MCP server is started. You can also pass in a list of environment variables as well.

For example, here's how you can add the test @modelcontextprotocol/server-everything MCP server.

jsonc title="opencode.jsonc"
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "mcp_everything": {
      "type": "local",
      "command": ["npx", "-y", "@modelcontextprotocol/server-everything"],
    },
  },
}

And to use it I can add use the mcp_everything tool to my prompts.

txt "mcp_everything"
use the mcp_everything tool to add the number 3 and 4

Options

Here are all the options for configuring a local MCP server.

Option Type Required Description
type String Y Type of MCP server connection, must be "local".
command Array Y Command and arguments to run the MCP server.
cwd String Working directory for the MCP server process. Relative paths resolve from the workspace.
environment Object Environment variables to set when running the server.
enabled Boolean Enable or disable the MCP server on startup.
timeout Number Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds).

Remote

Add remote MCP servers by setting type to "remote".

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-remote-mcp": {
      "type": "remote",
      "url": "https://my-mcp-server.com",
      "enabled": true,
      "headers": {
        "Authorization": "Bearer MY_API_KEY"
      }
    }
  }
}

The url is the URL of the remote MCP server and with the headers option you can pass in a list of headers.


Options

Option Type Required Description
type String Y Type of MCP server connection, must be "remote".
url String Y URL of the remote MCP server.
enabled Boolean Enable or disable the MCP server on startup.
headers Object Headers to send with the request.
oauth Object OAuth authentication configuration. See OAuth section below.
timeout Number Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds).

OAuth

OpenCode automatically handles OAuth authentication for remote MCP servers. When a server requires authentication, OpenCode will:

  1. Detect the 401 response and initiate the OAuth flow
  2. Use Dynamic Client Registration (RFC 7591) if supported by the server
  3. Store tokens securely for future requests

Automatic

For most OAuth-enabled MCP servers, no special configuration is needed. Just configure the remote server:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-oauth-server": {
      "type": "remote",
      "url": "https://mcp.example.com/mcp"
    }
  }
}

If the server requires authentication, OpenCode will prompt you to authenticate when you first try to use it. If not, you can manually trigger the flow with opencode mcp auth <server-name>.


Pre-registered

If you have client credentials from the MCP server provider, you can configure them:

json title="opencode.json" {7-11}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-oauth-server": {
      "type": "remote",
      "url": "https://mcp.example.com/mcp",
      "oauth": {
        "clientId": "{env:MY_MCP_CLIENT_ID}",
        "clientSecret": "{env:MY_MCP_CLIENT_SECRET}",
        "scope": "tools:read tools:execute"
      }
    }
  }
}

Authenticating

You can manually trigger authentication or manage credentials.

Authenticate with a specific MCP server:

bash
opencode mcp auth my-oauth-server

List all MCP servers and their auth status:

bash
opencode mcp list

Remove stored credentials:

bash
opencode mcp logout my-oauth-server

The mcp auth command will open your browser for authorization. After you authorize, OpenCode will store the tokens securely in ~/.local/share/opencode/mcp-auth.json.


Disabling OAuth

If you want to disable automatic OAuth for a server (e.g., for servers that use API keys instead), set oauth to false:

json title="opencode.json" {7}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-api-key-server": {
      "type": "remote",
      "url": "https://mcp.example.com/mcp",
      "oauth": false,
      "headers": {
        "Authorization": "Bearer {env:MY_API_KEY}"
      }
    }
  }
}

OAuth Options

Option Type Description
oauth Object | false OAuth config object, or false to disable OAuth auto-detection.
clientId String OAuth client ID. If not provided, dynamic client registration will be attempted.
clientSecret String OAuth client secret, if required by the authorization server.
scope String OAuth scopes to request during authorization.

Debugging

If a remote MCP server is failing to authenticate, you can diagnose issues with:

bash
# View auth status for all OAuth-capable servers
opencode mcp auth list

# Debug connection and OAuth flow for a specific server
opencode mcp debug my-oauth-server

The mcp debug command shows the current auth status, tests HTTP connectivity, and attempts the OAuth discovery flow.


Manage

Tools from your MCP servers are available in OpenCode alongside built-in tools. You can manage them through the OpenCode config like any other tool.


Global

This means that you can enable or disable them globally.

json title="opencode.json" {14}
{
  "$schema": "https://opencode.ai/config.json",
  "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"]
    }
  },
  "tools": {
    "my-mcp-foo": false
  }
}

We can also use a glob pattern to disable all matching MCP tools.

json title="opencode.json" {14}
{
  "$schema": "https://opencode.ai/config.json",
  "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"]
    }
  },
  "tools": {
    "my-mcp*": false
  }
}

Here we are using the glob pattern my-mcp* to disable all matching MCP tools.


Per agent

If you have a large number of MCP servers you may want to only enable them per agent and disable them globally. To do this:

  1. Disable it as a tool globally.
  2. In your agent config, enable the MCP server as a tool.
json title="opencode.json" {11, 14-18}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-mcp": {
      "type": "local",
      "command": ["bun", "x", "my-mcp-command"],
      "enabled": true
    }
  },
  "tools": {
    "my-mcp*": false
  },
  "agent": {
    "my-agent": {
      "tools": {
        "my-mcp*": true
      }
    }
  }
}

Glob patterns

The glob pattern uses simple regex globbing patterns:

  • * matches zero or more of any character (e.g., "my-mcp*" matches my-mcp_search, my-mcp_list, etc.)
  • ? matches exactly one character
  • All other characters match literally

:::note
MCP server tools are registered with server name as prefix, so to disable all tools for a server simply use:

text
"mymcpservername_*": false

:::


Examples

Below are examples of some common MCP servers. You can submit a PR if you want to document other servers.


Sentry

Add the Sentry MCP server to interact with your Sentry projects and issues.

json title="opencode.json" {4-8}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "sentry": {
      "type": "remote",
      "url": "https://mcp.sentry.dev/mcp",
      "oauth": {}
    }
  }
}

After adding the configuration, authenticate with Sentry:

bash
opencode mcp auth sentry

This will open a browser window to complete the OAuth flow and connect OpenCode to your Sentry account.

Once authenticated, you can use Sentry tools in your prompts to query issues, projects, and error data.

txt "use sentry"
Show me the latest unresolved issues in my project. use sentry

Context7

Add the Context7 MCP server to search through docs.

json title="opencode.json" {4-7}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "context7": {
      "type": "remote",
      "url": "https://mcp.context7.com/mcp"
    }
  }
}

If you have signed up for a free account, you can use your API key and get higher rate-limits.

json title="opencode.json" {7-9}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "context7": {
      "type": "remote",
      "url": "https://mcp.context7.com/mcp",
      "headers": {
        "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}"
      }
    }
  }
}

Here we are assuming that you have the CONTEXT7_API_KEY environment variable set.

Add use context7 to your prompts to use Context7 MCP server.

txt "use context7"
Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7

Alternatively, you can add something like this to your AGENTS.md.

md title="agents.md"
When you need to search docs, use `context7` tools.

Grep by Vercel

Add the Grep by Vercel MCP server to search through code snippets on GitHub.

json title="opencode.json" {4-7}
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "gh_grep": {
      "type": "remote",
      "url": "https://mcp.grep.app"
    }
  }
}

Since we named our MCP server gh_grep, you can add use the gh_grep tool to your prompts to get the agent to use it.

txt "use the gh_grep tool"
What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool

Alternatively, you can add something like this to your AGENTS.md.

md title="agents.md"
If you are unsure how to do something, use `gh_grep` to search code examples from GitHub.

Packages Web Src Content Docs Models (`packages/web/src/content/docs/models.mdx`)


title: Models

OpenCode uses the AI SDK and Models.dev to support 75+ LLM providers and it supports running local models.


Providers

Most popular providers are preloaded by default. If you've added the credentials for a provider through the /connect command, they'll be available when you start OpenCode.

Learn more about providers.


Select a model

Once you've configured your provider you can select the model you want by typing in:

bash frame="none"
/models

There are a lot of models out there, with new models coming out every week.

:::tip
Consider using one of the models we recommend.
:::

However, there are only a few of them that are good at both generating code and tool calling.

Here are several models that work well with OpenCode, in no particular order. (This is not an exhaustive list nor is it necessarily up to date):

  • GPT 5.2
  • GPT 5.1 Codex
  • Claude Opus 4.5
  • Claude Sonnet 4.5
  • Minimax M2.1
  • Gemini 3 Pro

Set a default

To set one of these as the default model, you can set the model key in your
OpenCode config.

json title="opencode.json" {3}
{
  "$schema": "https://opencode.ai/config.json",
  "model": "lmstudio/google/gemma-3n-e4b"
}

Here the full ID is provider_id/model_id. For example, if you're using OpenCode Zen, you would use opencode/gpt-5.1-codex for GPT 5.1 Codex.

If you've configured a custom provider, the provider_id is key from the provider part of your config, and the model_id is the key from provider.models.


Configure models

You can globally configure a model's options through the config.

jsonc title="opencode.jsonc" {7-12,19-24}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "openai": {
      "models": {
        "gpt-5": {
          "options": {
            "reasoningEffort": "high",
            "textVerbosity": "low",
            "reasoningSummary": "auto",
            "include": ["reasoning.encrypted_content"],
          },
        },
      },
    },
    "anthropic": {
      "models": {
        "claude-sonnet-4-5-20250929": {
          "options": {
            "thinking": {
              "type": "enabled",
              "budgetTokens": 16000,
            },
          },
        },
      },
    },
  },
}

Here we're configuring global settings for two built-in models: gpt-5 when accessed via the openai provider, and claude-sonnet-4-20250514 when accessed via the anthropic provider.
The built-in provider and model names can be found on Models.dev.

You can also configure these options for any agents that you are using. The agent config overrides any global options here. Learn more.

You can also define custom variants that extend built-in ones. Variants let you configure different settings for the same model without creating duplicate entries:

jsonc title="opencode.jsonc" {6-21}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "opencode": {
      "models": {
        "gpt-5": {
          "variants": {
            "high": {
              "reasoningEffort": "high",
              "textVerbosity": "low",
              "reasoningSummary": "auto",
            },
            "low": {
              "reasoningEffort": "low",
              "textVerbosity": "low",
              "reasoningSummary": "auto",
            },
          },
        },
      },
    },
  },
}

Variants

Many models support multiple variants with different configurations. OpenCode ships with built-in default variants for popular providers.

Built-in variants

OpenCode ships with default variants for many providers:

Anthropic:

  • high - High thinking budget (default)
  • max - Maximum thinking budget

OpenAI:

Varies by model but roughly:

  • none - No reasoning
  • minimal - Minimal reasoning effort
  • low - Low reasoning effort
  • medium - Medium reasoning effort
  • high - High reasoning effort
  • xhigh - Extra high reasoning effort

Google:

  • low - Lower effort/token budget
  • high - Higher effort/token budget

:::tip
This list is not comprehensive. Many other providers have built-in defaults too.
:::

Custom variants

You can override existing variants or add your own:

jsonc title="opencode.jsonc" {7-18}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "openai": {
      "models": {
        "gpt-5": {
          "variants": {
            "thinking": {
              "reasoningEffort": "high",
              "textVerbosity": "low",
            },
            "fast": {
              "disabled": true,
            },
          },
        },
      },
    },
  },
}

Cycle variants

Use the keybind variant_cycle to quickly switch between variants. Learn more.


Loading models

When OpenCode starts up, it checks for models in the following priority order:

  1. The --model or -m command line flag. The format is the same as in the config file: provider_id/model_id.

  2. The model list in the OpenCode config.

    json title="opencode.json"
    {
      "$schema": "https://opencode.ai/config.json",
      "model": "anthropic/claude-sonnet-4-20250514"
    }

    The format here is provider/model.

  3. The last used model.

  4. The first model using an internal priority.


Packages Web Src Content Docs Network (`packages/web/src/content/docs/network.mdx`)


title: Network

OpenCode supports standard proxy environment variables and custom certificates for enterprise network environments.


Proxy

OpenCode respects standard proxy environment variables.

bash
# HTTPS proxy (recommended)
export HTTPS_PROXY=https://proxy.example.com:8080

# HTTP proxy (if HTTPS not available)
export HTTP_PROXY=http://proxy.example.com:8080

# Bypass proxy for local server (required)
export NO_PROXY=localhost,127.0.0.1

:::caution
The TUI communicates with a local HTTP server. You must bypass the proxy for this connection to prevent routing loops.
:::

You can configure the server's port and hostname using CLI flags.


Authenticate

If your proxy requires basic authentication, include credentials in the URL.

bash
export HTTPS_PROXY=http://username:[email protected]:8080

:::caution
Avoid hardcoding passwords. Use environment variables or secure credential storage.
:::

For proxies requiring advanced authentication like NTLM or Kerberos, consider using an LLM Gateway that supports your authentication method.


Custom certificates

If your enterprise uses custom CAs for HTTPS connections, configure OpenCode to trust them.

bash
export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem

This works for both proxy connections and direct API access.


Packages Web Src Content Docs Permissions (`packages/web/src/content/docs/permissions.mdx`)


title: Permissions

OpenCode uses the permission config to decide whether a given action should run automatically, prompt you, or be blocked.

As of v1.1.1, the legacy tools boolean config is deprecated and has been merged into permission. The old tools config is still supported for backwards compatibility.


Actions

Each permission rule resolves to one of:

  • "allow" — run without approval
  • "ask" — prompt for approval
  • "deny" — block the action

Auto mode

Start OpenCode with --auto to automatically approve permission requests that are not explicitly denied.

bash
opencode --auto

You can also use auto mode with opencode run.

bash
opencode run --auto "Refactor this module"

Explicit "deny" rules are still enforced. Auto mode only changes requests that would otherwise ask for approval.

In the TUI, open the command palette and select Enable auto-approve permissions or Disable auto-approve permissions to change modes. When auto mode is active, the prompt displays a muted auto indicator next to the current agent.


Configuration

You can set permissions globally (with *), and override specific tools.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "*": "ask",
    "shell": "allow",
    "edit": "deny"
  }
}

You can also set all permissions at once:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": "allow"
}

Granular Rules (Object Syntax)

For most permissions, you can use an object to apply different actions based on the tool input.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "shell": {
      "*": "ask",
      "git *": "allow",
      "npm *": "allow",
      "rm *": "deny",
      "grep *": "allow"
    },
    "edit": {
      "*": "deny",
      "packages/web/src/content/docs/*.mdx": "allow"
    },
    "webfetch": {
      "*": "ask",
      "https://en.wikipedia.org/*": "allow"
    }
  }
}

Rules are evaluated by pattern match, with the last matching rule winning. A common pattern is to put the catch-all "*" rule first, and more specific rules after it.

Wildcards

Permission patterns use simple wildcard matching:

  • * matches zero or more of any character
  • ? matches exactly one character
  • All other characters match literally

Home Directory Expansion

You can use ~ or $HOME at the start of a pattern to reference your home directory. This is particularly useful for external_directory rules.

  • ~/projects/* -> /Users/username/projects/*
  • $HOME/projects/* -> /Users/username/projects/*
  • ~ -> /Users/username

External Directories

Use external_directory to allow tool calls that touch paths outside the working directory where OpenCode was started. This applies to any tool that takes a path as input (for example read, edit, glob, grep, and many shell commands).

Home expansion (like ~/...) only affects how a pattern is written. It does not make an external path part of the current workspace, so paths outside the working directory must still be allowed via external_directory.

For example, this allows access to everything under ~/projects/personal/:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "external_directory": {
      "~/projects/personal/**": "allow"
    }
  }
}

Any directory allowed here inherits the same defaults as the current workspace. Since read defaults to allow, reads are also allowed for entries under external_directory unless overridden. Add explicit rules when a tool should be restricted in these paths, such as blocking edits while keeping reads:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "external_directory": {
      "~/projects/personal/**": "allow"
    },
    "edit": {
      "~/projects/personal/**": "deny"
    }
  }
}

Keep the list focused on trusted paths, and layer extra allow or deny rules as needed for other tools (for example shell).


Available Permissions

OpenCode permissions are keyed by tool name, plus a couple of safety guards:

  • read — reading a file (matches the file path)
  • edit — all file modifications (covers edit, write, patch)
  • glob — file globbing (matches the glob pattern)
  • grep — content search (matches the regex pattern)
  • shell — running shell commands (matches parsed commands like git status --porcelain)
  • task — launching subagents (matches the subagent type)
  • skill — loading a skill (matches the skill name)
  • lsp — running LSP queries (currently non-granular)
  • question — asking the user questions during execution
  • webfetch — fetching a URL (matches the URL)
  • websearch — web search
  • external_directory — triggered when a tool touches paths outside the project working directory
  • doom_loop — triggered when the same tool call repeats 3 times with identical input

Defaults

If you don’t specify anything, OpenCode starts from permissive defaults:

  • Most permissions default to "allow".
  • doom_loop and external_directory default to "ask".
  • read is "allow", but .env files are denied by default:
json title="opencode.json"
{
  "permission": {
    "read": {
      "*": "allow",
      "*.env": "deny",
      "*.env.*": "deny",
      "*.env.example": "allow"
    }
  }
}

What “Ask” Does

When OpenCode prompts for approval, the UI offers three outcomes:

  • once — approve just this request
  • always — approve future requests matching the suggested patterns (for the rest of the current OpenCode session)
  • reject — deny the request

The set of patterns that always would approve is provided by the tool (for example, shell approvals typically whitelist a safe command prefix like git status*).


Agents

You can override permissions per agent. Agent permissions are merged with the global config, and agent rules take precedence. Learn more about agent permissions.

:::note
Refer to the Granular Rules (Object Syntax) section above for more detailed pattern matching examples.
:::

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "shell": {
      "*": "ask",
      "git *": "allow",
      "git commit *": "deny",
      "git push *": "deny",
      "grep *": "allow"
    }
  },
  "agent": {
    "build": {
      "permission": {
        "shell": {
          "*": "ask",
          "git *": "allow",
          "git commit *": "ask",
          "git push *": "deny",
          "grep *": "allow"
        }
      }
    }
  }
}

You can also configure agent permissions in Markdown:

markdown title="~/.config/opencode/agents/review.md"
---
description: Code review without edits
mode: subagent
permission:
  edit: deny
  shell: ask
  webfetch: deny
---

Only analyze code and suggest changes.

:::tip
Use pattern matching for commands with arguments. "grep *" allows grep pattern file.txt, while "grep" alone would block it. Commands like git status work for default behavior but require explicit permission (like "git status *") when arguments are passed.
:::


Packages Web Src Content Docs Plugins (`packages/web/src/content/docs/plugins.mdx`)


title: Plugins

Plugins allow you to extend OpenCode by hooking into various events and customizing behavior. You can create plugins to add new features, integrate with external services, or modify OpenCode's default behavior.

For examples, check out the plugins created by the community.


Use a plugin

There are two ways to load plugins.


From local files

Place JavaScript or TypeScript files in the plugin directory.

  • .opencode/plugins/ - Project-level plugins
  • ~/.config/opencode/plugins/ - Global plugins

Files in these directories are automatically loaded at startup.


From npm

Specify npm packages in your config file.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]
}

Both regular and scoped npm packages are supported.

Browse available plugins in the ecosystem.


How plugins are installed

npm plugins are installed automatically using Bun at startup. Packages and their dependencies are cached in ~/.cache/opencode/node_modules/.

Local plugins are loaded directly from the plugin directory. To use external packages, you must create a package.json within your config directory (see Dependencies), or publish the plugin to npm and add it to your config.


Load order

Plugins are loaded from all sources and all hooks run in sequence. The load order is:

  1. Global config (~/.config/opencode/opencode.json)
  2. Project config (opencode.json)
  3. Global plugin directory (~/.config/opencode/plugins/)
  4. Project plugin directory (.opencode/plugins/)

Duplicate npm packages with the same name and version are loaded once. However, a local plugin and an npm plugin with similar names are both loaded separately.


Create a plugin

A plugin is a JavaScript/TypeScript module that exports one or more plugin
functions. Each function receives a context object and returns a hooks object.


Dependencies

Local plugins and custom tools can use external npm packages. Add a package.json to your config directory with the dependencies you need.

json title=".opencode/package.json"
{
  "dependencies": {
    "shescape": "^2.1.0"
  }
}

OpenCode runs bun install at startup to install these. Your plugins and tools can then import them.

ts title=".opencode/plugins/my-plugin.ts"
import { escape } from "shescape"

export const MyPlugin = async (ctx) => {
  return {
    "tool.execute.before": async (input, output) => {
      if (input.tool === "shell") {
        output.args.command = escape(output.args.command)
      }
    },
  }
}

Basic structure

js title=".opencode/plugins/example.js"
export const MyPlugin = async ({ project, client, $, directory, worktree }) => {
  console.log("Plugin initialized!")

  return {
    // Hook implementations go here
  }
}

The plugin function receives:

  • project: The current project information.
  • directory: The current working directory.
  • worktree: The git worktree path.
  • client: An opencode SDK client for interacting with the AI.
  • $: Bun's shell API for executing commands.

TypeScript support

For TypeScript plugins, you can import types from the plugin package:

ts title="my-plugin.ts" {1}
import type { Plugin } from "@opencode-ai/plugin"

export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => {
  return {
    // Type-safe hook implementations
  }
}

Events

Plugins can subscribe to events as seen below in the Examples section. Here is a list of the different events available.

Command Events

  • command.executed

File Events

  • file.edited
  • file.watcher.updated

Installation Events

  • installation.updated

LSP Events

  • lsp.client.diagnostics
  • lsp.updated

Message Events

  • message.part.removed
  • message.part.updated
  • message.removed
  • message.updated

Permission Events

  • permission.asked
  • permission.replied

Server Events

  • server.connected

Session Events

  • session.created
  • session.compacted
  • session.deleted
  • session.diff
  • session.error
  • session.idle
  • session.status
  • session.updated

Shell Events

  • shell.env

Tool Events

  • tool.execute.after
  • tool.execute.before

TUI Events

  • tui.prompt.append
  • tui.command.execute
  • tui.toast.show

Examples

Here are some examples of plugins you can use to extend opencode.


Send notifications

Send notifications when certain events occur:

js title=".opencode/plugins/notification.js"
export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => {
  return {
    event: async ({ event }) => {
      // Send notification on session completion
      if (event.type === "session.idle") {
        await $`osascript -e 'display notification "Session completed!" with title "opencode"'`
      }
    },
  }
}

We are using osascript to run AppleScript on macOS. Here we are using it to send notifications.

:::note
If you’re using the OpenCode desktop app, it can send system notifications automatically when a response is ready or when a session errors.
:::


.env protection

Prevent opencode from reading .env files:

javascript title=".opencode/plugins/env-protection.js"
export const EnvProtection = async ({ project, client, $, directory, worktree }) => {
  return {
    "tool.execute.before": async (input, output) => {
      if (input.tool === "read" && output.args.filePath.includes(".env")) {
        throw new Error("Do not read .env files")
      }
    },
  }
}

Inject environment variables

Inject environment variables into all shell execution (AI tools and user terminals):

javascript title=".opencode/plugins/inject-env.js"
export const InjectEnvPlugin = async () => {
  return {
    "shell.env": async (input, output) => {
      output.env.MY_API_KEY = "secret"
      output.env.PROJECT_ROOT = input.cwd
    },
  }
}

Custom tools

Plugins can also add custom tools to opencode:

ts title=".opencode/plugins/custom-tools.ts"
import { type Plugin, tool } from "@opencode-ai/plugin"

export const CustomToolsPlugin: Plugin = async (ctx) => {
  return {
    tool: {
      mytool: tool({
        description: "This is a custom tool",
        args: {
          foo: tool.schema.string(),
        },
        async execute(args, context) {
          const { directory, worktree } = context
          return `Hello ${args.foo} from ${directory} (worktree: ${worktree})`
        },
      }),
    },
  }
}

The tool helper creates a custom tool that opencode can call. It takes a Zod schema function and returns a tool definition with:

  • description: What the tool does
  • args: Zod schema for the tool's arguments
  • execute: Function that runs when the tool is called

Your custom tools will be available to opencode alongside built-in tools.

:::note
If a plugin tool uses the same name as a built-in tool, the plugin tool takes precedence.
:::


Logging

Use client.app.log() instead of console.log for structured logging:

ts title=".opencode/plugins/my-plugin.ts"
export const MyPlugin = async ({ client }) => {
  await client.app.log({
    body: {
      service: "my-plugin",
      level: "info",
      message: "Plugin initialized",
      extra: { foo: "bar" },
    },
  })
}

Levels: debug, info, warn, error. See SDK documentation for details.


Compaction hooks

Customize the context included when a session is compacted:

ts title=".opencode/plugins/compaction.ts"
import type { Plugin } from "@opencode-ai/plugin"

export const CompactionPlugin: Plugin = async (ctx) => {
  return {
    "experimental.session.compacting": async (input, output) => {
      // Inject additional context into the compaction prompt
      output.context.push(`
## Custom Context

Include any state that should persist across compaction:
- Current task status
- Important decisions made
- Files being actively worked on
`)
    },
  }
}

The experimental.session.compacting hook fires before the LLM generates a continuation summary. Use it to inject domain-specific context that the default compaction prompt would miss.

You can also replace the compaction prompt entirely by setting output.prompt:

ts title=".opencode/plugins/custom-compaction.ts"
import type { Plugin } from "@opencode-ai/plugin"

export const CustomCompactionPlugin: Plugin = async (ctx) => {
  return {
    "experimental.session.compacting": async (input, output) => {
      // Replace the entire compaction prompt
      output.prompt = `
You are generating a continuation prompt for a multi-agent swarm session.

Summarize:
1. The current task and its status
2. Which files are being modified and by whom
3. Any blockers or dependencies between agents
4. The next steps to complete the work

Format as a structured prompt that a new agent can use to resume work.
`
    },
  }
}

When output.prompt is set, it completely replaces the default compaction prompt. The output.context array is ignored in this case.


Packages Web Src Content Docs Policies (`packages/web/src/content/docs/policies.mdx`)


title: Policies

Policies control whether OpenCode may perform an action on a named resource. This feature is experimental and is configured with the experimental.policies array in opencode.json.

Policies are separate from permissions. Permissions control what tools can do during a session, while policies control whether OpenCode may use a resource such as an LLM provider.


Configuration

Each policy statement has three fields:

  • effect - Either "allow" or "deny".
  • action - The operation being controlled.
  • resource - The resource ID or wildcard pattern the statement applies to.

For example, deny use of the openai provider:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "experimental": {
    "policies": [
      {
        "effect": "deny",
        "action": "provider.use",
        "resource": "openai"
      }
    ]
  }
}

A provider denied by policy is not available for model selection or model use, even if it has credentials or is otherwise configured correctly.


Available Policies

OpenCode currently supports one policy action:

Action Resource Description
provider.use Provider ID, such as openai Allow or deny use of an LLM provider.

More policy actions may be added in the future.


Matching

The resource field supports wildcard matching. Use * to match zero or more characters and ? to match one character.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "experimental": {
    "policies": [
      {
        "effect": "deny",
        "action": "provider.use",
        "resource": "company-*"
      }
    ]
  }
}

This denies providers such as company-us and company-eu.


Rule Order

When multiple statements match, the last matching statement wins. Put broad rules first, then more specific exceptions after them.

For example, allow only Anthropic:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "experimental": {
    "policies": [
      {
        "effect": "deny",
        "action": "provider.use",
        "resource": "*"
      },
      {
        "effect": "allow",
        "action": "provider.use",
        "resource": "anthropic"
      }
    ]
  }
}

If no policy matches a provider, provider use is allowed by default.

Policies may be set in both your global config and project config. If policies from both locations match the same provider, your global policy takes priority over the project policy. This prevents a repository from re-enabling a provider that you deny globally.


Provider Lists

Use policies instead of the older disabled_providers and enabled_providers settings when controlling provider access.

To replace disabled_providers:

json title="opencode.json"
{
  "experimental": {
    "policies": [
      { "effect": "deny", "action": "provider.use", "resource": "openai" },
      { "effect": "deny", "action": "provider.use", "resource": "google" }
    ]
  }
}

To replace enabled_providers, deny all providers first and allow the selected providers after it:

json title="opencode.json"
{
  "experimental": {
    "policies": [
      { "effect": "deny", "action": "provider.use", "resource": "*" },
      { "effect": "allow", "action": "provider.use", "resource": "anthropic" },
      { "effect": "allow", "action": "provider.use", "resource": "openai" }
    ]
  }
}

Packages Web Src Content Docs Providers (`packages/web/src/content/docs/providers.mdx`)


title: Providers

import config from "../../../config.mjs"
export const console = config.console

OpenCode uses the AI SDK and Models.dev to support 75+ LLM providers and it supports running local models.

To add a provider you need to:

  1. Add the API keys for the provider using the /connect command.
  2. Configure the provider in your OpenCode config.

Credentials

When you add a provider's API keys with the /connect command, they are stored
in ~/.local/share/opencode/auth.json.


Config

You can customize the providers through the provider section in your OpenCode
config.


Base URL

You can customize the base URL for any provider by setting the baseURL option. This is useful when using proxy services or custom endpoints.

json title="opencode.json" {6}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "anthropic": {
      "options": {
        "baseURL": "https://api.anthropic.com/v1"
      }
    }
  }
}

Hiding models

You can hide specific models from the /models picker for a provider using the blacklist option. This is useful when a provider exposes models you don't want to use or select.

json title="opencode.json" {6}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "anthropic": {
      "blacklist": ["claude-opus-4-20250514"]
    }
  }
}

The inverse whitelist option hides every model except the ones listed.

json title="opencode.json" {6}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "anthropic": {
      "whitelist": ["claude-sonnet-4-20250514"]
    }
  }
}

Both options take an array of model IDs — the same IDs shown in the /models picker.

  • blacklist removes the listed models from the picker.
  • whitelist keeps only the listed models and hides the rest.
  • You can combine them: whitelist narrows the set, then blacklist removes entries from it.

OpenCode Zen

OpenCode Zen is a list of models provided by the OpenCode team that have been
tested and verified to work well with OpenCode. Learn more.

:::tip
If you are new, we recommend starting with OpenCode Zen.
:::

  1. Run the /connect command in the TUI, select OpenCode Zen, and head to opencode.ai/auth.

    txt
    /connect
  2. Sign in, add your billing details, and copy your API key.

  3. Paste your API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run /models in the TUI to see the list of models we recommend.

    txt
    /models

It works like any other provider in OpenCode and is completely optional to use.


OpenCode Go

OpenCode Go is a low cost subscription plan that provides reliable access to popular open coding models provided by the OpenCode team that have been
tested and verified to work well with OpenCode.

  1. Run the /connect command in the TUI, select OpenCode Go, and head to opencode.ai/auth.

    txt
    /connect
  2. Sign in, add your billing details, and copy your API key.

  3. Paste your API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run /models in the TUI to see the list of models we recommend.

    txt
    /models

It works like any other provider in OpenCode and is completely optional to use.


Directory

Let's look at some of the providers in detail. If you'd like to add a provider to the
list, feel free to open a PR.

:::note
Don't see a provider here? Submit a PR.
:::


302.AI

  1. Head over to the 302.AI console, create an account, and generate an API key.

  2. Run the /connect command and search for 302.AI.

    txt
    /connect
  3. Enter your 302.AI API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

Amazon Bedrock

To use Amazon Bedrock with OpenCode:

  1. Head over to the Model catalog in the Amazon Bedrock console and request
    access to the models you want.

    :::tip
    You need to have access to the model you want in Amazon Bedrock.
    :::

  2. Configure authentication using one of the following methods:


    Environment Variables (Quick Start)

    Set one of these environment variables while running opencode:

    bash
    # Option 1: Using AWS access keys
    AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=YYY opencode
    
    # Option 2: Using named AWS profile
    AWS_PROFILE=my-profile opencode
    
    # Option 3: Using Bedrock bearer token
    AWS_BEARER_TOKEN_BEDROCK=XXX opencode

    Or add them to your bash profile:

    bash title="~/.bash_profile"
    export AWS_PROFILE=my-dev-profile
    export AWS_REGION=us-east-1

    For project-specific or persistent configuration, use opencode.json:

    json title="opencode.json"
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "amazon-bedrock": {
          "options": {
            "region": "us-east-1",
            "profile": "my-aws-profile"
          }
        }
      }
    }

    Available options:

    • region - AWS region (e.g., us-east-1, eu-west-1)
    • profile - AWS named profile from ~/.aws/credentials
    • endpoint - Custom endpoint URL for VPC endpoints (alias for generic baseURL option)

    :::tip
    Configuration file options take precedence over environment variables.
    :::


    Advanced: VPC Endpoints

    If you're using VPC endpoints for Bedrock:

    json title="opencode.json"
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "amazon-bedrock": {
          "options": {
            "region": "us-east-1",
            "profile": "production",
            "endpoint": "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com"
          }
        }
      }
    }

    :::note
    The endpoint option is an alias for the generic baseURL option, using AWS-specific terminology. If both endpoint and baseURL are specified, endpoint takes precedence.
    :::


    Authentication Methods

    • AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY: Create an IAM user and generate access keys in the AWS Console
    • AWS_PROFILE: Use named profiles from ~/.aws/credentials. First configure with aws configure --profile my-profile or aws sso login
    • AWS_BEARER_TOKEN_BEDROCK: Generate long-term API keys from the Amazon Bedrock console
    • AWS_WEB_IDENTITY_TOKEN_FILE / AWS_ROLE_ARN: For EKS IRSA (IAM Roles for Service Accounts) or other Kubernetes environments with OIDC federation. These environment variables are automatically injected by Kubernetes when using service account annotations.

    Authentication Precedence

    Amazon Bedrock uses the following authentication priority:

    1. Bearer Token - AWS_BEARER_TOKEN_BEDROCK environment variable or token from /connect command
    2. AWS Credential Chain - Profile, access keys, shared credentials, IAM roles, Web Identity Tokens (EKS IRSA), instance metadata

    :::note
    When a bearer token is set (via /connect or AWS_BEARER_TOKEN_BEDROCK), it takes precedence over all AWS credential methods including configured profiles.
    :::

  3. Run the /models command to select the model you want.

    txt
    /models

:::note
For custom inference profiles, use the model and provider name in the key and set the id property to the arn. This ensures correct caching.
:::

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "amazon-bedrock": {
      // ...
      "models": {
        "anthropic-claude-sonnet-4.5": {
          "id": "arn:aws:bedrock:us-east-1:xxx:application-inference-profile/yyy"
        }
      }
    }
  }
}

Anthropic

  1. Once you've signed up, run the /connect command and select Anthropic.

    txt
    /connect
  2. Here you can select the Claude Pro/Max option and it'll open your browser
    and ask you to authenticate.

    txt
    ┌ Select auth method
    │
    │ Manually enter API Key
    └
  3. Now all the Anthropic models should be available when you use the /models command.

    txt
    /models

:::info
There are plugins that allow you to use your Claude Pro/Max models with
OpenCode. Anthropic explicitly prohibits this.

Previous versions of OpenCode came bundled with these plugins but that is no
longer the case as of 1.3.0

Other companies support freedom of choice with developer tooling - you can use
the following subscriptions in OpenCode with zero setup:

  • ChatGPT Plus
  • Github Copilot
  • Gitlab Duo
    :::

Atomic Chat

You can configure opencode to use local models through Atomic Chat, a desktop application that runs local LLMs behind an OpenAI-compatible API server (default endpoint http://127.0.0.1:1337/v1).

json title="opencode.json" "atomic-chat" {5, 6, 8, 10-14}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "atomic-chat": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Atomic Chat (local)",
      "options": {
        "baseURL": "http://127.0.0.1:1337/v1"
      },
      "models": {
        "<your-model-id>": {
          "name": "<your-model-name>"
        }
      }
    }
  }
}

In this example:

  • atomic-chat is the custom provider ID. This can be any string you want.
  • npm specifies the package to use for this provider. Here, @ai-sdk/openai-compatible is used for any OpenAI-compatible API.
  • name is the display name for the provider in the UI.
  • options.baseURL is the endpoint for the local server. Change the host and port to match your Atomic Chat setup.
  • models is a map of model IDs to their display names. Each ID must match the id returned by GET /v1/models — run curl http://127.0.0.1:1337/v1/models to list the ids currently loaded in Atomic Chat.

:::tip
If tool calls aren't working well, pick a loaded model with strong tool-calling support (for example, a Qwen-Coder or DeepSeek-Coder variant).
:::


Azure OpenAI

:::note
If you encounter "I'm sorry, but I cannot assist with that request" errors, try changing the content filter from DefaultV2 to Default in your Azure resource.
:::

  1. Head over to the Azure portal and create an Azure OpenAI resource. You'll need:

    • Resource name: This becomes part of your API endpoint (https://RESOURCE_NAME.openai.azure.com/)
    • API key: Either KEY 1 or KEY 2 from your resource
  2. Go to Azure AI Foundry and deploy a model.

    :::note
    The deployment name must match the model name for opencode to work properly.
    :::

  3. Run the /connect command and search for Azure.

    txt
    /connect
  4. Enter your API key.

    txt
    ┌ API key
    │
    │
    └ enter
  5. Set your resource name as an environment variable:

    bash
    AZURE_RESOURCE_NAME=XXX opencode

    Or add it to your bash profile:

    bash title="~/.bash_profile"
    export AZURE_RESOURCE_NAME=XXX
  6. Run the /models command to select your deployed model.

    txt
    /models

Microsoft Entra ID (Azure CLI)

You can use your Azure CLI session instead of an API key. Install the Azure CLI, run az login, then run /connect, select Azure, and choose Microsoft Entra ID (Azure CLI). Enter the Azure Resource name when prompted. Use az login --tenant TENANT_ID if the Resource belongs to a different tenant.

Find the Resource name by opening your Azure OpenAI or Foundry Resource in the Azure portal or Microsoft Foundry. It is also the first part of the endpoint: my-models in https://my-models.openai.azure.com/ or https://my-models.services.ai.azure.com/. If your identity can list Resources, you can also find their names and Resource groups with:

bash
az cognitiveservices account list \
  --query "[].{name:name,resourceGroup:resourceGroup}" \
  --output table

OpenCode does not query Azure management APIs or discover deployments. Select a model whose catalog name matches your deployment, or configure its deployment name explicitly:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "azure": {
      "models": {
        "gpt-5-mini": {
          "id": "gpt-production"
        }
      }
    }
  }
}

Assign your identity the inference role required by the deployment: Cognitive Services OpenAI User for Azure OpenAI models or Cognitive Services User for other Foundry models. OpenCode refreshes access tokens through the Azure CLI, including versions earlier than 2.54.0, so you only need to sign in again when the CLI session expires.


Azure Cognitive Services

  1. Head over to the Azure portal and create an Azure OpenAI resource. You'll need:

    • Resource name: This becomes part of your API endpoint (https://AZURE_COGNITIVE_SERVICES_RESOURCE_NAME.cognitiveservices.azure.com/)
    • API key: Either KEY 1 or KEY 2 from your resource
  2. Go to Azure AI Foundry and deploy a model.

    :::note
    The deployment name must match the model name for opencode to work properly.
    :::

  3. Run the /connect command and search for Azure Cognitive Services.

    txt
    /connect
  4. Enter your API key.

    txt
    ┌ API key
    │
    │
    └ enter
  5. Set your resource name as an environment variable:

    bash
    AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX opencode

    Or add it to your bash profile:

    bash title="~/.bash_profile"
    export AZURE_COGNITIVE_SERVICES_RESOURCE_NAME=XXX
  6. Run the /models command to select your deployed model.

    txt
    /models

Baseten

  1. Head over to the Baseten, create an account, and generate an API key.

  2. Run the /connect command and search for Baseten.

    txt
    /connect
  3. Enter your Baseten API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

Cerebras

  1. Head over to the Cerebras console, create an account, and generate an API key.

  2. Run the /connect command and search for Cerebras.

    txt
    /connect
  3. Enter your Cerebras API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Qwen 3 Coder 480B.

    txt
    /models

Cloudflare AI Gateway

Cloudflare AI Gateway lets you access models from OpenAI, Anthropic, Workers AI, and more through a unified endpoint. With Unified Billing you don't need separate API keys for each provider.

  1. Head over to the Cloudflare dashboard, navigate to AI > AI Gateway, and create a new gateway. Note your Account ID and Gateway ID.

  2. Run the /connect command and search for Cloudflare AI Gateway.

    txt
    /connect
  3. Enter your Account ID when prompted.

    txt
    ┌ Enter your Cloudflare Account ID
    │
    │
    └ enter
  4. Enter your Gateway ID when prompted.

    txt
    ┌ Enter your Cloudflare AI Gateway ID
    │
    │
    └ enter
  5. Enter your Cloudflare API token.

    txt
    ┌ Gateway API token
    │
    │
    └ enter
  6. Run the /models command to select a model.

    txt
    /models

    You can also add models through your opencode config.

    json title="opencode.json"
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "cloudflare-ai-gateway": {
          "models": {
            "openai/gpt-4o": {},
            "anthropic/claude-sonnet-4": {}
          }
        }
      }
    }

    Alternatively, you can set environment variables instead of using /connect.

    bash title="~/.bash_profile"
    export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id
    export CLOUDFLARE_GATEWAY_ID=your-gateway-id
    export CLOUDFLARE_API_TOKEN=your-api-token

Cloudflare Workers AI

Cloudflare Workers AI lets you run AI models on Cloudflare's global network directly via REST API, with no separate provider accounts needed for supported models.

  1. Head over to the Cloudflare dashboard, navigate to Workers AI, and select Use REST API to get your Account ID and create an API token.

  2. Run the /connect command and search for Cloudflare Workers AI.

    txt
    /connect
  3. Enter your Account ID when prompted.

    txt
    ┌ Enter your Cloudflare Account ID
    │
    │
    └ enter
  4. Enter your Cloudflare API key.

    txt
    ┌ API key
    │
    │
    └ enter
  5. Run the /models command to select a model.

    txt
    /models

    Alternatively, you can set environment variables instead of using /connect.

    bash title="~/.bash_profile"
    export CLOUDFLARE_ACCOUNT_ID=your-32-character-account-id
    export CLOUDFLARE_API_KEY=your-api-token

Cortecs

  1. Head over to the Cortecs console, create an account, and generate an API key.

  2. Run the /connect command and search for Cortecs.

    txt
    /connect
  3. Enter your Cortecs API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Kimi K2 Instruct.

    txt
    /models

DeepSeek

  1. Head over to the DeepSeek console, create an account, and click Create new API key.

  2. Run the /connect command and search for DeepSeek.

    txt
    /connect
  3. Enter your DeepSeek API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a DeepSeek model like DeepSeek V4 Pro.

    txt
    /models

Deep Infra

  1. Head over to the Deep Infra dashboard, create an account, and generate an API key.

  2. Run the /connect command and search for Deep Infra.

    txt
    /connect
  3. Enter your Deep Infra API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

DigitalOcean

DigitalOcean's Inference Engine provides access to open models like GPT-OSS, Llama, Qwen, and DeepSeek, plus custom Inference Routers that route each request to the cheapest, fastest, or best-fit model for a task.

OpenCode supports two authentication methods:

  • OAuth (Recommended) — Sign in to your DigitalOcean account; OpenCode uses your DigitalOcean API token directly for inference and discovers your Inference Routers.
  • Model Access Key — Paste an existing key from the DigitalOcean console.
  1. Run the /connect command and search for DigitalOcean.

    txt
    /connect
  2. Select Login with DigitalOcean.

    txt
    ┌ Select auth method
    │
    │ Login with DigitalOcean
    │ Paste Model Access Key
    └
  3. Your browser opens to authorize OpenCode. Sign in and approve.

    :::note
    OpenCode requests genai:read and inference:query OAuth scopes. Your DigitalOcean API token is used directly for inference — no separate Model Access Key is created.
    :::

    :::note
    Inference Routers only appear in the model picker after OAuth. Pasting a Model Access Key manually does not discover routers.
    :::

  4. Run the /models command. Your Inference Routers appear as the format router: in the model selection.

    txt
    /models
  5. To pick up newly created Inference Routers, re-run /connect and select DigitalOcean again.

Using a Model Access Key

If you'd rather paste a key directly:

  1. Head over to the Manage page in the Inference section of the DigitalOcean console and create a new key.

  2. Run the /connect command and select DigitalOcean, then Paste Model Access Key.

    txt
    ┌ Enter your DigitalOcean Model Access Key
    │
    │
    └ enter

    :::note
    Inference Routers are not auto-discovered with this method. To surface them in the model picker, sign in via OAuth instead.
    :::

  3. Run the /models command to select a model.

    txt
    /models

Environment Variable

Alternatively, set your Model Access Key as an environment variable.

bash frame="none"
export DIGITALOCEAN_ACCESS_TOKEN=your-model-access-key

Inference Routers

Inference Routers let you define a routing policy across multiple models — picking the cheapest, fastest, or most appropriate model per request based on the task. After OAuth, OpenCode surfaces each router as router:<router-name> in the model picker.

Selecting a router model is a drop-in replacement for any other model — OpenCode forwards your request and DigitalOcean picks the underlying model based on your router's policy. Learn more about Inference Routers


Eden AI

Eden AI is an EU-based gateway that serves models from many vendors over a single OpenAI-compatible API, with a separate EU endpoint for teams that need inference to stay in the EU.

  1. Head over to the Eden AI platform to create an account and generate an API key.

  2. Run the /connect command and search for Eden AI.

    txt
    /connect
  3. Enter your Eden AI API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Mistral Large 3 or Claude Sonnet 5.

    txt
    /models

    Eden AI model ids are themselves in vendor/model form, so a full reference has three segments, for example edenai/anthropic/claude-sonnet-5.

  5. To keep requests on Eden AI's EU gateway, set its base URL.

    json title="opencode.json"
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "edenai": {
          "options": {
            "baseURL": "https://api.eu.edenai.run/v3"
          }
        }
      }
    }

    The default is https://api.edenai.run/v3, so this swaps the global endpoint for the EU one. The EU endpoint serves the subset of the catalog that is available in the EU, so a model chosen in step 4 may not be reachable through it.


FrogBot

  1. Head over to the FrogBot dashboard, create an account, and generate an API key.

  2. Run the /connect command and search for FrogBot.

    txt
    /connect
  3. Enter your FrogBot API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

Fireworks AI

  1. Head over to the Fireworks AI console, create an account, and click Create API Key.

  2. Run the /connect command and search for Fireworks AI.

    txt
    /connect
  3. Enter your Fireworks AI API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Kimi K2 Instruct.

    txt
    /models

GitLab Duo

:::caution[Experimental]
GitLab Duo support in OpenCode is experimental. Features, configuration, and
behavior may change in future releases.
:::

OpenCode integrates with the GitLab Duo Agent Platform,
providing AI-powered agentic chat with native tool calling capabilities.

:::note[License requirements]
GitLab Duo Agent Platform requires a Premium or Ultimate GitLab
subscription. It is available on GitLab.com and GitLab Self-Managed.
See GitLab Duo Agent Platform prerequisites
for full requirements.
:::

  1. Run the /connect command and select GitLab.

    txt
    /connect
  2. Choose your authentication method:

    txt
    ┌ Select auth method
    │
    │ OAuth (Recommended)
    │ Personal Access Token
    └

    Select OAuth and your browser will open for authorization.

    Using Personal Access Token

    1. Go to GitLab User Settings > Access Tokens
    2. Click Add new token
    3. Name: OpenCode, Scopes: api
    4. Copy the token (starts with glpat-)
    5. Enter it in the terminal
  3. Run the /models command to see available models.

    txt
    /models

    Three Claude-based models are available:

    • duo-chat-haiku-4-5 (Default) - Fast responses for quick tasks
    • duo-chat-sonnet-4-5 - Balanced performance for most workflows
    • duo-chat-opus-4-5 - Most capable for complex analysis

:::note
You can also specify 'GITLAB_TOKEN' environment variable if you don't want
to store token in opencode auth storage.
:::

Self-Hosted GitLab

:::note[compliance note]
OpenCode uses a small model for some AI tasks like generating the session title.
It is configured to use gpt-5-nano by default, hosted by Zen. To lock OpenCode
to only use your own GitLab-hosted instance, add the following to your
opencode.json file.

json
{
  "$schema": "https://opencode.ai/config.json",
  "small_model": "gitlab/duo-chat-haiku-4-5"
}

:::

For self-hosted GitLab instances:

bash
export GITLAB_INSTANCE_URL=https://gitlab.company.com
export GITLAB_TOKEN=glpat-...

If your instance runs a custom AI Gateway:

bash
GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com

Or add to your bash profile:

bash title="~/.bash_profile"
export GITLAB_INSTANCE_URL=https://gitlab.company.com
export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com
export GITLAB_TOKEN=glpat-...

:::note
Your GitLab administrator must:

  1. Turn on GitLab Duo
    for the user, group, or instance
  2. Turn on the Agent Platform
    (GitLab 18.8+) or enable beta and experimental features
    (GitLab 18.7 and earlier)
  3. For Self-Managed, configure your instance
    :::

OAuth for Self-Hosted instances

OpenCode's bundled GitLab OAuth application only exists on gitlab.com. To use
OAuth with a self-hosted instance, create your own application (Settings →
Applications) with the callback URL http://127.0.0.1:8080/callback, the
api scope, and Confidential unchecked (PKCE requires a public client).

Then expose the application ID as an environment variable:

bash
export GITLAB_OAUTH_CLIENT_ID=your_application_id_here

Configuration

Customize through opencode.json:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "gitlab": {
      "options": {
        "instanceUrl": "https://gitlab.com"
      }
    }
  }
}

GitLab Duo Agent Platform (DAP) Workflow Models

DAP workflow models provide an alternative execution path that routes tool calls
through GitLab's Duo Workflow Service (DWS) instead of the standard agentic chat.
When a duo-workflow-* model is selected, OpenCode will:

  1. Discover available models from your GitLab namespace
  2. Present a selection picker if multiple models are available
  3. Cache the selected model to disk for fast subsequent startups
  4. Route tool execution requests through OpenCode's permission-gated tool system

Available DAP workflow models follow the duo-workflow-* naming convention and
are dynamically discovered from your GitLab instance.

:::note
Workflow model discovery only runs for a login stored with /connect (OAuth or
a personal access token). A GITLAB_TOKEN environment variable on its own does
not trigger discovery.
:::

To access GitLab tools (merge requests, issues, pipelines, CI/CD, etc.):

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "plugin": ["opencode-gitlab-plugin"]
}

This plugin provides comprehensive GitLab repository management capabilities including MR reviews, issue tracking, pipeline monitoring, and more.


GitHub Copilot

To use your GitHub Copilot subscription with opencode:

:::note
Some models might need a Pro+
subscription
to use.
:::

  1. Run the /connect command and search for GitHub Copilot.

    txt
    /connect
  2. Navigate to github.com/login/device and enter the code.

    txt
    ┌ Login with GitHub Copilot
    │
    │ https://github.com/login/device
    │
    │ Enter code: 8F43-6FCF
    │
    └ Waiting for authorization...
  3. Now run the /models command to select the model you want.

    txt
    /models

GMI Cloud

To use GMI Cloud with OpenCode:

  1. Head over to the GMI Cloud console to create an API key. You can also review the API reference for the endpoint details.

  2. Run the /connect command and search for GMI Cloud.

    txt
    /connect
  3. Enter your GMI Cloud API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select the model you want.

    txt
    /models

Google Vertex AI

To use Google Vertex AI with OpenCode:

  1. Head over to the Model Garden in the Google Cloud Console and check the
    models available in your region.

    :::note
    You need to have a Google Cloud project with Vertex AI API enabled.
    :::

  2. Set the required environment variables:

    • GOOGLE_CLOUD_PROJECT: Your Google Cloud project ID
    • VERTEX_LOCATION (optional): The region for Vertex AI (defaults to global)
    • Authentication (choose one):
      • GOOGLE_APPLICATION_CREDENTIALS: Path to your service account JSON key file
      • Authenticate using gcloud CLI: gcloud auth application-default login

    Set them while running opencode.

    bash
    GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json GOOGLE_CLOUD_PROJECT=your-project-id opencode

    Or add them to your bash profile.

    bash title="~/.bash_profile"
    export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
    export GOOGLE_CLOUD_PROJECT=your-project-id
    export VERTEX_LOCATION=global

:::tip
The global region improves availability and reduces errors at no extra cost. Use regional endpoints (e.g., us-central1) for data residency requirements. Learn more
:::

  1. Run the /models command to select the model you want.

    txt
    /models

Groq

  1. Head over to the Groq console, click Create API Key, and copy the key.

  2. Run the /connect command and search for Groq.

    txt
    /connect
  3. Enter the API key for the provider.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select the one you want.

    txt
    /models

Hugging Face

Hugging Face Inference Providers provides access to open models supported by 17+ providers.

  1. Head over to Hugging Face settings to create a token with permission to make calls to Inference Providers.

  2. Run the /connect command and search for Hugging Face.

    txt
    /connect
  3. Enter your Hugging Face token.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Kimi-K2-Instruct or GLM-4.6.

    txt
    /models

Helicone

Helicone is an LLM observability platform that provides logging, monitoring, and analytics for your AI applications. The Helicone AI Gateway routes your requests to the appropriate provider automatically based on the model.

  1. Head over to Helicone, create an account, and generate an API key from your dashboard.

  2. Run the /connect command and search for Helicone.

    txt
    /connect
  3. Enter your Helicone API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

For more providers and advanced features like caching and rate limiting, check the Helicone documentation.

Optional Configs

In the event you see a feature or model from Helicone that isn't configured automatically through opencode, you can always configure it yourself.

Here's Helicone's Model Directory, you'll need this to grab the IDs of the models you want to add.

jsonc title="~/.config/opencode/opencode.jsonc"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "helicone": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Helicone",
      "options": {
        "baseURL": "https://ai-gateway.helicone.ai",
      },
      "models": {
        "gpt-4o": {
          // Model ID (from Helicone's model directory page)
          "name": "GPT-4o", // Your own custom name for the model
        },
        "claude-sonnet-4-20250514": {
          "name": "Claude Sonnet 4",
        },
      },
    },
  },
}

Custom Headers

Helicone supports custom headers for features like caching, user tracking, and session management. Add them to your provider config using options.headers:

jsonc title="~/.config/opencode/opencode.jsonc"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "helicone": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Helicone",
      "options": {
        "baseURL": "https://ai-gateway.helicone.ai",
        "headers": {
          "Helicone-Cache-Enabled": "true",
          "Helicone-User-Id": "opencode",
        },
      },
    },
  },
}

Session tracking

Helicone's Sessions feature lets you group related LLM requests together. Use the opencode-helicone-session plugin to automatically log each OpenCode conversation as a session in Helicone.

bash
npm install opencode-helicone-session

Add it to your config.

json title="opencode.json"
{
  "plugin": ["opencode-helicone-session"]
}

The plugin injects Helicone-Session-Id and Helicone-Session-Name headers into your requests. In Helicone's Sessions page, you'll see each OpenCode conversation listed as a separate session.

Common Helicone headers

Header Description
Helicone-Cache-Enabled Enable response caching (true/false)
Helicone-User-Id Track metrics by user
Helicone-Property-[Name] Add custom properties (e.g., Helicone-Property-Environment)
Helicone-Prompt-Id Associate requests with prompt versions

See the Helicone Header Directory for all available headers.


llama.cpp

You can configure opencode to use local models through llama.cpp's llama-server utility

json title="opencode.json" "llama.cpp" {5, 6, 8, 10-15}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "llama.cpp": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "llama-server (local)",
      "options": {
        "baseURL": "http://127.0.0.1:8080/v1"
      },
      "models": {
        "qwen3-coder:a3b": {
          "name": "Qwen3-Coder: a3b-30b (local)",
          "limit": {
            "context": 128000,
            "output": 65536
          }
        }
      }
    }
  }
}

In this example:

  • llama.cpp is the custom provider ID. This can be any string you want.
  • npm specifies the package to use for this provider. Here, @ai-sdk/openai-compatible is used for any OpenAI-compatible API.
  • name is the display name for the provider in the UI.
  • options.baseURL is the endpoint for the local server.
  • models is a map of model IDs to their configurations. The model name will be displayed in the model selection list.

IO.NET

IO.NET offers 17 models optimized for various use cases:

  1. Head over to the IO.NET console, create an account, and generate an API key.

  2. Run the /connect command and search for IO.NET.

    txt
    /connect
  3. Enter your IO.NET API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

LM Studio

You can configure opencode to use local models through LM Studio.

json title="opencode.json" "lmstudio" {5, 6, 8, 10-14}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "lmstudio": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "LM Studio (local)",
      "options": {
        "baseURL": "http://127.0.0.1:1234/v1"
      },
      "models": {
        "google/gemma-3n-e4b": {
          "name": "Gemma 3n-e4b (local)"
        }
      }
    }
  }
}

In this example:

  • lmstudio is the custom provider ID. This can be any string you want.
  • npm specifies the package to use for this provider. Here, @ai-sdk/openai-compatible is used for any OpenAI-compatible API.
  • name is the display name for the provider in the UI.
  • options.baseURL is the endpoint for the local server.
  • models is a map of model IDs to their configurations. The model name will be displayed in the model selection list.

Moonshot AI

To use Kimi K2 from Moonshot AI:

  1. Head over to the Moonshot AI console, create an account, and click Create API key.

  2. Run the /connect command and search for Moonshot AI.

    txt
    /connect
  3. Enter your Moonshot API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select Kimi K2.

    txt
    /models

MiniMax

  1. Head over to the MiniMax API Console, create an account, and generate an API key.

  2. Run the /connect command and search for MiniMax.

    txt
    /connect
  3. Enter your MiniMax API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like M2.1.

    txt
    /models

  1. Create a shared Endpoint for the model you want to use.

  2. Create a proxy token, then join its ID and secret with a period:

    txt
    wk-<id>.ws-<secret>
  3. Run the /connect command, search for Modal, and enter the combined proxy token.

    txt
    /connect
  4. Run the /models command to select one of the endpoints in your Modal workspace.

    txt
    /models

NVIDIA

NVIDIA provides access to Nemotron models and many other open models through build.nvidia.com for free.

  1. Head over to build.nvidia.com, create an account, and generate an API key.

  2. Run the /connect command and search for NVIDIA.

    txt
    /connect
  3. Enter your NVIDIA API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like nemotron-3-super-120b-a12b.

    txt
    /models

On-Prem / NIM

You can also use NVIDIA models locally via NVIDIA NIM by setting a custom base URL.

json title="opencode.json" {6}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "nvidia": {
      "options": {
        "baseURL": "http://localhost:8000/v1"
      }
    }
  }
}

Environment Variable

Alternatively, set your API key as an environment variable.

bash frame="none"
export NVIDIA_API_KEY=nvapi-your-key-here

Nebius Token Factory

  1. Head over to the Nebius Token Factory console, create an account, and click Add Key.

  2. Run the /connect command and search for Nebius Token Factory.

    txt
    /connect
  3. Enter your Nebius Token Factory API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Kimi K2 Instruct.

    txt
    /models

Ollama

You can configure opencode to use local models through Ollama.

:::tip
Ollama can automatically configure itself for OpenCode. See the Ollama integration docs for details.
:::

json title="opencode.json" "ollama" {5, 6, 8, 10-14}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "ollama": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Ollama (local)",
      "options": {
        "baseURL": "http://localhost:11434/v1"
      },
      "models": {
        "llama2": {
          "name": "Llama 2"
        }
      }
    }
  }
}

In this example:

  • ollama is the custom provider ID. This can be any string you want.
  • npm specifies the package to use for this provider. Here, @ai-sdk/openai-compatible is used for any OpenAI-compatible API.
  • name is the display name for the provider in the UI.
  • options.baseURL is the endpoint for the local server.
  • models is a map of model IDs to their configurations. The model name will be displayed in the model selection list.

:::tip
If tool calls aren't working, try increasing num_ctx in Ollama. Start around 16k - 32k.
:::


Ollama Cloud

To use Ollama Cloud with OpenCode:

  1. Head over to https://ollama.com/ and sign in or create an account.

  2. Navigate to Settings > Keys and click Add API Key to generate a new API key.

  3. Copy the API key for use in OpenCode.

  4. Run the /connect command and search for Ollama Cloud.

    txt
    /connect
  5. Enter your Ollama Cloud API key.

    txt
    ┌ API key
    │
    │
    └ enter
  6. Important: Before using cloud models in OpenCode, you must pull the model information locally:

    bash
    ollama pull gpt-oss:20b-cloud
  7. Run the /models command to select your Ollama Cloud model.

    txt
    /models

OpenAI

We recommend signing up for ChatGPT Plus or Pro.

  1. Once you've signed up, run the /connect command and select OpenAI.

    txt
    /connect
  2. Here you can select the ChatGPT Plus/Pro option and it'll open your browser
    and ask you to authenticate.

    txt
    ┌ Select auth method
    │
    │ ChatGPT Plus/Pro
    │ Manually enter API Key
    └
  3. Now all the OpenAI models should be available when you use the /models command.

    txt
    /models

Compute residency

For ChatGPT OAuth, OpenCode automatically applies a regional inference residency requirement when one is advertised by your workspace credentials. It forwards the compute residency value from the credential instead of maintaining a fixed list of regions. Data residency at rest does not imply regional inference.

Using API keys

If you already have an API key, you can select Manually enter API Key and paste it in your terminal.


OpenCode Zen

OpenCode Zen is a list of tested and verified models provided by the OpenCode team. Learn more.

  1. Sign in to OpenCode Zen and click Create API Key.

  2. Run the /connect command and search for OpenCode Zen.

    txt
    /connect
  3. Enter your OpenCode API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Qwen 3 Coder 480B.

    txt
    /models

OpenRouter

  1. Head over to the OpenRouter dashboard, click Create API Key, and copy the key.

  2. Run the /connect command and search for OpenRouter.

    txt
    /connect
  3. Enter the API key for the provider.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Many OpenRouter models are preloaded by default, run the /models command to select the one you want.

    txt
    /models

    You can also add additional models through your opencode config.

    json title="opencode.json" {6}
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "openrouter": {
          "models": {
            "somecoolnewmodel": {}
          }
        }
      }
    }
  5. You can also customize them through your opencode config. Here's an example of specifying a provider

    json title="opencode.json"
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "openrouter": {
          "models": {
            "moonshotai/kimi-k2": {
              "options": {
                "provider": {
                  "order": ["baseten"],
                  "allow_fallbacks": false
                }
              }
            }
          }
        }
      }
    }

LLM Gateway

  1. Head over to the LLM Gateway dashboard, click Create API Key, and copy the key.

  2. Run the /connect command and search for LLM Gateway.

    txt
    /connect
  3. Enter the API key for the provider.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Many LLM Gateway models are preloaded by default, run the /models command to select the one you want.

    txt
    /models

    You can also add additional models through your opencode config.

    json title="opencode.json" {6}
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "llmgateway": {
          "models": {
            "somecoolnewmodel": {}
          }
        }
      }
    }
  5. You can also customize them through your opencode config. Here's an example of specifying a provider

    json title="opencode.json"
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "llmgateway": {
          "models": {
            "glm-4.7": {
              "name": "GLM 4.7"
            },
            "gpt-5.2": {
              "name": "GPT-5.2"
            },
            "gemini-2.5-pro": {
              "name": "Gemini 2.5 Pro"
            },
            "claude-3-5-sonnet-20241022": {
              "name": "Claude 3.5 Sonnet"
            }
          }
        }
      }
    }

Poolside

Poolside provides access to its models through an OpenAI-compatible API.

  1. Head over to platform.poolside.ai, sign in, open the API Keys tab, and click New key to generate an API key.

  2. Run the /connect command and search for Poolside.

    txt
    /connect
  3. Enter your Poolside API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

Poolside deployment

If your organization runs a Poolside deployment, configure it as a custom OpenAI-compatible provider. Store the API key or token from your Poolside administrator in ~/.secrets/poolside-key. Use a unique provider ID and add the model IDs available from your deployment.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "poolside-deployment": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Poolside deployment",
      "options": {
        "baseURL": "https://poolside.example.com/openai/v1",
        "apiKey": "{file:~/.secrets/poolside-key}"
      },
      "models": {
        "<served-model-id>": {
          "name": "Poolside deployment model",
          "reasoning": true,
          "interleaved": {
            "field": "reasoning_content"
          }
        }
      }
    }
  }
}

Replace poolside.example.com with your deployment's host and <served-model-id> with a model ID returned by its /openai/v1/models endpoint. Model availability and thinking behavior depend on the deployment's configuration.

:::tip
You can also install Poolside Agent CLI to use Poolside agents directly from your terminal.
:::


SAP AI Core

SAP AI Core provides access to 40+ models from OpenAI, Anthropic, Google, Amazon, Meta, Mistral, and AI21 through a unified platform.

  1. Go to your SAP BTP Cockpit, navigate to your SAP AI Core service instance, and create a service key.

    :::tip
    The service key is a JSON object containing clientid, clientsecret, url, and serviceurls.AI_API_URL. You can find your AI Core instance under Services > Instances and Subscriptions in the BTP Cockpit.
    :::

  2. Run the /connect command and search for SAP AI Core.

    txt
    /connect
  3. Enter your service key JSON.

    txt
    ┌ Service key
    │
    │
    └ enter

    Or set the AICORE_SERVICE_KEY environment variable:

    bash
    AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}' opencode

    Or add it to your bash profile:

    bash title="~/.bash_profile"
    export AICORE_SERVICE_KEY='{"clientid":"...","clientsecret":"...","url":"...","serviceurls":{"AI_API_URL":"..."}}'
  4. Optionally set deployment ID and resource group:

    bash
    AICORE_DEPLOYMENT_ID=your-deployment-id AICORE_RESOURCE_GROUP=your-resource-group opencode

    :::note
    These settings are optional and should be configured according to your SAP AI Core setup.
    :::

  5. Run the /models command to select from 40+ available models.

    txt
    /models

STACKIT

STACKIT AI Model Serving provides fully managed sovereign hosting environment for AI models, focusing on LLMs like Llama, Mistral, and Qwen, with maximum data sovereignty on European infrastructure.

  1. Head over to STACKIT Portal, navigate to AI Model Serving, and create an auth token for your project.

    :::tip
    You need a STACKIT customer account, user account, and project before creating auth tokens.
    :::

  2. Run the /connect command and search for STACKIT.

    txt
    /connect
  3. Enter your STACKIT AI Model Serving auth token.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select from available models like Qwen3-VL 235B or Llama 3.3 70B.

    txt
    /models

OVHcloud AI Endpoints

  1. Head over to the OVHcloud panel. Navigate to the Public Cloud section, AI & Machine Learning > AI Endpoints and in API Keys tab, click Create a new API key.

  2. Run the /connect command and search for OVHcloud AI Endpoints.

    txt
    /connect
  3. Enter your OVHcloud AI Endpoints API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like gpt-oss-120b.

    txt
    /models

Scaleway

To use Scaleway Generative APIs with Opencode:

  1. Head over to the Scaleway Console IAM settings to generate a new API key.

  2. Run the /connect command and search for Scaleway.

    txt
    /connect
  3. Enter your Scaleway API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like devstral-2-123b-instruct-2512 or gpt-oss-120b.

    txt
    /models

SCX.ai

SCX.ai is an Australian sovereign AI platform serving open models over an OpenAI-compatible API, hosted on renewable-powered infrastructure in Australia.

  1. Head over to the SCX.ai platform to create an account and generate an API key.

  2. Run the /connect command and search for SCX.ai.

    txt
    /connect
  3. Enter your SCX.ai API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like MiniMax-M2.7 or GLM-5.2.

    txt
    /models

Snowflake Cortex

Snowflake Cortex gives you access to frontier models (Claude, OpenAI GPT-5, and more) via an OpenAI-compatible API. All inference runs within the Snowflake perimeter and is billed in Snowflake credits. For per-model rates, see the Snowflake Service Consumption Table.

Don't have a Snowflake account? Sign up for a free trial.

opencode's core workflow for coding, editing files, and running commands relies on tool calling. Only the Claude and OpenAI families within Snowflake Cortex support this. The provider is limited to those families to support the core workflow.

OpenCode supports two authentication methods:

  • Browser OAuth (Recommended) — sign in with your IdP/SSO; no secrets to manage, tokens refresh automatically.
  • Manual bearer token — paste a PAT or JWT from the Snowflake console.
  1. Run the /connect command and search for Snowflake Cortex.

    txt
    /connect
  2. Select Login with Snowflake (External Browser).

    txt
    ┌ Select auth method
    │
    │ Login with Snowflake (External Browser)
    │ Paste PAT or bearer token manually
    └
  3. Enter your account identifier when prompted, for example myorg-myaccount or xy12345.us-east-1.

    txt
    ┌ Snowflake Account Identifier
    │
    │
    └ enter
  4. Optionally enter a Snowflake role to scope the session (e.g. SYSADMIN). Leave blank to use your default role.

  5. Complete sign-in in the browser that opens. OpenCode captures the OAuth callback automatically and stores the token — no copy/paste needed.

  6. Run the /models command to select a model.

    txt
    /models

:::note
Browser OAuth uses Snowflake's built-in SNOWFLAKE$LOCAL_APPLICATION security integration (docs), which is rolling out to all accounts. To check availability in your account:

sql
SHOW SECURITY INTEGRATIONS LIKE 'SNOWFLAKE$LOCAL_APPLICATION';

If the result is empty, use the Manual bearer token method below while the integration rolls out to your account.
:::

Manual bearer token

If you prefer to paste a token directly, or if SNOWFLAKE$LOCAL_APPLICATION is not yet available in your account:

  1. Generate a Programmatic Access Token (PAT) in your Snowflake account.

  2. Run the /connect command, search for Snowflake Cortex, and select Paste PAT or bearer token manually.

  3. Enter your account identifier when prompted.

  4. Paste your PAT.

  5. Run the /models command to select a model.

    txt
    /models

Environment variable

For CI or headless environments, set a PAT or JWT before starting opencode:

bash
export SNOWFLAKE_ACCOUNT=myorg-myaccount
export SNOWFLAKE_CORTEX_TOKEN=your-pat-or-jwt

:::note
SNOWFLAKE_CORTEX_TOKEN accepts a PAT or JWT only — the browser OAuth flow is available via /connect only and cannot be configured through an environment variable. SNOWFLAKE_CORTEX_PAT is still supported for backward compatibility.
:::

The model catalog is provided automatically. A minimal opencode.json is all that's needed:

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "model": "snowflake-cortex/claude-sonnet-4-6",
  "small_model": "snowflake-cortex/claude-haiku-4-5"
}

Together AI

  1. Head over to the Together AI console, create an account, and click Add Key.

  2. Run the /connect command and search for Together AI.

    txt
    /connect
  3. Enter your Together AI API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Kimi K2 Instruct.

    txt
    /models

Venice AI

  1. Head over to the Venice AI console, create an account, and generate an API key.

  2. Run the /connect command and search for Venice AI.

    txt
    /connect
  3. Enter your Venice AI API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Llama 3.3 70B.

    txt
    /models

Vercel AI Gateway

Vercel AI Gateway lets you access models from OpenAI, Anthropic, Google, xAI, and more through a unified endpoint. Models are offered at list price with no markup.

  1. Head over to the Vercel dashboard, navigate to the AI Gateway tab, and click API keys to create a new API key.

  2. Run the /connect command and search for Vercel AI Gateway.

    txt
    /connect
  3. Enter your Vercel AI Gateway API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model.

    txt
    /models

You can also customize models through your opencode config. Here's an example of specifying provider routing order.

json title="opencode.json"
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "vercel": {
      "models": {
        "anthropic/claude-sonnet-4": {
          "options": {
            "order": ["anthropic", "vertex"]
          }
        }
      }
    }
  }
}

Some useful routing options:

Option Description
order Provider sequence to try
only Restrict to specific providers
zeroDataRetention Only use providers with zero data retention policies

xAI

Two ways to authenticate: a SuperGrok subscription via device-code OAuth or a pay-as-you-go API key from the xAI console.

Option A — SuperGrok subscription

  1. Run the /connect command and search for xAI.

    txt
    /connect
  2. Select SuperGrok Subscription. OpenCode opens xAI's verification link with the user code pre-populated when supported.

  3. Approve the consent screen. If xAI asks for a code, enter the user code displayed by OpenCode. OpenCode polls xAI's token endpoint and stores the resulting OAuth tokens once you approve.

  4. Run the /models command to select a Grok model.

    txt
    /models

OpenCode refreshes the OAuth access token automatically. Any Grok or X Premium plan that includes Grok API access works; you do not need a separate XAI_API_KEY.

Option B — API key

  1. Head over to the xAI console, create an account, and generate an API key.

  2. Run the /connect command and search for xAI.

    txt
    /connect
  3. Select Manually enter API Key and paste your xAI API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like Grok Beta.

    txt
    /models

Z.AI

  1. Head over to the Z.AI API console, create an account, and click Create a new API key.

  2. Run the /connect command and search for Z.AI.

    txt
    /connect

    If you are subscribed to the GLM Coding Plan, select Z.AI Coding Plan.

  3. Enter your Z.AI API key.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Run the /models command to select a model like GLM-4.7.

    txt
    /models

ZenMux

  1. Head over to the ZenMux dashboard, click Create API Key, and copy the key.

  2. Run the /connect command and search for ZenMux.

    txt
    /connect
  3. Enter the API key for the provider.

    txt
    ┌ API key
    │
    │
    └ enter
  4. Many ZenMux models are preloaded by default, run the /models command to select the one you want.

    txt
    /models

    You can also add additional models through your opencode config.

    json title="opencode.json" {6}
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "zenmux": {
          "models": {
            "somecoolnewmodel": {}
          }
        }
      }
    }

Custom provider

To add any OpenAI-compatible provider that's not listed in the /connect command:

:::tip
You can use any OpenAI-compatible provider with opencode. Most modern AI providers offer OpenAI-compatible APIs.
:::

  1. Run the /connect command and scroll down to Other.

    bash
    $ /connect
    
    ┌  Add credential
    │
    ◆  Select provider
    │  ...
    │  ● Other
    └
  2. Enter a unique ID for the provider.

    bash
    $ /connect
    
    ┌  Add credential
    │
    ◇  Enter provider id
    │  myprovider
    └

    :::note
    Choose a memorable ID, you'll use this in your config file.
    :::

  3. Enter your API key for the provider.

    bash
    $ /connect
    
    ┌  Add credential
    │
    ▲  This only stores a credential for myprovider - you will need to configure it in opencode.json, check the docs for examples.
    │
    ◇  Enter your API key
    │  sk-...
    └
  4. Create or update your opencode.json file in your project directory:

    json title="opencode.json" ""myprovider"" {5-15}
    {
      "$schema": "https://opencode.ai/config.json",
      "provider": {
        "myprovider": {
          "npm": "@ai-sdk/openai-compatible",
          "name": "My AI Provider Display Name",
          "options": {
            "baseURL": "https://api.myprovider.com/v1"
          },
          "models": {
            "my-model-name": {
              "name": "My Model Display Name"
            }
          }
        }
      }
    }

    Here are the configuration options:

    • npm: AI SDK package to use, @ai-sdk/openai-compatible for OpenAI-compatible providers (for /v1/chat/completions). If your provider/model uses /v1/responses, use @ai-sdk/openai.
    • name: Display name in UI.
    • models: Available models.
    • options.baseURL: API endpoint URL.
    • options.apiKey: Optionally set the API key, if not using auth.
    • options.headers: Optionally set custom headers.

    More on the advanced options in the example below.

  5. Run the /models command and your custom provider and models will appear in the selection list.


Example

Here's an example setting the apiKey, headers, and model limit options.

json title="opencode.json" {9,11,17-20}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "myprovider": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "My AI Provider Display Name",
      "options": {
        "baseURL": "https://api.myprovider.com/v1",
        "apiKey": "{env:ANTHROPIC_API_KEY}",
        "headers": {
          "Authorization": "Bearer custom-token"
        }
      },
      "models": {
        "my-model-name": {
          "name": "My Model Display Name",
          "limit": {
            "context": 200000,
            "output": 65536
          }
        }
      }
    }
  }
}

Configuration details:

  • apiKey: Set using env variable syntax, learn more.
  • headers: Custom headers sent with each request.
  • limit.context: Maximum input tokens the model accepts.
  • limit.output: Maximum tokens the model can generate.

The limit fields allow OpenCode to understand how much context you have left. Standard providers pull these from models.dev automatically.


Troubleshooting

If you are having trouble with configuring a provider, check the following:

  1. Check the auth setup: Run opencode auth list to see if the credentials
    for the provider are added to your config.

    This doesn't apply to providers like Amazon Bedrock, that rely on environment variables for their auth.

  2. For custom