# Table of Contents - [Intro | AI coding agent built for the terminal](#intro-ai-coding-agent-built-for-the-terminal) - [Config | OpenCode](#config-opencode) - [配置 | OpenCode](#-opencode) - [Config | OpenCode](#config-opencode) - [設定 | OpenCode](#-opencode) - [Configuration | OpenCode](#configuration-opencode) - [Konfiguration | OpenCode](#konfiguration-opencode) - [Configuración | OpenCode](#configuraci-n-opencode) - [Share | OpenCode](#share-opencode) - [分享 | OpenCode](#-opencode) - [分享 | OpenCode](#-opencode) - [Compartir | OpenCode](#compartir-opencode) - [Deling | OpenCode](#deling-opencode) - [Partager | OpenCode](#partager-opencode) - [Teilen | OpenCode](#teilen-opencode) - [Compartilhar | OpenCode](#compartilhar-opencode) - [共有 | OpenCode](#-opencode) - [المشاركة | OpenCode](#-opencode) - [Deling | OpenCode](#deling-opencode) - [Configurazione | OpenCode](#configurazione-opencode) - [設定 | OpenCode](#-opencode) - [แบ่งปัน | OpenCode](#-opencode) - [Udostępnianie | OpenCode](#udost-pnianie-opencode) - [Paylasim | OpenCode](#paylasim-opencode) - [공유 | OpenCode](#-opencode) - [Делиться | OpenCode](#-opencode) - [Condivisione | OpenCode](#condivisione-opencode) - [伺服器 | OpenCode](#-opencode) - [Formatters | OpenCode](#formatters-opencode) - [服务器 | OpenCode](#-opencode) - [서버 | OpenCode](#-opencode) - [Server | OpenCode](#server-opencode) - [Server | OpenCode](#server-opencode) - [Servidor | OpenCode](#servidor-opencode) - [포매터 | OpenCode](#-opencode) - [格式化工具 | OpenCode](#-opencode) - [格式化器 | OpenCode](#-opencode) - [Formatierer | OpenCode](#formatierer-opencode) - [Serveur | OpenCode](#serveur-opencode) - [Formateadores | OpenCode](#formateadores-opencode) - [Server | OpenCode](#server-opencode) - [Formateurs | OpenCode](#formateurs-opencode) - [Formatery | OpenCode](#formatery-opencode) - [Server | OpenCode](#server-opencode) - [Tjener | OpenCode](#tjener-opencode) - [Formatere | OpenCode](#formatere-opencode) - [Formattatori | OpenCode](#formattatori-opencode) - [Форматтеры | OpenCode](#-opencode) - [Konfigurasjon | OpenCode](#konfigurasjon-opencode) - [Сервер | OpenCode](#-opencode) - [Biçimlendiriciler | OpenCode](#bi-imlendiriciler-opencode) - [Formattere | OpenCode](#formattere-opencode) - [サーバー | OpenCode](#-opencode) - [Configuração | OpenCode](#configura-o-opencode) - [الخادم | OpenCode](#-opencode) - [Sunucu | OpenCode](#sunucu-opencode) - [Servidor | OpenCode](#servidor-opencode) - [Serwer | OpenCode](#serwer-opencode) - [フォーマッタ | OpenCode](#-opencode) - [المُنسِّقات | OpenCode](#-opencode) - [Konfiguracja | OpenCode](#konfiguracja-opencode) - [Formatadores | OpenCode](#formatadores-opencode) - [ฟอร์แมตเตอร์ | OpenCode](#-opencode) - [Zen | OpenCode](#zen-opencode) - [الإعدادات | OpenCode](#-opencode) - [Конфигурация | OpenCode](#-opencode) - [IDE | OpenCode](#ide-opencode) - [Konfiguration | OpenCode](#konfiguration-opencode) - [การกำหนดค่า | OpenCode](#-opencode) - [Zen | OpenCode](#zen-opencode) - [เซิร์ฟเวอร์ | OpenCode](#-opencode) - [IDE | OpenCode](#ide-opencode) - [Zen | OpenCode](#zen-opencode) - [Zen | OpenCode](#zen-opencode) - [IDE | OpenCode](#ide-opencode) - [Go | OpenCode](#go-opencode) - [IDE | OpenCode](#ide-opencode) - [Yapılandırma | OpenCode](#yap-land-rma-opencode) - [Zen | OpenCode](#zen-opencode) - [Zen | OpenCode](#zen-opencode) - [Zen | OpenCode](#zen-opencode) - [Zen | OpenCode](#zen-opencode) - [Go | OpenCode](#go-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [Go | OpenCode](#go-opencode) - [Zen | OpenCode](#zen-opencode) - [Zen | OpenCode](#zen-opencode) - [Zen | OpenCode](#zen-opencode) - [Go | OpenCode](#go-opencode) - [IDE | OpenCode](#ide-opencode) - [Go | OpenCode](#go-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [IDE | OpenCode](#ide-opencode) - [Go | OpenCode](#go-opencode) - [Go | OpenCode](#go-opencode) - [Go | OpenCode](#go-opencode) - [Zen | OpenCode](#zen-opencode) - [Go | OpenCode](#go-opencode) - [Go | OpenCode](#go-opencode) - [Go | OpenCode](#go-opencode) - [Go | OpenCode](#go-opencode) - [IDE | OpenCode](#ide-opencode) - [OpenCode Zen | OpenCode](#opencode-zen-opencode) - [เซน | OpenCode](#-opencode) - [Zen | OpenCode](#zen-opencode) - [Go | OpenCode](#go-opencode) - [Zen | OpenCode](#zen-opencode) - [IDE | OpenCode](#ide-opencode) - [Go | OpenCode](#go-opencode) - [Go | OpenCode](#go-opencode) - [Go | OpenCode](#go-opencode) - [Zen | OpenCode](#zen-opencode) - [Custom Tools | OpenCode](#custom-tools-opencode) - [Benutzerdefinierte Tools | OpenCode](#benutzerdefinierte-tools-opencode) - [Go | OpenCode](#go-opencode) - [自訂工具 | OpenCode](#-opencode) - [Özel Araçlar | OpenCode](#-zel-ara-lar-opencode) - [TUI | OpenCode](#tui-opencode) - [自定义工具 | OpenCode](#-opencode) - [Herramientas personalizadas | OpenCode](#herramientas-personalizadas-opencode) - [Пользовательские инструменты | OpenCode](#-opencode) - [Troubleshooting | OpenCode](#troubleshooting-opencode) - [Keybinds | OpenCode](#keybinds-opencode) - [カスタムツール | OpenCode](#-opencode) - [Ferramentas Personalizadas | OpenCode](#ferramentas-personalizadas-opencode) - [เครื่องมือที่กำหนดเอง | OpenCode](#-opencode) - [Outils personnalisés | OpenCode](#outils-personnalis-s-opencode) - [Web | OpenCode](#web-opencode) - [快捷鍵 | OpenCode](#-opencode) - [키바인드 | OpenCode](#-opencode) - [Combinaciones de teclas | OpenCode](#combinaciones-de-teclas-opencode) - [TUI | OpenCode](#tui-opencode) - [Strumenti personalizzati | OpenCode](#strumenti-personalizzati-opencode) - [Narzędzia specjalistyczne | OpenCode](#narz-dzia-specjalistyczne-opencode) - [Egendefinerte verktøy | OpenCode](#egendefinerte-verkt-y-opencode) - [Brugerdefinerede værktøjer | OpenCode](#brugerdefinerede-v-rkt-jer-opencode) - [الأدوات المخصصة | OpenCode](#-opencode) - [Feilsøking | OpenCode](#feils-king-opencode) - [快捷键 | OpenCode](#-opencode) - [TUI | OpenCode](#tui-opencode) - [Solución de problemas | OpenCode](#soluci-n-de-problemas-opencode) - [Solução de Problemas | OpenCode](#solu-o-de-problemas-opencode) - [Sorun giderme | OpenCode](#sorun-giderme-opencode) - [故障排除 | OpenCode](#-opencode) - [Custom Tools | OpenCode](#custom-tools-opencode) - [Fehlerbehebung | OpenCode](#fehlerbehebung-opencode) - [Plugins | OpenCode](#plugins-opencode) - [Scorciatoie | OpenCode](#scorciatoie-opencode) - [Plugins | OpenCode](#plugins-opencode) - [LSP Servers | OpenCode](#lsp-servers-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [Fejlfinding | OpenCode](#fejlfinding-opencode) - [استكشاف الأخطاء وإصلاحها | OpenCode](#-opencode) - [문제 해결 | OpenCode](#-opencode) - [插件 | OpenCode](#-opencode) - [Complementos | OpenCode](#complementos-opencode) - [Raccourcis clavier | OpenCode](#raccourcis-clavier-opencode) - [Сочетания клавиш | OpenCode](#-opencode) - [Atalhos de Teclado | OpenCode](#atalhos-de-teclado-opencode) - [اختصارات لوحة المفاتيح | OpenCode](#-opencode) - [ปุ่มลัด | OpenCode](#-opencode) - [Web | OpenCode](#web-opencode) - [ウェブ | OpenCode](#-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [TUI | OpenCode](#tui-opencode) - [Web | OpenCode](#web-opencode) - [Plugins | OpenCode](#plugins-opencode) - [Programtillegg | OpenCode](#programtillegg-opencode) - [Plugin | OpenCode](#plugin-opencode) - [Plugins | OpenCode](#plugins-opencode) - [外掛 | OpenCode](#-opencode) - [플러그인 | OpenCode](#-opencode) - [Plugins | OpenCode](#plugins-opencode) - [Rozwiązywanie problemów | OpenCode](#rozwi-zywanie-problem-w-opencode) - [Tastenkombinationen | OpenCode](#tastenkombinationen-opencode) - [Skróty klawiszowe | OpenCode](#skr-ty-klawiszowe-opencode) - [Tastebindinger | OpenCode](#tastebindinger-opencode) - [LSP 伺服器 | OpenCode](#lsp-opencode) - [LSP 서버 | OpenCode](#lsp-opencode) - [LSP 服务器 | OpenCode](#lsp-opencode) - [Server LSP | OpenCode](#server-lsp-opencode) - [TUI | OpenCode](#tui-opencode) - [疑難排解 | OpenCode](#-opencode) - [การแก้ไขปัญหา | OpenCode](#-opencode) - [トラブルシューティング | OpenCode](#-opencode) - [Web | OpenCode](#web-opencode) - [Web | OpenCode](#web-opencode) - [Web | OpenCode](#web-opencode) - [ปลั๊กอิน | OpenCode](#-opencode) - [الإضافات | OpenCode](#-opencode) - [プラグイン | OpenCode](#-opencode) - [Web | OpenCode](#web-opencode) - [Web | OpenCode](#web-opencode) - [キーバインド | OpenCode](#-opencode) - [Tastebindinger | OpenCode](#tastebindinger-opencode) - [Tuş atamaları | OpenCode](#tu-atamalar-opencode) - [Serwery LSP | OpenCode](#serwery-lsp-opencode) - [Serveurs LSP | OpenCode](#serveurs-lsp-opencode) - [Servidores LSP | OpenCode](#servidores-lsp-opencode) - [LSP-servere | OpenCode](#lsp-servere-opencode) - [Verktøy | OpenCode](#verkt-y-opencode) - [Værktøjer | OpenCode](#v-rkt-jer-opencode) - [Dépannage | OpenCode](#d-pannage-opencode) - [Web | OpenCode](#web-opencode) - [Web | OpenCode](#web-opencode) - [Web | OpenCode](#web-opencode) - [الويب | OpenCode](#-opencode) - [Web | OpenCode](#web-opencode) - [Web | OpenCode](#web-opencode) - [Eklentiler | OpenCode](#eklentiler-opencode) - [Wtyczki | OpenCode](#wtyczki-opencode) - [Интернет | OpenCode](#-opencode) - [เว็บ | OpenCode](#-opencode) - [Плагины | OpenCode](#-opencode) - [LSPサーバー | OpenCode](#lsp-opencode) - [LSP Server | OpenCode](#lsp-server-opencode) - [Tools | OpenCode](#tools-opencode) - [工具 | OpenCode](#-opencode) - [Ferramentas | OpenCode](#ferramentas-opencode) - [Tools | OpenCode](#tools-opencode) - [Поиск неисправностей | OpenCode](#-opencode) - [도구 | OpenCode](#-opencode) - [Araçlar | OpenCode](#ara-lar-opencode) - [Outils | OpenCode](#outils-opencode) - [Strumenti | OpenCode](#strumenti-opencode) - [工具 | OpenCode](#-opencode) - [ツール | OpenCode](#-opencode) - [Risoluzione dei problemi | OpenCode](#risoluzione-dei-problemi-opencode) - [Инструменты | OpenCode](#-opencode) - [Herramientas | OpenCode](#herramientas-opencode) - [Narzędzia | OpenCode](#narz-dzia-opencode) - [الأدوات | OpenCode](#-opencode) - [เครื่องมือ | OpenCode](#-opencode) --- # Intro | AI coding agent built for the terminal [Skip to content](https://opencode.ai/docs/en#_top) Intro ===== Get started with OpenCode. [**OpenCode**](https://opencode.ai/) is an open source AI coding agent. It’s available as a terminal-based interface, desktop app, or IDE extension. ![OpenCode TUI with the opencode theme](https://opencode.ai/docs/_astro/screenshot.CQjBbRyJ_1dLadc.webp) Let’s get started. * * * #### [Prerequisites](https://opencode.ai/docs/en#prerequisites) To use OpenCode in your terminal, you’ll need: 1. A modern terminal emulator like: * [WezTerm](https://wezterm.org/) , cross-platform * [Alacritty](https://alacritty.org/) , cross-platform * [Ghostty](https://ghostty.org/) , Linux and macOS * [Kitty](https://sw.kovidgoyal.net/kitty/) , Linux and macOS 2. API keys for the LLM providers you want to use. * * * [Install](https://opencode.ai/docs/en#install) ----------------------------------------------- The easiest way to install OpenCode is through the install script. curl -fsSL https://opencode.ai/install | bash You can also install it with the following commands: * **Using Node.js** * [npm](https://opencode.ai/docs/en#tab-panel-0) * [Bun](https://opencode.ai/docs/en#tab-panel-1) * [pnpm](https://opencode.ai/docs/en#tab-panel-2) * [Yarn](https://opencode.ai/docs/en#tab-panel-3) npm install -g opencode-ai bun install -g opencode-ai pnpm install -g opencode-ai yarn global add opencode-ai * **Using Homebrew on macOS and Linux** 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** sudo pacman -S opencode # Arch Linux (Stable)paru -S opencode-bin # Arch Linux (Latest from AUR) #### [Windows](https://opencode.ai/docs/en#windows) * **Using Chocolatey** choco install opencode * **Using Scoop** scoop install opencode * **Using NPM** npm install -g opencode-ai * **Using Mise** mise use -g github:anomalyco/opencode * **Using Docker** 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](https://github.com/anomalyco/opencode/releases) . * * * [Configure](https://opencode.ai/docs/en#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](https://opencode.ai/docs/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](https://opencode.ai/auth) . /connect 2. Sign in, add your billing details, and copy your API key. 3. Paste your API key. ┌ API key││└ enter Alternatively, you can select one of the other providers. [Learn more](https://opencode.ai/docs/providers#directory) . * * * [Initialize](https://opencode.ai/docs/en#initialize) ----------------------------------------------------- Now that you’ve configured a provider, you can navigate to a project that you want to work on. cd /path/to/project And run OpenCode. opencode Next, initialize OpenCode for the project by running the following command. /init This will get OpenCode to analyze your project and create an `AGENTS.md` file in the project root. This helps OpenCode understand the project structure and the coding patterns used. * * * [Usage](https://opencode.ai/docs/en#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](https://opencode.ai/docs/en#ask-questions) You can ask OpenCode to explain the codebase to you. 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](https://opencode.ai/docs/en#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. Now let’s describe what we want it to do. 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. 2. **Iterate on the plan** Once it gives you a plan, you can give it feedback or add more details. 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. 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. And asking it to make the changes. Sounds good! Go ahead and make the changes. * * * ### [Make changes](https://opencode.ai/docs/en#make-changes) For more straightforward changes, you can ask OpenCode to directly build it without having to review the plan first. We need to add authentication to the /settings route. Take a look at how this ishandled in the /notes route in @packages/functions/src/notes.ts and implementthe 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](https://opencode.ai/docs/en#undo-changes) Let’s say you ask OpenCode to make some changes. 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. /undo OpenCode will now revert the changes you made and show your original message again. 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. Or you **can redo** the changes using the `/redo` command. /redo * * * The conversations that you have with OpenCode can be [shared with your team](https://opencode.ai/docs/share) . /share This will create a link to the current conversation and copy it to your clipboard. Here’s an [example conversation](https://opencode.ai/s/4XP1fce5) with OpenCode. * * * [Customize](https://opencode.ai/docs/en#customize) --------------------------------------------------- And that’s it! You are now a pro at using OpenCode. To make it your own, we recommend [picking a theme](https://opencode.ai/docs/themes) , [customizing the keybinds](https://opencode.ai/docs/keybinds) , [configuring code formatters](https://opencode.ai/docs/formatters) , [creating custom commands](https://opencode.ai/docs/commands) , or playing around with the [OpenCode config](https://opencode.ai/docs/config) . --- # Config | OpenCode [Skip to content](https://opencode.ai/docs/config#_top) Config ====== Using the OpenCode JSON config. You can configure OpenCode using a JSON config file. * * * [Format](https://opencode.ai/docs/config#format) ------------------------------------------------- OpenCode supports both **JSON** and **JSONC** (JSON with Comments) formats. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [Locations](https://opencode.ai/docs/config#locations) ------------------------------------------------------- You can place your config in a couple of different locations and they have a different order of precedence. 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](https://opencode.ai/docs/config#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 This means project configs can override global defaults, and global configs can override remote organizational defaults. * * * ### [Remote](https://opencode.ai/docs/config#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: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} You can enable specific servers in your local config: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global](https://opencode.ai/docs/config#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](https://opencode.ai/docs/config#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. When OpenCode starts up, it looks for a config file in the current directory or traverse 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](https://opencode.ai/docs/config#custom-path) Specify a custom config file path using the `OPENCODE_CONFIG` environment variable. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Custom config is loaded between global and project configs in the precedence order. * * * ### [Custom directory](https://opencode.ai/docs/config#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. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" The custom directory is loaded after the global config and `.opencode` directories, so it **can override** their settings. * * * [Schema](https://opencode.ai/docs/config#schema) ------------------------------------------------- The server/runtime config schema is defined in [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . TUI config uses [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) . Your editor should be able to validate and autocomplete based on the schema. * * * ### [TUI](https://opencode.ai/docs/config#tui) Use a dedicated `tui.json` (or `tui.jsonc`) file for TUI-specific settings. { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Use `OPENCODE_TUI_CONFIG` to point to a custom TUI config file. Legacy `theme`, `keybinds`, and `tui` keys in `opencode.json` are deprecated and automatically migrated when possible. [Learn more about TUI configuration here](https://opencode.ai/docs/tui#configure) . * * * ### [Server](https://opencode.ai/docs/config#server) You can configure server settings for the `opencode serve` and `opencode web` commands through the `server` option. { "$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](https://opencode.ai/docs/server) . * * * ### [Tools](https://opencode.ai/docs/config#tools) You can manage the tools an LLM can use through the `tools` option. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Learn more about tools here](https://opencode.ai/docs/tools) . * * * ### [Models](https://opencode.ai/docs/config#models) You can configure the providers and models you want to use in your OpenCode config through the `provider`, `model` and `small_model` options. { "$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` and `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Request timeout in milliseconds (default: 300000). Set to `false` to disable. * `setCacheKey` - Ensure a cache key is always set for designated provider. You can also configure [local models](https://opencode.ai/docs/models#local) . [Learn more](https://opencode.ai/docs/models) . * * * #### [Provider-Specific Options](https://opencode.ai/docs/config#provider-specific-options) Some providers support additional configuration options beyond the generic `timeout` and `apiKey` settings. ##### [Amazon Bedrock](https://opencode.ai/docs/config#amazon-bedrock) Amazon Bedrock supports AWS-specific configuration: { "$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. [Learn more about Amazon Bedrock configuration](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Themes](https://opencode.ai/docs/config#themes) Set your UI theme in `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [Learn more here](https://opencode.ai/docs/themes) . * * * ### [Agents](https://opencode.ai/docs/config#agents) You can configure specialized agents for specific tasks through the `agent` option. { "$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](https://opencode.ai/docs/agents) . * * * ### [Default agent](https://opencode.ai/docs/config#default-agent) You can set the default agent using the `default_agent` option. This determines which agent is used when none is explicitly specified. { "$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](https://opencode.ai/docs/agents) 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. * * * ### [Sharing](https://opencode.ai/docs/config#sharing) You can configure the [share](https://opencode.ai/docs/share) feature through the `share` option. { "$schema": "https://opencode.ai/config.json", "share": "manual"} This takes: * `"manual"` - Allow manual sharing via commands (default) * `"auto"` - Automatically share new conversations * `"disabled"` - Disable sharing entirely By default, sharing is set to manual mode where you need to explicitly share conversations using the `/share` command. * * * ### [Commands](https://opencode.ai/docs/config#commands) You can configure custom commands for repetitive tasks through the `command` option. { "$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](https://opencode.ai/docs/commands) . * * * ### [Keybinds](https://opencode.ai/docs/config#keybinds) Customize keybinds in `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [Learn more here](https://opencode.ai/docs/keybinds) . * * * ### [Autoupdate](https://opencode.ai/docs/config#autoupdate) OpenCode will automatically download any new updates when it starts up. You can disable this with the `autoupdate` option. { "$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](https://opencode.ai/docs/config#formatters) You can configure code formatters through the `formatter` option. { "$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](https://opencode.ai/docs/formatters) . * * * ### [Permissions](https://opencode.ai/docs/config#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 `bash` tools require user approval: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Learn more about permissions here](https://opencode.ai/docs/permissions) . * * * ### [Compaction](https://opencode.ai/docs/config#compaction) You can control context compaction behavior through the `compaction` option. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - Automatically compact the session when context is full (default: `true`). * `prune` - Remove old tool outputs to save tokens (default: `true`). * `reserved` - Token buffer for compaction. Leaves enough window to avoid overflow during compaction * * * ### [Watcher](https://opencode.ai/docs/config#watcher) You can configure file watcher ignore patterns through the `watcher` option. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Patterns follow glob syntax. Use this to exclude noisy directories from file watching. * * * ### [MCP servers](https://opencode.ai/docs/config#mcp-servers) You can configure MCP servers you want to use through the `mcp` option. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Learn more here](https://opencode.ai/docs/mcp-servers) . * * * ### [Plugins](https://opencode.ai/docs/config#plugins) [Plugins](https://opencode.ai/docs/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. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Learn more here](https://opencode.ai/docs/plugins) . * * * ### [Instructions](https://opencode.ai/docs/config#instructions) You can configure the instructions for the model you’re using through the `instructions` option. { "$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](https://opencode.ai/docs/rules) . * * * ### [Disabled providers](https://opencode.ai/docs/config#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. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} 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](https://opencode.ai/docs/config#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. { "$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. If a provider appears in both `enabled_providers` and `disabled_providers`, the `disabled_providers` takes priority for backwards compatibility. * * * ### [Experimental](https://opencode.ai/docs/config#experimental) The `experimental` key contains options that are under active development. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variables](https://opencode.ai/docs/config#variables) ------------------------------------------------------- You can use variable substitution in your config files to reference environment variables and file contents. * * * ### [Env vars](https://opencode.ai/docs/config#env-vars) Use `{env:VARIABLE_NAME}` to substitute environment variables: { "$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](https://opencode.ai/docs/config#files) Use `{file:path/to/file}` to substitute the contents of a file: { "$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. --- # 配置 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/config#_top) 配置 == 使用 OpenCode JSON 配置。 您可以使用 JSON 配置文件来配置 OpenCode。 * * * [格式](https://opencode.ai/docs/zh-cn/config#%E6%A0%BC%E5%BC%8F) --------------------------------------------------------------- OpenCode 支持 **JSON** 和 **JSONC**(带注释的 JSON)格式。 { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [位置](https://opencode.ai/docs/zh-cn/config#%E4%BD%8D%E7%BD%AE) --------------------------------------------------------------- 您可以将配置放置在不同的位置,它们具有不同的优先级顺序。 配置文件是合并在一起的,而不是被替换。来自以下配置位置的设置会被合并。后面的配置仅在键冲突时覆盖前面的配置。所有配置中的非冲突设置都会被保留。 例如,如果您的全局配置设置了 `autoupdate: true`,而您的项目配置设置了 `model: "anthropic/claude-sonnet-4-5"`,则最终配置将包含这两个设置。 * * * ### [优先级顺序](https://opencode.ai/docs/zh-cn/config#%E4%BC%98%E5%85%88%E7%BA%A7%E9%A1%BA%E5%BA%8F) 配置源按以下顺序加载(后面的源覆盖前面的源): 1. **远程配置**(来自 `.well-known/opencode`)- 组织默认值 2. **全局配置**(`~/.config/opencode/opencode.json`)- 用户偏好 3. **自定义配置**(`OPENCODE_CONFIG` 环境变量)- 自定义覆盖 4. **项目配置**(项目中的 `opencode.json`)- 项目特定设置 5. **`.opencode` 目录** - 代理、命令、插件 6. **内联配置**(`OPENCODE_CONFIG_CONTENT` 环境变量)- 运行时覆盖 这意味着项目配置可以覆盖全局默认值,全局配置可以覆盖远程组织默认值。 * * * ### [远程](https://opencode.ai/docs/zh-cn/config#%E8%BF%9C%E7%A8%8B) 组织可以通过 `.well-known/opencode` 端点提供默认配置。当您使用支持该功能的提供商进行身份验证时,会自动获取此配置。 远程配置最先加载,作为基础层。所有其他配置源(全局、项目)都可以覆盖这些默认值。 例如,如果您的组织提供了默认禁用的 MCP 服务器: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} 您可以在本地配置中启用特定服务器: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [全局](https://opencode.ai/docs/zh-cn/config#%E5%85%A8%E5%B1%80) 将全局 OpenCode 配置放在 `~/.config/opencode/opencode.json` 中。使用全局配置来设置用户级别的偏好,例如主题、提供商或快捷键。 全局配置覆盖远程组织默认值。 * * * ### [项目级](https://opencode.ai/docs/zh-cn/config#%E9%A1%B9%E7%9B%AE%E7%BA%A7) 在项目根目录中添加 `opencode.json`。项目配置在标准配置文件中具有最高优先级——它会覆盖全局配置和远程配置。 当 OpenCode 启动时,它会在当前目录中查找配置文件,或向上遍历到最近的 Git 目录。 该配置文件也可以安全地提交到 Git 中,并使用与全局配置相同的 Schema。 * * * ### [自定义路径](https://opencode.ai/docs/zh-cn/config#%E8%87%AA%E5%AE%9A%E4%B9%89%E8%B7%AF%E5%BE%84) 使用 `OPENCODE_CONFIG` 环境变量指定自定义配置文件路径。 export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" 自定义配置在优先级顺序中位于全局配置和项目配置之间加载。 * * * ### [自定义目录](https://opencode.ai/docs/zh-cn/config#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9B%AE%E5%BD%95) 使用 `OPENCODE_CONFIG_DIR` 环境变量指定自定义配置目录。该目录会像标准 `.opencode` 目录一样被搜索代理、命令、模式和插件,并且应遵循相同的结构。 export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" 自定义目录在全局配置和 `.opencode` 目录之后加载,因此**可以覆盖**它们的设置。 * * * [Schema](https://opencode.ai/docs/zh-cn/config#schema) ------------------------------------------------------- 配置文件具有在 [**`opencode.ai/config.json`**](https://opencode.ai/config.json) 中定义的 Schema。 您的编辑器应该能够基于该 Schema 进行验证和自动补全。 * * * ### [TUI](https://opencode.ai/docs/zh-cn/config#tui) 您可以通过 `tui` 选项配置 TUI 相关设置。 { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} 可用选项: * `scroll_acceleration.enabled` - 启用 macOS 风格的滚动加速。**优先于 `scroll_speed`。** * `scroll_speed` - 自定义滚动速度倍率(默认值:`3`,最小值:`1`)。如果 `scroll_acceleration.enabled` 为 `true`,则忽略此选项。 * `diff_style` - 控制差异渲染方式。`"auto"` 根据终端宽度自适应,`"stacked"` 始终显示单列。 [在此了解更多关于 TUI 的信息](https://opencode.ai/docs/tui) 。 * * * ### [服务器](https://opencode.ai/docs/zh-cn/config#%E6%9C%8D%E5%8A%A1%E5%99%A8) 您可以通过 `server` 选项为 `opencode serve` 和 `opencode web` 命令配置服务器设置。 { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} 可用选项: * `port` - 监听端口。 * `hostname` - 监听主机名。当 `mdns` 启用且未设置主机名时,默认为 `0.0.0.0`。 * `mdns` - 启用 mDNS 服务发现。这允许网络上的其他设备发现您的 OpenCode 服务器。 * `mdnsDomain` - mDNS 服务的自定义域名。默认为 `opencode.local`。适用于在同一网络上运行多个实例的场景。 * `cors` - 从基于浏览器的客户端使用 HTTP 服务器时允许 CORS 的额外来源。值必须是完整的来源(协议 + 主机 + 可选端口),例如 `https://app.example.com`。 [在此了解更多关于服务器的信息](https://opencode.ai/docs/server) 。 * * * ### [工具](https://opencode.ai/docs/zh-cn/config#%E5%B7%A5%E5%85%B7) 您可以通过 `tools` 选项管理 LLM 可以使用的工具。 { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [在此了解更多关于工具的信息](https://opencode.ai/docs/tools) 。 * * * ### [模型](https://opencode.ai/docs/zh-cn/config#%E6%A8%A1%E5%9E%8B) 您可以通过 `provider`、`model` 和 `small_model` 选项在 OpenCode 配置中设置要使用的提供商和模型。 { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} `small_model` 选项为标题生成等轻量级任务配置单独的模型。默认情况下,如果您的提供商有更便宜的模型可用,OpenCode 会尝试使用该模型,否则会回退到您的主模型。 提供商选项可以包括 `timeout` 和 `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - 请求超时时间,单位为毫秒(默认值:300000)。设置为 `false` 可禁用超时。 * `setCacheKey` - 确保始终为指定提供商设置缓存键。 您还可以配置[本地模型](https://opencode.ai/docs/models#local) 。[了解更多](https://opencode.ai/docs/models) 。 * * * #### [提供商特定选项](https://opencode.ai/docs/zh-cn/config#%E6%8F%90%E4%BE%9B%E5%95%86%E7%89%B9%E5%AE%9A%E9%80%89%E9%A1%B9) 一些提供商支持除通用 `timeout` 和 `apiKey` 设置之外的额外配置选项。 ##### [Amazon Bedrock](https://opencode.ai/docs/zh-cn/config#amazon-bedrock) Amazon Bedrock 支持 AWS 特定配置: { "$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` - Bedrock 的 AWS 区域(默认为 `AWS_REGION` 环境变量或 `us-east-1`) * `profile` - 来自 `~/.aws/credentials` 的 AWS 命名配置文件(默认为 `AWS_PROFILE` 环境变量) * `endpoint` - VPC 端点的自定义端点 URL。这是通用 `baseURL` 选项使用 AWS 特定术语的别名。如果两者都指定,`endpoint` 优先。 [了解更多关于 Amazon Bedrock 配置的信息](https://opencode.ai/docs/providers#amazon-bedrock) 。 * * * ### [主题](https://opencode.ai/docs/zh-cn/config#%E4%B8%BB%E9%A2%98) 您可以通过 OpenCode 配置中的 `theme` 选项设置要使用的主题。 { "$schema": "https://opencode.ai/config.json", "theme": ""} [在此了解更多](https://opencode.ai/docs/themes) 。 * * * ### [代理](https://opencode.ai/docs/zh-cn/config#%E4%BB%A3%E7%90%86) 您可以通过 `agent` 选项为特定任务配置专用代理。 { "$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, }, }, },} 您还可以使用 `~/.config/opencode/agents/` 或 `.opencode/agents/` 中的 Markdown 文件定义代理。[在此了解更多](https://opencode.ai/docs/agents) 。 * * * ### [默认代理](https://opencode.ai/docs/zh-cn/config#%E9%BB%98%E8%AE%A4%E4%BB%A3%E7%90%86) 您可以使用 `default_agent` 选项设置默认代理。当未明确指定代理时,将使用该默认代理。 { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} 默认代理必须是主代理(不能是子代理)。可以是内置代理(如 `"build"` 或 `"plan"`),也可以是您定义的[自定义代理](https://opencode.ai/docs/agents) 。如果指定的代理不存在或是子代理,OpenCode 将回退到 `"build"` 并发出警告。 此设置适用于所有界面:TUI、CLI(`opencode run`)、桌面应用和 GitHub Action。 * * * ### [分享](https://opencode.ai/docs/zh-cn/config#%E5%88%86%E4%BA%AB) 您可以通过 `share` 选项配置[分享](https://opencode.ai/docs/share) 功能。 { "$schema": "https://opencode.ai/config.json", "share": "manual"} 该选项接受: * `"manual"` - 允许通过命令手动分享(默认) * `"auto"` - 自动分享新会话 * `"disabled"` - 完全禁用分享 默认情况下,分享设置为手动模式,您需要使用 `/share` 命令显式分享会话。 * * * ### [命令](https://opencode.ai/docs/zh-cn/config#%E5%91%BD%E4%BB%A4) 您可以通过 `command` 选项为重复任务配置自定义命令。 { "$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", }, },} 您还可以使用 `~/.config/opencode/commands/` 或 `.opencode/commands/` 中的 Markdown 文件定义命令。[在此了解更多](https://opencode.ai/docs/commands) 。 * * * ### [快捷键](https://opencode.ai/docs/zh-cn/config#%E5%BF%AB%E6%8D%B7%E9%94%AE) 您可以通过 `keybinds` 选项自定义快捷键。 { "$schema": "https://opencode.ai/config.json", "keybinds": {}} [在此了解更多](https://opencode.ai/docs/keybinds) 。 * * * ### [自动更新](https://opencode.ai/docs/zh-cn/config#%E8%87%AA%E5%8A%A8%E6%9B%B4%E6%96%B0) OpenCode 启动时会自动下载新版本。您可以使用 `autoupdate` 选项禁用此功能。 { "$schema": "https://opencode.ai/config.json", "autoupdate": false} 如果您不想自动更新但希望在新版本可用时收到通知,可将 `autoupdate` 设置为 `"notify"`。 请注意,此功能仅在未通过 Homebrew 等包管理器安装时有效。 * * * ### [格式化程序](https://opencode.ai/docs/zh-cn/config#%E6%A0%BC%E5%BC%8F%E5%8C%96%E7%A8%8B%E5%BA%8F) 您可以通过 `formatter` 选项配置代码格式化程序。 { "$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"] } }} [在此了解更多关于格式化程序的信息](https://opencode.ai/docs/formatters) 。 * * * ### [权限](https://opencode.ai/docs/zh-cn/config#%E6%9D%83%E9%99%90) 默认情况下,OpenCode **允许所有操作**,无需明确批准。您可以使用 `permission` 选项更改此行为。 例如,要让 `edit` 和 `bash` 工具需要用户确认: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [在此了解更多关于权限的信息](https://opencode.ai/docs/permissions) 。 * * * ### [压缩](https://opencode.ai/docs/zh-cn/config#%E5%8E%8B%E7%BC%A9) 您可以通过 `compaction` 选项控制上下文压缩行为。 { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - 当上下文已满时自动压缩会话(默认值:`true`)。 * `prune` - 删除旧的工具输出以节省 Token(默认值:`true`)。 * `reserved` - 压缩时的 Token 缓冲区。保留足够的窗口以避免压缩过程中溢出。 * * * ### [文件监视器](https://opencode.ai/docs/zh-cn/config#%E6%96%87%E4%BB%B6%E7%9B%91%E8%A7%86%E5%99%A8) 您可以通过 `watcher` 选项配置文件监视器的忽略模式。 { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} 模式遵循 glob 语法。使用此选项可以从文件监视中排除频繁变动的目录。 * * * ### [MCP 服务器](https://opencode.ai/docs/zh-cn/config#mcp-%E6%9C%8D%E5%8A%A1%E5%99%A8) 您可以通过 `mcp` 选项配置要使用的 MCP 服务器。 { "$schema": "https://opencode.ai/config.json", "mcp": {}} [在此了解更多](https://opencode.ai/docs/mcp-servers) 。 * * * ### [插件](https://opencode.ai/docs/zh-cn/config#%E6%8F%92%E4%BB%B6) [插件](https://opencode.ai/docs/plugins) 通过自定义工具、钩子和集成来扩展 OpenCode。 将插件文件放置在 `.opencode/plugins/` 或 `~/.config/opencode/plugins/` 中。您还可以通过 `plugin` 选项从 npm 加载插件。 { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [在此了解更多](https://opencode.ai/docs/plugins) 。 * * * ### [指令](https://opencode.ai/docs/zh-cn/config#%E6%8C%87%E4%BB%A4) 您可以通过 `instructions` 选项为所使用的模型配置指令。 { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} 该选项接受指令文件路径和 glob 模式的数组。[在此了解更多关于规则的信息](https://opencode.ai/docs/rules) 。 * * * ### [禁用提供商](https://opencode.ai/docs/zh-cn/config#%E7%A6%81%E7%94%A8%E6%8F%90%E4%BE%9B%E5%95%86) 您可以通过 `disabled_providers` 选项禁用自动加载的提供商。当您希望阻止某些提供商被加载(即使其凭据可用)时,此选项非常有用。 { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} `disabled_providers` 选项接受提供商 ID 的数组。当某个提供商被禁用时: * 即使设置了环境变量,也不会被加载。 * 即使通过 `/connect` 命令配置了 API 密钥,也不会被加载。 * 该提供商的模型不会出现在模型选择列表中。 * * * ### [启用提供商](https://opencode.ai/docs/zh-cn/config#%E5%90%AF%E7%94%A8%E6%8F%90%E4%BE%9B%E5%95%86) 您可以通过 `enabled_providers` 选项指定允许使用的提供商白名单。设置后,仅启用指定的提供商,所有其他提供商将被忽略。 { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} 当您希望限制 OpenCode 仅使用特定提供商,而不是逐一禁用其他提供商时,此选项非常有用。 如果某个提供商同时出现在 `enabled_providers` 和 `disabled_providers` 中,为了向后兼容,`disabled_providers` 优先。 * * * ### [实验性功能](https://opencode.ai/docs/zh-cn/config#%E5%AE%9E%E9%AA%8C%E6%80%A7%E5%8A%9F%E8%83%BD) `experimental` 键包含正在积极开发中的选项。 { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [变量](https://opencode.ai/docs/zh-cn/config#%E5%8F%98%E9%87%8F) --------------------------------------------------------------- 您可以在配置文件中使用变量替换来引用环境变量和文件内容。 * * * ### [环境变量](https://opencode.ai/docs/zh-cn/config#%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F) 使用 `{env:VARIABLE_NAME}` 来替换环境变量: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} 如果环境变量未设置,它将被替换为空字符串。 * * * ### [文件](https://opencode.ai/docs/zh-cn/config#%E6%96%87%E4%BB%B6) 使用 `{file:path/to/file}` 来替换文件内容: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} 文件路径可以是: * 相对于配置文件所在目录的路径 * 以 `/` 或 `~` 开头的绝对路径 这些功能适用于: * 将 API 密钥等敏感数据保存在单独的文件中。 * 引入大型指令文件而不会使配置变得杂乱。 * 在多个配置文件之间共享通用配置片段。 --- # Config | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/config#_top) Config ====== Using the OpenCode JSON config. JSON config 파일로 OpenCode를 설정할 수 있습니다. * * * [형식](https://opencode.ai/docs/ko/config#%ED%98%95%EC%8B%9D) ------------------------------------------------------------ OpenCode는 **JSON**과 **JSONC**(주석이 포함된 JSON) 형식을 모두 지원합니다. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [위치](https://opencode.ai/docs/ko/config#%EC%9C%84%EC%B9%98) ------------------------------------------------------------ config 파일은 여러 위치에 둘 수 있으며, 각 위치에는 우선순위가 있습니다. config 파일은 서로 대체되는 방식이 아니라 병합됩니다. 아래 config 위치의 설정이 결합되며, 충돌하는 key에 대해서만 나중에 로드된 config가 앞선 값을 override합니다. 충돌하지 않는 설정은 모두 유지됩니다. 예를 들어, 전역 config에 `autoupdate: true`가 있고 프로젝트 config에 `model: "anthropic/claude-sonnet-4-5"`가 있으면 최종 config에는 이 설정이 모두 포함됩니다. * * * ### [우선순위](https://opencode.ai/docs/ko/config#%EC%9A%B0%EC%84%A0%EC%88%9C%EC%9C%84) config source는 다음 순서로 로드됩니다(나중 source가 앞선 source를 override). 1. **Remote config**(`.well-known/opencode`) - 조직 기본값 2. **Global config**(`~/.config/opencode/opencode.json`) - 사용자 기본 설정 3. **Custom config**(`OPENCODE_CONFIG` env var) - custom override 4. **Project config**(프로젝트의 `opencode.json`) - 프로젝트별 설정 5. **`.opencode` directories** - agents, commands, plugins 6. **Inline config**(`OPENCODE_CONFIG_CONTENT` env var) - 런타임 override 즉, 프로젝트 config는 전역 기본값을 override할 수 있고, 전역 config는 조직의 Remote 기본값을 override할 수 있습니다. * * * ### [Remote](https://opencode.ai/docs/ko/config#remote) 조직은 `.well-known/opencode` endpoint로 기본 config를 제공할 수 있습니다. 이를 지원하는 provider로 인증하면 자동으로 가져옵니다. Remote config는 가장 먼저 로드되어 기본 레이어 역할을 합니다. 이후의 모든 config source(전역, 프로젝트)는 이 기본값을 override할 수 있습니다. 예를 들어, 조직에서 기본 비활성화된 MCP 서버를 제공하는 경우: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} 로컬 config에서 특정 서버를 활성화할 수 있습니다. { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global](https://opencode.ai/docs/ko/config#global) 전역 OpenCode config는 `~/.config/opencode/opencode.json`에 두세요. provider, model, permissions 같은 사용자 전체 기본 설정은 전역 config로 관리하세요. TUI 관련 설정은 `~/.config/opencode/tui.json`을 사용하세요. 전역 config는 조직의 Remote 기본값을 override합니다. * * * ### [Per project](https://opencode.ai/docs/ko/config#per-project) 프로젝트 루트에 `opencode.json`을 추가하세요. 프로젝트 config는 표준 config 파일 중 우선순위가 가장 높아 전역 및 Remote config를 모두 override합니다. 프로젝트별 TUI 설정은 `tui.json`을 함께 추가하세요. OpenCode 시작 시 현재 디렉토리에서 config 파일을 찾고, 없으면 가장 가까운 Git 디렉토리까지 상위로 탐색합니다. 이 파일은 Git에 커밋해도 안전하며 전역 config와 동일한 schema를 사용합니다. * * * ### [Custom path](https://opencode.ai/docs/ko/config#custom-path) `OPENCODE_CONFIG` 환경 변수로 custom config 파일 경로를 지정하세요. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Custom config는 우선순위상 전역 config와 프로젝트 config 사이에서 로드됩니다. * * * ### [Custom directory](https://opencode.ai/docs/ko/config#custom-directory) `OPENCODE_CONFIG_DIR` 환경 변수로 custom config 디렉토리를 지정할 수 있습니다. 이 디렉토리는 표준 `.opencode` 디렉토리와 동일하게 agents, commands, modes, plugins를 검색하며, 동일한 구조를 따라야 합니다. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" custom 디렉토리는 전역 config와 `.opencode` 디렉토리 뒤에 로드되므로 해당 설정을 **override할 수 있습니다**. * * * [Schema](https://opencode.ai/docs/ko/config#schema) ---------------------------------------------------- server/runtime config schema는 [**`opencode.ai/config.json`**](https://opencode.ai/config.json) 에 정의되어 있습니다. TUI config는 [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) 을 사용합니다. 편집기에서 이 schema를 기반으로 validation과 autocomplete를 사용할 수 있습니다. * * * ### [TUI](https://opencode.ai/docs/ko/config#tui) TUI 관련 설정에는 전용 `tui.json` (또는 `tui.jsonc`) 파일을 사용하세요. { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} `OPENCODE_TUI_CONFIG`를 사용하여 사용자 지정 TUI 설정 파일을 가리킬 수 있습니다. `opencode.json`의 기존 `theme`, `keybinds`, `tui` 키는 더 이상 사용되지 않으며(deprecated) 가능한 경우 자동으로 마이그레이션됩니다. [TUI 구성에 대해 더 알아보기](https://opencode.ai/docs/tui#configure) . * * * ### [Server](https://opencode.ai/docs/ko/config#server) `server` 옵션으로 `opencode serve`와 `opencode web` 명령의 server 설정을 구성할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} 사용 가능한 옵션: * `port` - 수신할 포트입니다. * `hostname` - 수신할 호스트명입니다. `mdns`가 활성화되어 있고 hostname이 없으면 기본값은 `0.0.0.0`입니다. * `mdns` - mDNS service discovery를 활성화합니다. 네트워크 내 다른 기기에서 OpenCode server를 찾을 수 있습니다. * `mdnsDomain` - mDNS service의 custom 도메인 이름입니다. 기본값은 `opencode.local`입니다. 같은 네트워크에서 여러 인스턴스를 실행할 때 유용합니다. * `cors` - 브라우저 기반 client에서 HTTP server를 사용할 때 허용할 추가 CORS origin입니다. 값은 전체 origin(scheme + host + optional port) 형식이어야 하며, 예: `https://app.example.com`. [server에 대해 더 알아보기](https://opencode.ai/docs/server) . * * * ### [Tools](https://opencode.ai/docs/ko/config#tools) `tools` 옵션으로 LLM이 사용할 수 있는 tool을 관리할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [tool에 대해 더 알아보기](https://opencode.ai/docs/tools) . * * * ### [Models](https://opencode.ai/docs/ko/config#models) OpenCode config의 `provider`, `model`, `small_model` 옵션으로 사용할 provider와 model을 설정할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} `small_model`은 제목 생성 같은 경량 작업에 사용할 별도 model을 설정합니다. 기본적으로 OpenCode는 provider에서 더 저렴한 model을 사용할 수 있으면 우선 사용하고, 없으면 메인 model로 fallback합니다. provider 옵션에는 `timeout`, `setCacheKey`를 포함할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - 요청 timeout(밀리초, 기본값: 300000). `false`로 비활성화할 수 있습니다. * `setCacheKey` - 지정된 provider에 대해 cache key가 항상 설정되도록 보장합니다. [local model](https://opencode.ai/docs/models#local) 도 설정할 수 있습니다. [더 알아보기](https://opencode.ai/docs/models) . * * * #### [Provider-Specific Options](https://opencode.ai/docs/ko/config#provider-specific-options) 일부 provider는 공통 옵션인 `timeout`, `apiKey` 외에 추가 config 옵션을 지원합니다. ##### [Amazon Bedrock](https://opencode.ai/docs/ko/config#amazon-bedrock) Amazon Bedrock은 AWS 전용 config를 지원합니다. { "$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` - Bedrock용 AWS 리전(`AWS_REGION` env var 또는 기본값 `us-east-1`) * `profile` - `~/.aws/credentials`의 AWS named profile(기본값: `AWS_PROFILE` env var) * `endpoint` - VPC endpoint용 custom endpoint URL입니다. AWS 용어를 사용한 일반 `baseURL` 옵션의 별칭(alias)입니다. 둘 다 지정하면 `endpoint`가 우선합니다. [Amazon Bedrock config 더 알아보기](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Themes](https://opencode.ai/docs/ko/config#themes) `tui.json`에서 UI 테마를 설정하세요. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [더 알아보기](https://opencode.ai/docs/themes) . * * * ### [Agents](https://opencode.ai/docs/ko/config#agents) `agent` 옵션으로 특정 작업용 전문 agent를 구성할 수 있습니다. { "$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, }, }, },} `~/.config/opencode/agents/` 또는 `.opencode/agents/`의 Markdown 파일로 agent를 정의할 수도 있습니다. [더 알아보기](https://opencode.ai/docs/agents) . * * * ### [Default agent](https://opencode.ai/docs/ko/config#default-agent) `default_agent` 옵션으로 기본 agent를 설정할 수 있습니다. 별도 지정이 없을 때 어떤 agent를 사용할지 결정합니다. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} 기본 agent는 primary agent여야 합니다(subagent 불가). `"build"`, `"plan"` 같은 내장 agent나 직접 정의한 [custom agent](https://opencode.ai/docs/agents) 를 지정할 수 있습니다. 지정한 agent가 없거나 subagent이면 OpenCode는 경고와 함께 `"build"`로 fallback합니다. 이 설정은 TUI, CLI(`opencode run`), 데스크톱 앱, GitHub Action 등 모든 인터페이스에 적용됩니다. * * * ### [Sharing](https://opencode.ai/docs/ko/config#sharing) `share` 옵션으로 [share](https://opencode.ai/docs/share) 기능을 설정할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "share": "manual"} 허용 값: * `"manual"` - 명령으로 수동 공유 허용(기본값) * `"auto"` - 새 대화를 자동 공유 * `"disabled"` - 공유 기능 완전 비활성화 기본값은 manual 모드이며, `/share` 명령으로 명시적으로 공유해야 합니다. * * * ### [Commands](https://opencode.ai/docs/ko/config#commands) `command` 옵션으로 반복 작업용 custom command를 구성할 수 있습니다. { "$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", }, },} `~/.config/opencode/commands/` 또는 `.opencode/commands/`의 Markdown 파일로 command를 정의할 수도 있습니다. [더 알아보기](https://opencode.ai/docs/commands) . * * * ### [Keybinds](https://opencode.ai/docs/ko/config#keybinds) `tui.json`에서 단축키를 사용자 지정하세요. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [더 알아보기](https://opencode.ai/docs/keybinds) . * * * ### [Autoupdate](https://opencode.ai/docs/ko/config#autoupdate) OpenCode는 시작 시 새 업데이트를 자동으로 다운로드합니다. `autoupdate` 옵션으로 비활성화할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} 업데이트를 자동 적용하지 않고 새 버전 알림만 받고 싶다면 `autoupdate`를 `"notify"`로 설정하세요. 이 옵션은 Homebrew 같은 패키지 매니저로 설치하지 않은 경우에만 동작합니다. * * * ### [Formatters](https://opencode.ai/docs/ko/config#formatters) `formatter` 옵션으로 코드 formatter를 설정할 수 있습니다. { "$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"] } }} [formatter에 대해 더 알아보기](https://opencode.ai/docs/formatters) . * * * ### [Permissions](https://opencode.ai/docs/ko/config#permissions) 기본적으로 OpenCode는 **명시적 승인 없이 모든 작업을 허용**합니다. `permission` 옵션으로 이 동작을 바꿀 수 있습니다. 예를 들어 `edit`, `bash` tool이 사용자 승인을 요구하게 하려면: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [permission에 대해 더 알아보기](https://opencode.ai/docs/permissions) . * * * ### [Compaction](https://opencode.ai/docs/ko/config#compaction) `compaction` 옵션으로 context compaction 동작을 제어할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - context가 가득 찼을 때 세션을 자동 compact합니다(기본값: `true`). * `prune` - token 절약을 위해 오래된 tool 출력을 제거합니다(기본값: `true`). * `reserved` - compaction용 token buffer입니다. compaction 중 overflow가 나지 않도록 충분한 window를 남깁니다. * * * ### [Watcher](https://opencode.ai/docs/ko/config#watcher) `watcher` 옵션으로 파일 watcher ignore 패턴을 설정할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} 패턴은 glob 문법을 따릅니다. 파일 감시에서 노이즈가 많은 디렉토리를 제외할 때 유용합니다. * * * ### [MCP servers](https://opencode.ai/docs/ko/config#mcp-servers) `mcp` 옵션으로 사용할 MCP server를 설정할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [더 알아보기](https://opencode.ai/docs/mcp-servers) . * * * ### [Plugins](https://opencode.ai/docs/ko/config#plugins) [Plugins](https://opencode.ai/docs/plugins) 는 custom tool, hook, integration으로 OpenCode를 확장합니다. plugin 파일은 `.opencode/plugins/` 또는 `~/.config/opencode/plugins/`에 두세요. `plugin` 옵션으로 npm plugin을 로드할 수도 있습니다. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [더 알아보기](https://opencode.ai/docs/plugins) . * * * ### [Instructions](https://opencode.ai/docs/ko/config#instructions) `instructions` 옵션으로 사용 중인 model에 제공할 지침 파일을 설정할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} 이 옵션은 지침 파일 경로 및 glob 패턴 배열을 받습니다. [rules에 대해 더 알아보기](https://opencode.ai/docs/rules) . * * * ### [Disabled providers](https://opencode.ai/docs/ko/config#disabled-providers) `disabled_providers` 옵션으로 자동 로드되는 provider를 비활성화할 수 있습니다. credential이 있어도 특정 provider를 로드하지 않게 하고 싶을 때 유용합니다. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} `disabled_providers`는 provider ID 배열을 받습니다. provider가 비활성화되면: * 환경 변수가 설정되어 있어도 로드되지 않습니다. * `/connect` 명령으로 API key를 설정해도 로드되지 않습니다. * 해당 provider의 model은 model 선택 목록에 표시되지 않습니다. * * * ### [Enabled providers](https://opencode.ai/docs/ko/config#enabled-providers) `enabled_providers` 옵션으로 provider allowlist를 지정할 수 있습니다. 이 값을 설정하면 지정한 provider만 활성화되고 나머지는 무시됩니다. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} provider를 하나씩 비활성화하는 대신, OpenCode가 특정 provider만 사용하도록 제한하고 싶을 때 유용합니다. 동일 provider가 `enabled_providers`와 `disabled_providers`에 모두 있으면 하위 호환성을 위해 `disabled_providers`가 우선합니다. * * * ### [Experimental](https://opencode.ai/docs/ko/config#experimental) `experimental` key에는 현재 활발히 개발 중인 옵션이 포함됩니다. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variables](https://opencode.ai/docs/ko/config#variables) ---------------------------------------------------------- config 파일에서 환경 변수와 파일 내용을 참조할 수 있도록 변수 치환을 사용할 수 있습니다. * * * ### [Env vars](https://opencode.ai/docs/ko/config#env-vars) `{env:VARIABLE_NAME}` 형식으로 환경 변수를 치환할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} 환경 변수가 설정되지 않았으면 빈 문자열로 치환됩니다. * * * ### [Files](https://opencode.ai/docs/ko/config#files) `{file:path/to/file}` 형식으로 파일 내용을 치환할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} 파일 경로는 다음을 지원합니다. * config 파일 디렉토리 기준 상대 경로 * `/` 또는 `~`로 시작하는 절대 경로 이 기능은 다음 상황에 유용합니다. * API key 같은 민감 정보를 별도 파일로 분리 * 큰 지침 파일을 config를 복잡하게 만들지 않고 포함 * 여러 config 파일에서 공통 설정 스니펫 재사용 --- # 設定 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/config#_top) 設定 == 使用 OpenCode JSON 設定。 您可以使用 JSON 設定檔來設定 OpenCode。 * * * [格式](https://opencode.ai/docs/zh-tw/config#%E6%A0%BC%E5%BC%8F) --------------------------------------------------------------- OpenCode 支援 **JSON** 和 **JSONC**(帶註解的 JSON)格式。 { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [位置](https://opencode.ai/docs/zh-tw/config#%E4%BD%8D%E7%BD%AE) --------------------------------------------------------------- 您可以將設定放置在不同的位置,它們具有不同的優先順序。 設定檔是合併在一起的,而不是被替換。來自以下設定位置的設定會被合併。後面的設定僅在鍵衝突時覆寫前面的設定。所有設定中的非衝突設定都會被保留。 例如,如果您的全域設定設定了 `autoupdate: true`,而您的專案設定設定了 `model: "anthropic/claude-sonnet-4-5"`,則最終設定將包含這兩個設定。 * * * ### [優先順序](https://opencode.ai/docs/zh-tw/config#%E5%84%AA%E5%85%88%E9%A0%86%E5%BA%8F) 設定來源按以下順序載入(後面的來源覆寫前面的來源): 1. **遠端設定**(來自 `.well-known/opencode`)- 組織預設值 2. **全域設定**(`~/.config/opencode/opencode.json`)- 使用者偏好 3. **自訂設定**(`OPENCODE_CONFIG` 環境變數)- 自訂覆寫 4. **專案設定**(專案中的 `opencode.json`)- 專案特定設定 5. **`.opencode` 目錄** - 代理、指令、外掛程式 6. **內嵌設定**(`OPENCODE_CONFIG_CONTENT` 環境變數)- 執行時覆寫 這意味著專案設定可以覆寫全域預設值,全域設定可以覆寫遠端組織預設值。 * * * ### [遠端](https://opencode.ai/docs/zh-tw/config#%E9%81%A0%E7%AB%AF) 組織可以透過 `.well-known/opencode` 端點提供預設設定。當您使用支援該功能的供應商進行身分驗證時,會自動擷取此設定。 遠端設定最先載入,作為基礎層。所有其他設定來源(全域、專案)都可以覆寫這些預設值。 例如,如果您的組織提供了預設停用的 MCP 伺服器: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} 您可以在本地設定中啟用特定伺服器: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [全域](https://opencode.ai/docs/zh-tw/config#%E5%85%A8%E5%9F%9F) 將全域 OpenCode 設定放在 `~/.config/opencode/opencode.json` 中。使用全域設定來設定使用者層級的偏好,例如主題、供應商或快捷鍵。 全域設定覆寫遠端組織預設值。 * * * ### [專案層級](https://opencode.ai/docs/zh-tw/config#%E5%B0%88%E6%A1%88%E5%B1%A4%E7%B4%9A) 在專案根目錄中新增 `opencode.json`。專案設定在標準設定檔中具有最高優先級——它會覆寫全域設定和遠端設定。 當 OpenCode 啟動時,它會在當前目錄中尋找設定檔,或向上遍歷到最近的 Git 目錄。 該設定檔也可以安全地提交到 Git 中,並使用與全域設定相同的 Schema。 * * * ### [自訂路徑](https://opencode.ai/docs/zh-tw/config#%E8%87%AA%E8%A8%82%E8%B7%AF%E5%BE%91) 使用 `OPENCODE_CONFIG` 環境變數指定自訂設定檔路徑。 export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" 自訂設定在優先順序中位於全域設定和專案設定之間載入。 * * * ### [自訂目錄](https://opencode.ai/docs/zh-tw/config#%E8%87%AA%E8%A8%82%E7%9B%AE%E9%8C%84) 使用 `OPENCODE_CONFIG_DIR` 環境變數指定自訂設定目錄。該目錄會像標準 `.opencode` 目錄一樣被搜尋代理、指令、模式和外掛程式,並且應遵循相同的結構。 export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" 自訂目錄在全域設定和 `.opencode` 目錄之後載入,因此**可以覆寫**它們的設定。 * * * [Schema](https://opencode.ai/docs/zh-tw/config#schema) ------------------------------------------------------- 設定檔具有在 [**`opencode.ai/config.json`**](https://opencode.ai/config.json) 中定義的 Schema。 您的編輯器應該能夠基於該 Schema 進行驗證和自動補全。 * * * ### [TUI](https://opencode.ai/docs/zh-tw/config#tui) 您可以透過 `tui` 選項設定 TUI 相關設定。 { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} 可用選項: * `scroll_acceleration.enabled` - 啟用 macOS 風格的捲動加速。**優先於 `scroll_speed`。** * `scroll_speed` - 自訂捲動速度倍率(預設值:`3`,最小值:`1`)。如果 `scroll_acceleration.enabled` 為 `true`,則忽略此選項。 * `diff_style` - 控制差異呈現方式。`"auto"` 根據終端機寬度自適應,`"stacked"` 始終顯示單列。 使用 `OPENCODE_TUI_CONFIG` 指向自訂 TUI 設定檔。 `opencode.json` 中的舊版 `theme`、`keybinds` 和 `tui` 鍵已被棄用,並將在可能的情況下自動遷移。 [在此了解更多關於 TUI 的資訊](https://opencode.ai/docs/tui) 。 * * * ### [伺服器](https://opencode.ai/docs/zh-tw/config#%E4%BC%BA%E6%9C%8D%E5%99%A8) 您可以透過 `server` 選項為 `opencode serve` 和 `opencode web` 指令設定伺服器設定。 { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} 可用選項: * `port` - 監聽連接埠。 * `hostname` - 監聽主機名稱。當 `mdns` 啟用且未設定主機名稱時,預設為 `0.0.0.0`。 * `mdns` - 啟用 mDNS 服務探索。這允許網路上的其他裝置發現您的 OpenCode 伺服器。 * `mdnsDomain` - mDNS 服務的自訂網域名稱。預設為 `opencode.local`。適用於在同一網路上執行多個實例的情境。 * `cors` - 從基於瀏覽器的用戶端使用 HTTP 伺服器時允許 CORS 的額外來源。值必須是完整的來源(通訊協定 + 主機 + 可選連接埠),例如 `https://app.example.com`。 [在此了解更多關於伺服器的資訊](https://opencode.ai/docs/server) 。 * * * ### [工具](https://opencode.ai/docs/zh-tw/config#%E5%B7%A5%E5%85%B7) 您可以透過 `tools` 選項管理 LLM 可以使用的工具。 { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [在此了解更多關於工具的資訊](https://opencode.ai/docs/tools) 。 * * * ### [模型](https://opencode.ai/docs/zh-tw/config#%E6%A8%A1%E5%9E%8B) 您可以透過 `provider`、`model` 和 `small_model` 選項在 OpenCode 設定中設定要使用的供應商和模型。 { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} `small_model` 選項為標題生成等輕量級任務設定單獨的模型。預設情況下,如果您的供應商有更便宜的模型可用,OpenCode 會嘗試使用該模型,否則會回退到您的主模型。 供應商選項可以包括 `timeout` 和 `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - 請求逾時時間,單位為毫秒(預設值:300000)。設定為 `false` 可停用逾時。 * `setCacheKey` - 確保始終為指定供應商設定快取金鑰。 您還可以設定[本地模型](https://opencode.ai/docs/models#local) 。[了解更多](https://opencode.ai/docs/models) 。 * * * #### [供應商特定選項](https://opencode.ai/docs/zh-tw/config#%E4%BE%9B%E6%87%89%E5%95%86%E7%89%B9%E5%AE%9A%E9%81%B8%E9%A0%85) 一些供應商支援除通用 `timeout` 和 `apiKey` 設定之外的額外設定選項。 ##### [Amazon Bedrock](https://opencode.ai/docs/zh-tw/config#amazon-bedrock) Amazon Bedrock 支援 AWS 特定設定: { "$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` - Bedrock 的 AWS 區域(預設為 `AWS_REGION` 環境變數或 `us-east-1`) * `profile` - 來自 `~/.aws/credentials` 的 AWS 命名設定檔(預設為 `AWS_PROFILE` 環境變數) * `endpoint` - VPC 端點的自訂端點 URL。這是通用 `baseURL` 選項使用 AWS 特定術語的別名。如果兩者都指定,`endpoint` 優先。 [了解更多關於 Amazon Bedrock 設定的資訊](https://opencode.ai/docs/providers#amazon-bedrock) 。 * * * ### [主題](https://opencode.ai/docs/zh-tw/config#%E4%B8%BB%E9%A1%8C) 在 `tui.json` 中設定您的 UI 主題。 { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [在此了解更多](https://opencode.ai/docs/themes) 。 * * * ### [代理](https://opencode.ai/docs/zh-tw/config#%E4%BB%A3%E7%90%86) 您可以透過 `agent` 選項為特定任務設定專用代理。 { "$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, }, }, },} 您還可以使用 `~/.config/opencode/agents/` 或 `.opencode/agents/` 中的 Markdown 檔案定義代理。[在此了解更多](https://opencode.ai/docs/agents) 。 * * * ### [預設代理](https://opencode.ai/docs/zh-tw/config#%E9%A0%90%E8%A8%AD%E4%BB%A3%E7%90%86) 您可以使用 `default_agent` 選項設定預設代理。當未明確指定代理時,將使用該預設代理。 { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} 預設代理必須是主代理(不能是子代理)。可以是內建代理(如 `"build"` 或 `"plan"`),也可以是您定義的[自訂代理](https://opencode.ai/docs/agents) 。如果指定的代理不存在或是子代理,OpenCode 將回退到 `"build"` 並發出警告。 此設定適用於所有介面:TUI、CLI(`opencode run`)、桌面應用程式和 GitHub Action。 * * * ### [分享](https://opencode.ai/docs/zh-tw/config#%E5%88%86%E4%BA%AB) 您可以透過 `share` 選項設定[分享](https://opencode.ai/docs/share) 功能。 { "$schema": "https://opencode.ai/config.json", "share": "manual"} 該選項接受: * `"manual"` - 允許透過指令手動分享(預設) * `"auto"` - 自動分享新工作階段 * `"disabled"` - 完全停用分享 預設情況下,分享設定為手動模式,您需要使用 `/share` 指令明確分享工作階段。 * * * ### [指令](https://opencode.ai/docs/zh-tw/config#%E6%8C%87%E4%BB%A4) 您可以透過 `command` 選項為重複任務設定自訂指令。 { "$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", }, },} 您還可以使用 `~/.config/opencode/commands/` 或 `.opencode/commands/` 中的 Markdown 檔案定義指令。[在此了解更多](https://opencode.ai/docs/commands) 。 * * * ### [快捷鍵](https://opencode.ai/docs/zh-tw/config#%E5%BF%AB%E6%8D%B7%E9%8D%B5) 在 `tui.json` 中自訂快捷鍵。 { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [在此了解更多](https://opencode.ai/docs/keybinds) 。 * * * ### [自動更新](https://opencode.ai/docs/zh-tw/config#%E8%87%AA%E5%8B%95%E6%9B%B4%E6%96%B0) OpenCode 啟動時會自動下載新版本。您可以使用 `autoupdate` 選項停用此功能。 { "$schema": "https://opencode.ai/config.json", "autoupdate": false} 如果您不想自動更新但希望在新版本可用時收到通知,可將 `autoupdate` 設定為 `"notify"`。 請注意,此功能僅在未透過 Homebrew 等套件管理器安裝時有效。 * * * ### [格式化器](https://opencode.ai/docs/zh-tw/config#%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%99%A8) 您可以透過 `formatter` 選項設定程式碼格式化器。 { "$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"] } }} [在此了解更多關於格式化器的資訊](https://opencode.ai/docs/formatters) 。 * * * ### [權限](https://opencode.ai/docs/zh-tw/config#%E6%AC%8A%E9%99%90) 預設情況下,OpenCode **允許所有操作**,無需明確批准。您可以使用 `permission` 選項變更此行為。 例如,要讓 `edit` 和 `bash` 工具需要使用者確認: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [在此了解更多關於權限的資訊](https://opencode.ai/docs/permissions) 。 * * * ### [壓縮](https://opencode.ai/docs/zh-tw/config#%E5%A3%93%E7%B8%AE) 您可以透過 `compaction` 選項控制上下文壓縮行為。 { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - 當上下文已滿時自動壓縮工作階段(預設值:`true`)。 * `prune` - 刪除舊的工具輸出以節省 Token(預設值:`true`)。 * `reserved` - 壓縮時的 Token 緩衝區。保留足夠的窗口以避免壓縮過程中溢出。 * * * ### [檔案監看器](https://opencode.ai/docs/zh-tw/config#%E6%AA%94%E6%A1%88%E7%9B%A3%E7%9C%8B%E5%99%A8) 您可以透過 `watcher` 選項設定檔案監看器的忽略模式。 { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} 模式遵循 glob 語法。使用此選項可以從檔案監看中排除頻繁變動的目錄。 * * * ### [MCP 伺服器](https://opencode.ai/docs/zh-tw/config#mcp-%E4%BC%BA%E6%9C%8D%E5%99%A8) 您可以透過 `mcp` 選項設定要使用的 MCP 伺服器。 { "$schema": "https://opencode.ai/config.json", "mcp": {}} [在此了解更多](https://opencode.ai/docs/mcp-servers) 。 * * * ### [外掛程式](https://opencode.ai/docs/zh-tw/config#%E5%A4%96%E6%8E%9B%E7%A8%8B%E5%BC%8F) [外掛程式](https://opencode.ai/docs/plugins) 透過自訂工具、掛鉤和整合來擴展 OpenCode。 將外掛程式檔案放置在 `.opencode/plugins/` 或 `~/.config/opencode/plugins/` 中。您還可以透過 `plugin` 選項從 npm 載入外掛程式。 { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [在此了解更多](https://opencode.ai/docs/plugins) 。 * * * ### [指示](https://opencode.ai/docs/zh-tw/config#%E6%8C%87%E7%A4%BA) 您可以透過 `instructions` 選項為所使用的模型設定指示。 { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} 該選項接受指示檔案路徑和 glob 模式的陣列。[在此了解更多關於規則的資訊](https://opencode.ai/docs/rules) 。 * * * ### [停用供應商](https://opencode.ai/docs/zh-tw/config#%E5%81%9C%E7%94%A8%E4%BE%9B%E6%87%89%E5%95%86) 您可以透過 `disabled_providers` 選項停用自動載入的供應商。當您希望阻止某些供應商被載入(即使其憑證可用)時,此選項非常有用。 { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} `disabled_providers` 選項接受供應商 ID 的陣列。當某個供應商被停用時: * 即使設定了環境變數,也不會被載入。 * 即使透過 `/connect` 指令設定了 API 金鑰,也不會被載入。 * 該供應商的模型不會出現在模型選擇列表中。 * * * ### [啟用供應商](https://opencode.ai/docs/zh-tw/config#%E5%95%9F%E7%94%A8%E4%BE%9B%E6%87%89%E5%95%86) 您可以透過 `enabled_providers` 選項指定允許使用的供應商白名單。設定後,僅啟用指定的供應商,所有其他供應商將被忽略。 { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} 當您希望限制 OpenCode 僅使用特定供應商,而不是逐一停用其他供應商時,此選項非常有用。 如果某個供應商同時出現在 `enabled_providers` 和 `disabled_providers` 中,為了向後相容,`disabled_providers` 優先。 * * * ### [實驗性功能](https://opencode.ai/docs/zh-tw/config#%E5%AF%A6%E9%A9%97%E6%80%A7%E5%8A%9F%E8%83%BD) `experimental` 鍵包含正在積極開發中的選項。 { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [變數](https://opencode.ai/docs/zh-tw/config#%E8%AE%8A%E6%95%B8) --------------------------------------------------------------- 您可以在設定檔中使用變數替換來參照環境變數和檔案內容。 * * * ### [環境變數](https://opencode.ai/docs/zh-tw/config#%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8) 使用 `{env:VARIABLE_NAME}` 來替換環境變數: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} 如果環境變數未設定,它將被替換為空字串。 * * * ### [檔案](https://opencode.ai/docs/zh-tw/config#%E6%AA%94%E6%A1%88) 使用 `{file:path/to/file}` 來替換檔案內容: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} 檔案路徑可以是: * 相對於設定檔所在目錄的路徑 * 以 `/` 或 `~` 開頭的絕對路徑 這些功能適用於: * 將 API 金鑰等敏感資料保存在單獨的檔案中。 * 引入大型指示檔案而不會使設定變得雜亂。 * 在多個設定檔之間共享通用設定片段。 --- # Configuration | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/config#_top) Configuration ============= Utilisation de la configuration JSON OpenCode. Vous pouvez configurer OpenCode à l’aide d’un fichier de configuration JSON. * * * [Format](https://opencode.ai/docs/fr/config#format) ---------------------------------------------------- OpenCode prend en charge les formats **JSON** et **JSONC** (JSON avec commentaires). { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [Emplacements](https://opencode.ai/docs/fr/config#emplacements) ---------------------------------------------------------------- Vous pouvez placer votre configuration à plusieurs emplacements différents et ils ont un ordre de priorité différent. Les fichiers de configuration sont fusionnés et non remplacés. Les paramètres des emplacements de configuration suivants sont combinés. Les configurations ultérieures remplacent les précédentes uniquement en cas de clés en conflit. Les paramètres non conflictuels de toutes les configurations sont conservés. Par exemple, si votre configuration globale définit `autoupdate: true` et que la configuration de votre projet définit `model: "anthropic/claude-sonnet-4-5"`, la configuration finale inclura les deux paramètres. * * * ### [Ordre de priorité](https://opencode.ai/docs/fr/config#ordre-de-priorit%C3%A9) Les sources de configuration sont chargées dans cet ordre (les sources ultérieures remplacent les précédentes) : 1. **Configuration distante** (à partir de `.well-known/opencode`) - paramètres par défaut de l’organisation 2. **Configuration globale** (`~/.config/opencode/opencode.json`) - préférences utilisateur 3. **Configuration personnalisée** (`OPENCODE_CONFIG` env var) - remplacements personnalisés 4. **Configuration du projet** (`opencode.json` dans le projet) - paramètres spécifiques au projet 5. **Répertoires `.opencode`** - agents, commandes, plugins 6. **Configuration en ligne** (`OPENCODE_CONFIG_CONTENT` env var) - remplacements d’exécution Cela signifie que les configurations de projet peuvent remplacer les valeurs par défaut globales, et que les configurations globales peuvent remplacer les valeurs par défaut de l’organisation distante. * * * ### [Configuration distante](https://opencode.ai/docs/fr/config#configuration-distante) Les organisations peuvent fournir une configuration par défaut via le point de terminaison `.well-known/opencode`. Ceci est récupéré automatiquement lorsque vous vous authentifiez auprès d’un fournisseur qui le prend en charge. La configuration distante est chargée en premier, servant de couche de base. Toutes les autres sources de configuration (globales, projet) peuvent remplacer ces valeurs par défaut. Par exemple, si votre organisation fournit des serveurs MCP qui sont désactivés par défaut : { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Vous pouvez activer des serveurs spécifiques dans votre configuration locale : { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Globale](https://opencode.ai/docs/fr/config#globale) Placez votre configuration globale OpenCode dans `~/.config/opencode/opencode.json`. Utilisez la configuration globale pour les préférences de l’utilisateur telles que les fournisseurs, les modèles et les autorisations. Pour les paramètres spécifiques à TUI, utilisez `~/.config/opencode/tui.json`. La configuration globale remplace les paramètres par défaut de l’organisation distante. * * * ### [Par projet](https://opencode.ai/docs/fr/config#par-projet) Ajoutez `opencode.json` à la racine de votre projet. La configuration du projet a la priorité la plus élevée parmi les fichiers de configuration standard : elle remplace les configurations globales et distantes. Pour les paramètres TUI spécifiques au projet, ajoutez `tui.json` à côté. Lorsque OpenCode démarre, il recherche un fichier de configuration dans le répertoire actuel ou remonte jusqu’au répertoire Git le plus proche. Il peut également être archivé en toute sécurité dans Git et utilise le même schéma que le schéma global. * * * ### [Chemin personnalisé](https://opencode.ai/docs/fr/config#chemin-personnalis%C3%A9) Spécifiez un chemin de fichier de configuration personnalisé à l’aide de la variable d’environnement `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" La configuration personnalisée est chargée entre les configurations globales et celles du projet dans l’ordre de priorité. * * * ### [Répertoire personnalisé](https://opencode.ai/docs/fr/config#r%C3%A9pertoire-personnalis%C3%A9) Spécifiez un répertoire de configuration personnalisé à l’aide de `OPENCODE_CONFIG_DIR` variable d’environnement. Ce répertoire sera recherché pour les agents, les commandes, modes et plugins tout comme le répertoire standard `.opencode`, et devrait suivre la même structure. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" Le répertoire personnalisé est chargé après les répertoires de configuration globale et `.opencode`, il **peut donc remplacer** leurs paramètres. * * * [Schéma](https://opencode.ai/docs/fr/config#sch%C3%A9ma) --------------------------------------------------------- Le fichier de configuration a un schéma défini dans [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . La configuration TUI utilise [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) . Votre éditeur doit être capable de valider et de compléter automatiquement en fonction du schéma. * * * ### [TUI](https://opencode.ai/docs/fr/config#tui) Utilisez un fichier dédié `tui.json` (ou `tui.jsonc`) pour les paramètres spécifiques à TUI. { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Utilisez `OPENCODE_TUI_CONFIG` pour pointer vers un fichier de configuration TUI personnalisé. Les anciennes clés `theme`, `keybinds` et `tui` dans `opencode.json` sont obsolètes et migrées automatiquement lorsque cela est possible. [En savoir plus sur l’utilisation du TUI ici](https://opencode.ai/docs/tui#configure) . * * * ### [Serveur](https://opencode.ai/docs/fr/config#serveur) Vous pouvez configurer les paramètres du serveur pour les commandes `opencode serve` et `opencode web` via l’option `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Options disponibles : * `port` - Port d’écoute. * `hostname` - Nom d’hôte d’écoute. Lorsque `mdns` est activé et qu’aucun nom d’hôte n’est défini, la valeur par défaut est `0.0.0.0`. * `mdns` - Activer la découverte du service mDNS. Cela permet à d’autres appareils du réseau de découvrir votre serveur OpenCode. * `mdnsDomain` - Nom de domaine personnalisé pour le service mDNS. La valeur par défaut est `opencode.local`. Utile pour exécuter plusieurs instances sur le même réseau. * `cors` - Origines supplémentaires pour autoriser CORS lors de l’utilisation du serveur HTTP à partir d’un client basé sur un navigateur. Les valeurs doivent être des origines complètes (schéma + hôte + port facultatif), par exemple `https://app.example.com`. [En savoir plus sur le serveur ici](https://opencode.ai/docs/server) . * * * ### [Outils](https://opencode.ai/docs/fr/config#outils) Vous pouvez gérer les outils qu’un LLM peut utiliser via l’option `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [En savoir plus sur les outils ici](https://opencode.ai/docs/tools) . * * * ### [Modèles](https://opencode.ai/docs/fr/config#mod%C3%A8les) Vous pouvez configurer les fournisseurs et les modèles que vous souhaitez utiliser dans votre configuration OpenCode via les options `provider`, `model` et `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} L’option `small_model` configure un modèle distinct pour les tâches légères comme la génération de titres. Par défaut, OpenCode essaie d’utiliser un modèle moins cher s’il est disponible auprès de votre fournisseur, sinon il revient à votre modèle principal. Les options du fournisseur peuvent inclure `timeout` et `setCacheKey` : { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Délai d’expiration de la demande en millisecondes (par défaut : 300 000). Réglez sur `false` pour désactiver. * `setCacheKey` - Assurez-vous qu’une clé de cache est toujours définie pour le fournisseur désigné. Vous pouvez également configurer [modèles locaux](https://opencode.ai/docs/models#local) . [En savoir plus](https://opencode.ai/docs/models) . * * * #### [Options spécifiques au fournisseur](https://opencode.ai/docs/fr/config#options-sp%C3%A9cifiques-au-fournisseur) Certains fournisseurs prennent en charge des options de configuration supplémentaires au-delà des paramètres génériques `timeout` et `apiKey`. ##### [Amazon Bedrock](https://opencode.ai/docs/fr/config#amazon-bedrock) Amazon Bedrock prend en charge la configuration spécifique à AWS : { "$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` - Région AWS pour Bedrock (par défaut : `AWS_REGION` env var ou `us-east-1`) * `profile` - Profil nommé AWS de `~/.aws/credentials` (par défaut : `AWS_PROFILE` env var) * `endpoint` - Point de terminaison personnalisé URL pour les points de terminaison d’un VPC. Il s’agit d’un alias pour l’option générique `baseURL` utilisant la terminologie spécifique à AWS. Si les deux sont spécifiés, `endpoint` est prioritaire. [En savoir plus sur la configuration d’Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Thèmes](https://opencode.ai/docs/fr/config#th%C3%A8mes) Définissez votre thème d’interface utilisateur dans `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [En savoir plus ici](https://opencode.ai/docs/themes) . * * * ### [Agents](https://opencode.ai/docs/fr/config#agents) Vous pouvez configurer des agents spécialisés pour des tâches spécifiques via l’option `agent`. { "$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, }, }, },} Vous pouvez également définir des agents à l’aide de fichiers markdown dans `~/.config/opencode/agents/` ou `.opencode/agents/`. [En savoir plus ici](https://opencode.ai/docs/agents) . * * * ### [Agent par défaut](https://opencode.ai/docs/fr/config#agent-par-d%C3%A9faut) Vous pouvez définir l’agent par défaut à l’aide de l’option `default_agent`. Ceci détermine quel agent est utilisé lorsqu’aucun n’est explicitement spécifié. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} L’agent par défaut doit être un agent principal (et non un sous-agent). Il peut s’agir d’un agent intégré tel que `"build"` ou `"plan"`, ou d’un [agent personnalisé](https://opencode.ai/docs/agents) que vous avez défini. Si l’agent spécifié n’existe pas ou est un sous-agent, OpenCode reviendra à `"build"` avec un avertissement. Ce paramètre s’applique à toutes les interfaces : TUI, CLI (`opencode run`), application de bureau et GitHub Action. * * * ### [Partage](https://opencode.ai/docs/fr/config#partage) Vous pouvez configurer la fonctionnalité [share](https://opencode.ai/docs/share) via l’option `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Elle accepte : * `"manual"` – Autoriser le partage manuel via des commandes (par défaut) * `"auto"` – Partager automatiquement de nouvelles conversations * `"disabled"` – Désactiver complètement le partage Par défaut, le partage est défini en mode manuel où vous devez partager explicitement les conversations à l’aide de la commande `/share`. * * * ### [Commandes](https://opencode.ai/docs/fr/config#commandes) Vous pouvez configurer des commandes personnalisées pour les tâches répétitives via l’option `command`. { "$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", }, },} Vous pouvez également définir des commandes à l’aide de fichiers markdown dans `~/.config/opencode/commands/` ou `.opencode/commands/`. [En savoir plus ici](https://opencode.ai/docs/commands) . * * * ### [Raccourcis clavier](https://opencode.ai/docs/fr/config#raccourcis-clavier) Personnalisez les raccourcis clavier dans `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [En savoir plus ici](https://opencode.ai/docs/keybinds) . * * * ### [Mise à jour automatique](https://opencode.ai/docs/fr/config#mise-%C3%A0-jour-automatique) OpenCode téléchargera automatiquement toutes les nouvelles mises à jour au démarrage. Vous pouvez désactiver cela avec l’option `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Si vous ne souhaitez pas de mises à jour mais souhaitez être averti lorsqu’une nouvelle version est disponible, définissez `autoupdate` sur `"notify"`. Notez que cela ne fonctionne que s’il n’a pas été installé à l’aide d’un gestionnaire de packages tel que Homebrew. * * * ### [Formateurs](https://opencode.ai/docs/fr/config#formateurs) Vous pouvez configurer les formateurs de code via l’option `formatter`. { "$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"] } }} [En savoir plus sur les formateurs ici](https://opencode.ai/docs/formatters) . * * * ### [Autorisations](https://opencode.ai/docs/fr/config#autorisations) Par défaut, opencode **autorise toutes les opérations** sans nécessiter d’approbation explicite. Vous pouvez modifier cela en utilisant l’option `permission`. Par exemple, pour garantir que les outils `edit` et `bash` nécessitent l’approbation de l’utilisateur : { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [En savoir plus sur les autorisations ici](https://opencode.ai/docs/permissions) . * * * ### [Compactage](https://opencode.ai/docs/fr/config#compactage) Vous pouvez contrôler le comportement de compactage du contexte via l’option `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - Compacte automatiquement la session lorsque le contexte est plein (par défaut : `true`). * `prune` - Supprimez les anciennes sorties de l’outil pour économiser des tokens (par défaut : `true`). * `reserved` - Tampon de jetons pour le compactage. Laisse suffisamment de marge pour éviter le débordement lors du compactage. * * * ### [Observateur](https://opencode.ai/docs/fr/config#observateur) Vous pouvez configurer les modèles d’ignorance de l’observateur de fichiers via l’option `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Les modèles suivent la syntaxe glob. Utilisez ceci pour exclure les répertoires bruyants de la surveillance des fichiers. * * * ### [Serveurs MCP](https://opencode.ai/docs/fr/config#serveurs-mcp) Vous pouvez configurer les serveurs MCP que vous souhaitez utiliser via l’option `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [En savoir plus ici](https://opencode.ai/docs/mcp-servers) . * * * ### [Extensions](https://opencode.ai/docs/fr/config#extensions) [Plugins](https://opencode.ai/docs/plugins) étendent OpenCode avec des outils, des hooks et des intégrations personnalisés. Placez les fichiers du plugin dans `.opencode/plugins/` ou `~/.config/opencode/plugins/`. Vous pouvez également charger des plugins depuis npm via l’option `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [En savoir plus ici](https://opencode.ai/docs/plugins) . * * * ### [Instructions](https://opencode.ai/docs/fr/config#instructions) Vous pouvez configurer les instructions pour le modèle que vous utilisez via l’option `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Cela prend un tableau de chemins et de modèles globaux vers les fichiers d’instructions. [En savoir plus sur les règles ici](https://opencode.ai/docs/rules) . * * * ### [Fournisseurs désactivés](https://opencode.ai/docs/fr/config#fournisseurs-d%C3%A9sactiv%C3%A9s) Vous pouvez désactiver les fournisseurs chargés automatiquement via l’option `disabled_providers`. Ceci est utile lorsque vous souhaitez empêcher le chargement de certains fournisseurs même si leurs informations d’identification sont disponibles. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} L’option `disabled_providers` accepte un tableau d’ID de fournisseur. Lorsqu’un fournisseur est désactivé : * Il ne sera pas chargé même si des variables d’environnement sont définies. * Il ne sera pas chargé même si les clés API sont configurées via la commande `/connect`. * Les modèles du fournisseur n’apparaîtront pas dans la liste de sélection des modèles. * * * ### [Fournisseurs activés](https://opencode.ai/docs/fr/config#fournisseurs-activ%C3%A9s) Vous pouvez spécifier une liste autorisée de fournisseurs via l’option `enabled_providers`. Une fois défini, seuls les fournisseurs spécifiés seront activés et tous les autres seront ignorés. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Ceci est utile lorsque vous souhaitez restreindre OpenCode à l’utilisation de fournisseurs spécifiques plutôt que de les désactiver un par un. Si un fournisseur apparaît à la fois dans `enabled_providers` et `disabled_providers`, le `disabled_providers` est prioritaire pour la compatibilité ascendante. * * * ### [Expérimental](https://opencode.ai/docs/fr/config#exp%C3%A9rimental) La clé `experimental` contient des options en cours de développement actif. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variables](https://opencode.ai/docs/fr/config#variables) ---------------------------------------------------------- Vous pouvez utiliser la substitution de variables dans vos fichiers de configuration pour référencer les variables d’environnement et le contenu des fichiers. * * * ### [Variables d’environnement](https://opencode.ai/docs/fr/config#variables-denvironnement) Utilisez `{env:VARIABLE_NAME}` pour remplacer les variables d’environnement : { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Si la variable d’environnement n’est pas définie, elle sera remplacée par une chaîne vide. * * * ### [Fichiers](https://opencode.ai/docs/fr/config#fichiers) Utilisez `{file:path/to/file}` pour remplacer le contenu d’un fichier : { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Les chemins de fichiers peuvent être : * Relatifs au répertoire du fichier de configuration * Ou des chemins absolus commençant par `/` ou `~` Elles sont utiles pour : * Conserver les données sensibles telles que les clés API dans des fichiers séparés. * Inclure de gros fichiers d’instructions sans encombrer votre configuration. * Partager des extraits de configuration communs sur plusieurs fichiers de configuration. --- # Konfiguration | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/config#_top) Konfiguration ============= Verwenden Sie die Konfiguration OpenCode JSON. Sie können OpenCode mithilfe einer JSON-Konfigurationsdatei konfigurieren. * * * [Format](https://opencode.ai/docs/de/config#format) ---------------------------------------------------- OpenCode unterstützt die Formate **JSON** und **JSONC** (JSON mit Kommentaren). { "$schema": "https://opencode.ai/config.json", // Theme configuration "theme": "opencode", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true,} * * * [Speicherorte](https://opencode.ai/docs/de/config#speicherorte) ---------------------------------------------------------------- Sie können Ihre Konfiguration an verschiedenen Orten platzieren und sie haben eine andere Rangfolge. Konfigurationsdateien werden zusammengeführt und nicht ersetzt. Einstellungen aus den folgenden Konfigurationsspeicherorten werden kombiniert. Spätere Konfigurationen überschreiben frühere nur bei Schlüsselkonflikten. Es bleiben keine widersprüchlichen Einstellungen aus allen Konfigurationen erhalten. Wenn Ihre globale Konfiguration beispielsweise `theme: "opencode"` und `autoupdate: true` und Ihre Projektkonfiguration `model: "anthropic/claude-sonnet-4-5"` festlegt, umfasst die endgültige Konfiguration alle drei Einstellungen. * * * ### [Rangfolge](https://opencode.ai/docs/de/config#rangfolge) Konfigurationsquellen werden in dieser Reihenfolge geladen (spätere Quellen überschreiben frühere): 1. **Remote-Konfiguration** (von `.well-known/opencode`) – Organisationsstandards 2. **Globale Konfiguration** (`~/.config/opencode/opencode.json`) – Benutzereinstellungen 3. **Benutzerdefinierte Konfiguration** (`OPENCODE_CONFIG` env var) – benutzerdefinierte Überschreibungen 4. **Projektkonfiguration** (`opencode.json` im Projekt) – projektspezifische Einstellungen 5. **`.opencode` Verzeichnisse** – Agenten, Befehle, Plugins 6. **Inline-Konfiguration** (`OPENCODE_CONFIG_CONTENT` env var) – Laufzeitüberschreibungen Dies bedeutet, dass Projektkonfigurationen globale Standardeinstellungen überschreiben können und globale Konfigurationen Remote-Organisationsstandards überschreiben können. * * * ### [Remote](https://opencode.ai/docs/de/config#remote) Organisationen können die Standardkonfiguration über den Endpunkt `.well-known/opencode` bereitstellen. Dieser wird automatisch abgerufen, wenn Sie sich bei einem Anbieter authentifizieren, der dies unterstützt. Zuerst wird die Remote-Konfiguration geladen, die als Basisschicht dient. Alle anderen Konfigurationsquellen (global, Projekt) können diese Standardeinstellungen überschreiben. Wenn Ihre Organisation beispielsweise MCP-Server bereitstellt, sind die standardmäßig deaktiviert: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Sie können bestimmte Server in Ihrer lokalen Konfiguration aktivieren: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global](https://opencode.ai/docs/de/config#global) Platzieren Sie Ihre globale OpenCode-Konfiguration in `~/.config/opencode/opencode.json`. Verwenden Sie die globale Konfiguration für benutzerweite Einstellungen wie Themen, Anbieter oder Tastenkombinationen. Die globale Konfiguration überschreibt die Standardeinstellungen der Remote-Organisation. * * * ### [Pro Projekt](https://opencode.ai/docs/de/config#pro-projekt) Fügen Sie `opencode.json` in Ihrem Projektstamm hinzu. Die Projektkonfiguration hat unter den Standardkonfigurationsdateien die höchste Priorität – sie überschreibt sowohl globale als auch Remote-Konfigurationen. Wenn OpenCode gestartet wird, sucht es im aktuellen Verzeichnis nach einer Konfigurationsdatei oder durchsucht das nächstgelegene Git-Verzeichnis. Dies kann auch sicher in Git eingecheckt werden und dasselbe Schema wie das globale verwenden. * * * ### [Benutzerdefinierter Pfad](https://opencode.ai/docs/de/config#benutzerdefinierter-pfad) Geben Sie mithilfe der Umgebungsvariablen `OPENCODE_CONFIG` einen benutzerdefinierten Konfigurationsdateipfad an. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Die benutzerdefinierte Konfiguration wird in der Rangfolge zwischen globalen und Projektkonfigurationen geladen. * * * ### [Benutzerdefiniertes Verzeichnis](https://opencode.ai/docs/de/config#benutzerdefiniertes-verzeichnis) Geben Sie mit `OPENCODE_CONFIG_DIR` ein benutzerdefiniertes Konfigurationsverzeichnis an. Umgebungsvariable. Dieses Verzeichnis wird nach Agenten, Befehlen, Modi und Plugins genau wie das Standardverzeichnis `.opencode` und sollten folgen der gleichen Struktur. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" Das benutzerdefinierte Verzeichnis wird nach den Verzeichnissen global config und `.opencode` geladen, sodass es deren Einstellungen **überschreiben** kann. * * * [Schema](https://opencode.ai/docs/de/config#schema) ---------------------------------------------------- Die Konfigurationsdatei verfügt über ein Schema, das in [**`opencode.ai/config.json`**](https://opencode.ai/config.json) definiert ist. Ihr Editor sollte in der Lage sein, basierend auf dem Schema zu validieren und automatisch zu vervollständigen. * * * ### [TUI](https://opencode.ai/docs/de/config#tui) Sie können TUI-spezifische Einstellungen über die Option `tui` konfigurieren. { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} Verfügbare Optionen: * `scroll_acceleration.enabled` – Scrollbeschleunigung im macOS-Stil aktivieren. **Hat Vorrang vor `scroll_speed`.** * `scroll_speed` – Benutzerdefinierter Scrollgeschwindigkeitsmultiplikator (Standard: `3`, Minimum: `1`). Wird ignoriert, wenn `scroll_acceleration.enabled` gleich `true` ist. * `diff_style` – Steuern Sie das Diff-Rendering. `"auto"` passt sich der Terminalbreite an, `"stacked"` zeigt immer eine einzelne Spalte an. [Erfahren Sie hier mehr über die Verwendung der TUI](https://opencode.ai/docs/tui) . * * * ### [Server](https://opencode.ai/docs/de/config#server) Sie können Servereinstellungen für die Befehle `opencode serve` und `opencode web` über die Option `server` konfigurieren. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Verfügbare Optionen: * `port` – Port zum Abhören. * `hostname` – Hostname zum Abhören. Wenn `mdns` aktiviert ist und kein Hostname festgelegt ist, wird standardmäßig `0.0.0.0` verwendet. * `mdns` – mDNS-Diensterkennung aktivieren. Dadurch können andere Geräte im Netzwerk Ihres OpenCode-Servers erkannt werden. * `mdnsDomain` – Benutzerdefinierter Domänenname für den mDNS-Dienst. Standardmäßig ist `opencode.local`. Nützlich für die Ausführung mehrerer Instanzen im selben Netzwerk. * `cors` – Zusätzliche Ursprünge, um CORS zu ermöglichen, wenn der HTTP-Server von einem browserbasierten Client aus verwendet wird. Die Werte müssen vollständige Ursprünge haben (Schema + Host + optionaler Port), z. B. `https://app.example.com`. [Erfahren Sie hier mehr über den Server](https://opencode.ai/docs/server) . * * * ### [Werkzeuge](https://opencode.ai/docs/de/config#werkzeuge) Sie können die Tools, die ein LLM verwenden kann, über die Option `tools` verwalten. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Erfahren Sie hier mehr über Tools](https://opencode.ai/docs/tools) . * * * ### [Modelle](https://opencode.ai/docs/de/config#modelle) Sie können die Anbieter und Modelle, die Sie in Ihrer OpenCode-Konfiguration verwenden möchten, über die Optionen `provider`, `model` und `small_model` konfigurieren. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} Die Option `small_model` konfiguriert ein separates Modell für einfache Aufgaben wie die Titelgenerierung. Standardmäßig versucht OpenCode, ein günstigeres Modell zu verwenden, sofern eines bei Ihrem Anbieter verfügbar ist, andernfalls greift es auf Ihr Hauptmodell zurück. Zu den Anbieteroptionen können `timeout` und `setCacheKey` gehören: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` – Anforderungszeitlimit in Millisekunden (Standard: 300000). Zum Deaktivieren auf `false` setzen. * `setCacheKey` – Stellen Sie sicher, dass immer ein Cache-Schlüssel für den angegebenen Anbieter festgelegt ist. Sie können auch [lokale Modelle](https://opencode.ai/docs/models#local) konfigurieren. [Mehr erfahren](https://opencode.ai/docs/models) . * * * #### [Anbieterspezifische Optionen](https://opencode.ai/docs/de/config#anbieterspezifische-optionen) Einige Anbieter unterstützen zusätzliche Konfigurationsoptionen über die allgemeinen Einstellungen `timeout` und `apiKey` hinaus. ##### [Amazon Bedrock](https://opencode.ai/docs/de/config#amazon-bedrock) Amazon Bedrock unterstützt AWS-spezifische Konfigurationen: { "$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 für Bedrock (standardmäßig `AWS_REGION` env var oder `us-east-1`) * `profile` – AWS benanntes Profil von `~/.aws/credentials` (standardmäßig `AWS_PROFILE` Umgebungsvariable) * `endpoint` – Benutzerdefinierter Endpunkt URL für VPC-Endpunkte. Dies ist ein Alias ​​​​für die generische Option `baseURL` unter Verwendung der AWS-spezifischen Terminologie. Wenn beide angegeben sind, hat `endpoint` Vorrang. [Erfahren Sie mehr über die Amazon Bedrock-Konfiguration](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Themen](https://opencode.ai/docs/de/config#themen) Sie können das Thema, das Sie in Ihrer OpenCode-Konfiguration verwenden möchten, über die Option `theme` konfigurieren. { "$schema": "https://opencode.ai/config.json", "theme": ""} [Mehr erfahren](https://opencode.ai/docs/themes) . * * * ### [Agenten](https://opencode.ai/docs/de/config#agenten) Über die Option `agent` können Sie spezielle Agenten für bestimmte Aufgaben konfigurieren. { "$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, }, }, },} Sie können Agenten auch mithilfe von Markdown-Dateien in `~/.config/opencode/agents/` oder `.opencode/agents/` definieren. [Mehr erfahren](https://opencode.ai/docs/agents) . * * * ### [Standardagent](https://opencode.ai/docs/de/config#standardagent) Sie können den Standardagenten mit der Option `default_agent` festlegen. Dadurch wird bestimmt, welcher Agent verwendet wird, wenn keiner explizit angegeben wird. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} Der Standardagent muss ein Primäragent (kein Subagent) sein. Dies kann ein integrierter Agent wie `"build"` oder `"plan"` oder ein von Ihnen definierter [custom agent](https://opencode.ai/docs/agents) sein. Wenn der angegebene Agent nicht existiert oder ein Subagent ist, greift OpenCode mit einer Warnung auf `"build"` zurück. Diese Einstellung gilt für alle Schnittstellen: TUI, CLI (`opencode run`), Desktop-App und GitHub Aktion. * * * ### [Teilen](https://opencode.ai/docs/de/config#teilen) Sie können die Funktion [share](https://opencode.ai/docs/share) über die Option `share` konfigurieren. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Dazu braucht es: * `"manual"` – Manuelles Teilen über Befehle zulassen (Standard) * `"auto"` – Neue Konversationen automatisch teilen * `"disabled"` – Teile vollständig deaktivieren Standardmäßig ist die Freigabe auf den manuellen Modus eingestellt, in dem Sie Konversationen explizit mit dem Befehl `/share` teilen müssen. * * * ### [Befehle](https://opencode.ai/docs/de/config#befehle) Sie können benutzerdefinierte Befehle für sich wiederholende Aufgaben über die Option `command` konfigurieren. { "$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", }, },} Sie können Befehle auch mithilfe von Markdown-Dateien in `~/.config/opencode/commands/` oder `.opencode/commands/` definieren. [Mehr erfahren](https://opencode.ai/docs/commands) . * * * ### [Tastenkombinationen](https://opencode.ai/docs/de/config#tastenkombinationen) Sie können Ihre Tastenkombinationen über die Option `keybinds` anpassen. { "$schema": "https://opencode.ai/config.json", "keybinds": {}} [Mehr erfahren](https://opencode.ai/docs/keybinds) . * * * ### [Automatisches Update](https://opencode.ai/docs/de/config#automatisches-update) OpenCode lädt beim Start automatisch alle neuen Updates herunter. Sie können dies mit der Option `autoupdate` deaktivieren. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Wenn Sie keine Updates wünschen, aber dringend möchten, wenn eine neue Version verfügbar ist, setzen Sie `autoupdate` auf `"notify"`. Beachten Sie, dass dies nur funktioniert, wenn es nicht mit einem Paketmanager wie Homebrew installiert wurde. * * * ### [Formatierer](https://opencode.ai/docs/de/config#formatierer) Sie können Codeformatierer über die Option `formatter` konfigurieren. { "$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"] } }} [Erfahren Sie hier mehr über Formatierer](https://opencode.ai/docs/formatters) . * * * ### [Berechtigungen](https://opencode.ai/docs/de/config#berechtigungen) OpenCode erlaubt standardmäßig alle Vorgänge, ohne dass eine ausdrückliche Genehmigung erforderlich ist. Sie können dies mit der Option `permission` ändern. Um beispielsweise sicherzustellen, dass die Tools `edit` und `bash` eine Benutzergenehmigung erfordern: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Erfahren Sie hier mehr über Berechtigungen](https://opencode.ai/docs/permissions) . * * * ### [Komprimierung](https://opencode.ai/docs/de/config#komprimierung) Sie können das Verhalten der Kontextkomprimierung über die Option `compaction` steuern. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true }} * `auto` – Die Sitzung wird automatisch komprimieren, wenn der Kontext voll ist (Standard: `true`). * `prune` – Alte Tool-Ausgaben entfernen, um Token zu sparen (Standard: `true`). * * * ### [Dateiüberwachung](https://opencode.ai/docs/de/config#datei%C3%BCberwachung) Sie können Datei-Watcher-Ignoriermuster über die Option `watcher` konfigurieren. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Muster folgen der Glob-Syntax. Verwenden Sie diese Option, um verrauschte Verzeichnisse von der Dateiüberwachung auszuschließen. * * * ### [MCP](https://opencode.ai/docs/de/config#mcp) Sie können den MCP-Server, den Sie verwenden möchten, über die Option `mcp` konfigurieren. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Mehr erfahren](https://opencode.ai/docs/mcp-servers) . * * * ### [Plugins](https://opencode.ai/docs/de/config#plugins) [Plugins](https://opencode.ai/docs/plugins) erweitert OpenCode mit benutzerdefinierten Tools, Hooks und Integrationen. Platzieren Sie Ihre Plugin-Dateien in `.opencode/plugins/` oder `~/.config/opencode/plugins/`. Sie können Plugins auch über die Option `plugin` von npm laden. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Mehr erfahren](https://opencode.ai/docs/plugins) . * * * ### [Anweisungen](https://opencode.ai/docs/de/config#anweisungen) Sie können die Anweisungen für das von Ihnen verwendete Modell über die Option `instructions` konfigurieren. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Dies erfordert eine Reihe von Pfaden und Glob-Mustern zu Anweisungsdateien. [Erfahren Sie hier mehr über Regeln](https://opencode.ai/docs/rules) . * * * ### [Deaktivierte Anbieter](https://opencode.ai/docs/de/config#deaktivierte-anbieter) Sie können Anbieter, die automatisch geladen werden, über die Option `disabled_providers` deaktivieren. Dies ist nützlich, wenn Sie verhindern möchten, dass bestimmte Anbieter geladen werden, selbst wenn deren Anmeldeinformationen verfügbar sind. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} Die Option `disabled_providers` akzeptiert ein Array des Anbieters IDs. Wenn ein Anbieter deaktiviert ist: * Es wird nicht geladen, selbst wenn Umgebungsvariablen festgelegt sind. * Es wird nicht geladen, selbst wenn API-Schlüssel über den Befehl `/connect` konfiguriert werden. * Die Modelle des Anbieters erscheinen nicht in der Modellauswahlliste. * * * ### [Aktivierte Anbieter](https://opencode.ai/docs/de/config#aktivierte-anbieter) Sie können über die Option `enabled_providers` eine Zulassungsliste für Anbieter angeben. Wenn diese Option festgelegt ist, werden nur die angegebenen Anbieter aktiviert und alle anderen werden ignoriert. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Dies ist nützlich, wenn Sie OpenCode darauf beschränken möchten, nur bestimmte Anbieter zu verwenden, anstatt sie einzeln zu deaktivieren. Wenn ein Anbieter sowohl in `enabled_providers` als auch in `disabled_providers` vorkommt, hat `disabled_providers` aus Gründen der Abwärtskompatibilität Vorrang. * * * ### [Experimentell](https://opencode.ai/docs/de/config#experimentell) Der Schlüssel `experimental` enthält Optionen, die sich in der aktiven Entwicklung befinden. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variablen](https://opencode.ai/docs/de/config#variablen) ---------------------------------------------------------- Sie können die Variablenersetzung in Ihren Konfigurationsdateien verwenden, um auf Umgebungsvariablen und Dateiinhalte zu verweisen. * * * ### [Umgebungsvariablen](https://opencode.ai/docs/de/config#umgebungsvariablen) Verwenden Sie `{env:VARIABLE_NAME}`, um Umgebungsvariablen zu ersetzen: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Wenn die Umgebungsvariable nicht gesetzt ist, wird sie durch eine leere Zeichenfolge ersetzt. * * * ### [Dateien](https://opencode.ai/docs/de/config#dateien) Verwenden Sie `{file:path/to/file}`, um den Inhalt einer Datei zu ersetzen: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Dateipfade können sein: * Relativ zum Konfigurationsdateiverzeichnis * Oder absolute Pfade beginnend mit `/` oder `~` Diese sind nützlich für: * Bewahren Sie vertrauliche Daten wie API-Schlüssel in separaten Dateien auf. * Einschließlich große Anweisungsdateien, ohne Ihre Konfiguration zu überladen. * Gemeinsame Nutzung gemeinsamer Konfigurationsausschnitte über mehrere Konfigurationsdateien hinweg. --- # Configuración | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/config#_top) Configuración ============= Usando la configuración OpenCode JSON. Puede configurar OpenCode usando un archivo de configuración JSON. * * * [Formato](https://opencode.ai/docs/es/config#formato) ------------------------------------------------------ OpenCode admite los formatos **JSON** y **JSONC** (JSON con comentarios). { "$schema": "https://opencode.ai/config.json", // Theme configuration "theme": "opencode", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true,} * * * [Ubicaciones](https://opencode.ai/docs/es/config#ubicaciones) -------------------------------------------------------------- Puedes colocar tu configuración en un par de ubicaciones diferentes y tienen un diferente orden de precedencia. Los archivos de configuración se fusionan, no se reemplazan. Se combinan las configuraciones de las siguientes ubicaciones de configuración. Las configuraciones posteriores anulan las anteriores solo para claves en conflicto. Se conservan las configuraciones no conflictivas de todas las configuraciones. Por ejemplo, si su configuración global establece `theme: "opencode"` y `autoupdate: true`, y la configuración de su proyecto establece `model: "anthropic/claude-sonnet-4-5"`, la configuración final incluirá las tres configuraciones. * * * ### [Orden de precedencia](https://opencode.ai/docs/es/config#orden-de-precedencia) Las fuentes de configuración se cargan en este orden (las fuentes posteriores anulan las anteriores): 1. **Configuración remota** (de `.well-known/opencode`): valores predeterminados de la organización 2. **Configuración global** (`~/.config/opencode/opencode.json`) - preferencias del usuario 3. **Configuración personalizada** (`OPENCODE_CONFIG` env var): anulaciones personalizadas 4. **Configuración del proyecto** (`opencode.json` en el proyecto): configuración específica del proyecto 5. Directorios **`.opencode`** - agentes, comandos, complementos 6. **Configuración en línea** (`OPENCODE_CONFIG_CONTENT` env var): anulaciones del tiempo de ejecución Esto significa que las configuraciones del proyecto pueden anular los valores predeterminados globales y las configuraciones globales pueden anular los valores predeterminados de la organización remota. * * * ### [Remoto](https://opencode.ai/docs/es/config#remoto) Las organizaciones pueden proporcionar una configuración predeterminada a través del punto final `.well-known/opencode`. Esto se obtiene automáticamente cuando se autentica con un proveedor que lo admita. La configuración remota se carga primero y sirve como capa base. Todas las demás fuentes de configuración (global, proyecto) pueden anular estos valores predeterminados. Por ejemplo, si su organización proporciona servidores MCP que están deshabilitados de forma predeterminada: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Puede habilitar servidores específicos en su configuración local: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global](https://opencode.ai/docs/es/config#global) Coloque su configuración global OpenCode en `~/.config/opencode/opencode.json`. Utilice la configuración global para las preferencias de todo el usuario, como temas, proveedores o combinaciones de teclas. La configuración global anula los valores predeterminados de la organización remota. * * * ### [Por proyecto](https://opencode.ai/docs/es/config#por-proyecto) Agregue `opencode.json` en la raíz de su proyecto. La configuración del proyecto tiene la mayor prioridad entre los archivos de configuración estándar: anula las configuraciones globales y remotas. Cuando se inicia OpenCode, busca un archivo de configuración en el directorio actual o recorre hasta el directorio Git más cercano. Esto también es seguro para registrarlo en Git y utiliza el mismo esquema que el global. * * * ### [Ruta personalizada](https://opencode.ai/docs/es/config#ruta-personalizada) Especifique una ruta de archivo de configuración personalizada utilizando la variable de entorno `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" La configuración personalizada se carga entre las configuraciones globales y del proyecto en orden de prioridad. * * * ### [Directorio personalizado](https://opencode.ai/docs/es/config#directorio-personalizado) Especifique un directorio de configuración personalizado usando `OPENCODE_CONFIG_DIR` variable de entorno. En este directorio se buscarán agentes, comandos, modos y complementos como el directorio estándar `.opencode`, y debería Sigue la misma estructura. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" El directorio personalizado se carga después de los directorios global config y `.opencode`, por lo que **puede anular** su configuración. * * * [Esquema](https://opencode.ai/docs/es/config#esquema) ------------------------------------------------------ El archivo de configuración tiene un esquema definido en [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . Su editor debería poder validar y autocompletar según el esquema. * * * ### [TUI](https://opencode.ai/docs/es/config#tui) Puede configurar ajustes específicos de TUI a través de la opción `tui`. { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} Opciones disponibles: * `scroll_acceleration.enabled` - Habilita la aceleración de desplazamiento estilo macOS. **Tiene prioridad sobre `scroll_speed`.** * `scroll_speed` - Multiplicador de velocidad de desplazamiento personalizado (predeterminado: `3`, mínimo: `1`). Se ignora si `scroll_acceleration.enabled` es `true`. * `diff_style` - Controla la representación de diferencias. `"auto"` se adapta al ancho del terminal, `"stacked"` siempre muestra una sola columna. [Obtenga más información sobre el uso de TUI aquí](https://opencode.ai/docs/tui) . * * * ### [Servidor](https://opencode.ai/docs/es/config#servidor) Puede configurar los ajustes del servidor para los comandos `opencode serve` y `opencode web` a través de la opción `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Opciones disponibles: * `port` - Puerto para escuchar. * `hostname`: nombre de host para escuchar. Cuando `mdns` está habilitado y no se establece ningún nombre de host, el valor predeterminado es `0.0.0.0`. * `mdns`: habilita el descubrimiento de servicios mDNS. Esto permite que otros dispositivos en la red descubran su servidor OpenCode. * `mdnsDomain` - Nombre de dominio personalizado para el servicio mDNS. El valor predeterminado es `opencode.local`. Útil para ejecutar múltiples instancias en la misma red. * `cors`: orígenes adicionales para permitir CORS cuando se utiliza el servidor HTTP desde un cliente basado en navegador. Los valores deben ser orígenes completos (esquema + host + puerto opcional), por ejemplo, `https://app.example.com`. [Obtenga más información sobre el servidor aquí](https://opencode.ai/docs/server) . * * * ### [Herramientas](https://opencode.ai/docs/es/config#herramientas) Puede administrar las herramientas que un LLM puede usar a través de la opción `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Obtenga más información sobre las herramientas aquí](https://opencode.ai/docs/tools) . * * * ### [Modelos](https://opencode.ai/docs/es/config#modelos) Puede configurar los proveedores y modelos que desea utilizar en su configuración OpenCode a través de las opciones `provider`, `model` y `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} La opción `small_model` configura un modelo separado para tareas livianas como la generación de títulos. De forma predeterminada, OpenCode intenta utilizar un modelo más económico si su proveedor tiene uno disponible; de ​​lo contrario, recurre a su modelo principal. Las opciones de proveedores pueden incluir `timeout` y `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout`: tiempo de espera de solicitud en milisegundos (predeterminado: 300000). Establezca en `false` para desactivar. * `setCacheKey`: asegúrese de que siempre haya una clave de caché configurada para el proveedor designado. También puede configurar [modelos locales](https://opencode.ai/docs/models#local) . [Más información](https://opencode.ai/docs/models) . * * * #### [Opciones específicas del proveedor](https://opencode.ai/docs/es/config#opciones-espec%C3%ADficas-del-proveedor) Algunos proveedores admiten opciones de configuración adicionales más allá de las configuraciones genéricas `timeout` y `apiKey`. ##### [Amazon Bedrock](https://opencode.ai/docs/es/config#amazon-bedrock) Amazon Bedrock admite la configuración específica de AWS: { "$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 región para Bedrock (el valor predeterminado es `AWS_REGION` env var o `us-east-1`) * `profile` - AWS perfil con nombre de `~/.aws/credentials` (el valor predeterminado es `AWS_PROFILE` var env) * `endpoint`: URL de punto de enlace personalizada para puntos de enlace de VPC. Este es un alias para la opción genérica `baseURL` que utiliza terminología específica de AWS. Si se especifican ambos, `endpoint` tiene prioridad. [Obtenga más información sobre la configuración de Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Temas](https://opencode.ai/docs/es/config#temas) Puede configurar el tema que desea usar en su configuración OpenCode a través de la opción `theme`. { "$schema": "https://opencode.ai/config.json", "theme": ""} [Más información aquí](https://opencode.ai/docs/themes) . * * * ### [Agentes](https://opencode.ai/docs/es/config#agentes) Puedes configurar agentes especializados para tareas específicas a través de la opción `agent`. { "$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, }, }, },} También puede definir agentes utilizando archivos de Markdown en `~/.config/opencode/agents/` o `.opencode/agents/`. [Más información aquí](https://opencode.ai/docs/agents) . * * * ### [Agente predeterminado](https://opencode.ai/docs/es/config#agente-predeterminado) Puede configurar el agente predeterminado usando la opción `default_agent`. Esto determina qué agente se utiliza cuando no se especifica ninguno explícitamente. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} El agente predeterminado debe ser un agente principal (no un subagente). Puede ser un agente integrado como `"build"` o `"plan"`, o un [agente personalizado](https://opencode.ai/docs/agents) que haya definido. Si el agente especificado no existe o es un subagente, OpenCode recurrirá a `"build"` con una advertencia. Esta configuración se aplica en todas las interfaces: TUI, CLI (`opencode run`), aplicación de escritorio y GitHub Acción. * * * ### [Compartir](https://opencode.ai/docs/es/config#compartir) Puede configurar la función [compartir](https://opencode.ai/docs/share) a través de la opción `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Esto requiere: * `"manual"` - Permitir compartir manualmente mediante comandos (predeterminado) * `"auto"` - Comparte automáticamente nuevas conversaciones * `"disabled"` - Deshabilitar el uso compartido por completo De forma predeterminada, el uso compartido está configurado en modo manual, donde debe compartir conversaciones explícitamente usando el comando `/share`. * * * ### [Comandos](https://opencode.ai/docs/es/config#comandos) Puede configurar comandos personalizados para tareas repetitivas a través de la opción `command`. { "$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", }, },} También puede definir comandos utilizando archivos de Markdown en `~/.config/opencode/commands/` o `.opencode/commands/`. [Más información aquí](https://opencode.ai/docs/commands) . * * * ### [Atajos de teclado](https://opencode.ai/docs/es/config#atajos-de-teclado) Puede personalizar sus combinaciones de teclas a través de la opción `keybinds`. { "$schema": "https://opencode.ai/config.json", "keybinds": {}} [Más información aquí](https://opencode.ai/docs/keybinds) . * * * ### [Actualización automática](https://opencode.ai/docs/es/config#actualizaci%C3%B3n-autom%C3%A1tica) OpenCode descargará automáticamente cualquier actualización nueva cuando se inicie. Puede desactivar esto con la opción `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Si no desea actualizaciones pero desea recibir una notificación cuando haya una nueva versión disponible, configure `autoupdate` en `"notify"`. Tenga en cuenta que esto sólo funciona si no se instaló mediante un administrador de paquetes como Homebrew. * * * ### [Formateadores](https://opencode.ai/docs/es/config#formateadores) Puede configurar formateadores de código a través de la opción `formatter`. { "$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"] } }} [Obtenga más información sobre los formateadores aquí](https://opencode.ai/docs/formatters) . * * * ### [Permisos](https://opencode.ai/docs/es/config#permisos) De forma predeterminada, opencode **permite todas las operaciones** sin requerir aprobación explícita. Puede cambiar esto usando la opción `permission`. Por ejemplo, para garantizar que las herramientas `edit` y `bash` requieran la aprobación del usuario: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Obtenga más información sobre los permisos aquí](https://opencode.ai/docs/permissions) . * * * ### [Compactación](https://opencode.ai/docs/es/config#compactaci%C3%B3n) Puede controlar el comportamiento de compactación del contexto a través de la opción `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true }} * `auto`: compacta automáticamente la sesión cuando el contexto está lleno (predeterminado: `true`). * `prune`: elimina las salidas de herramientas antiguas para guardar tokens (predeterminado: `true`). * * * ### [Observador](https://opencode.ai/docs/es/config#observador) Puede configurar patrones de ignorancia del observador de archivos a través de la opción `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Los patrones siguen la sintaxis global. Utilice esto para excluir directorios ruidosos de la visualización de archivos. * * * ### [Servidores MCP](https://opencode.ai/docs/es/config#servidores-mcp) Puede configurar los servidores MCP que desee utilizar a través de la opción `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Más información aquí](https://opencode.ai/docs/mcp-servers) . * * * ### [Complementos](https://opencode.ai/docs/es/config#complementos) Los [complementos](https://opencode.ai/docs/plugins) amplían OpenCode con herramientas, enlaces e integraciones personalizados. Coloque los archivos de complemento en `.opencode/plugins/` o `~/.config/opencode/plugins/`. También puedes cargar complementos desde npm a través de la opción `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Más información aquí](https://opencode.ai/docs/plugins) . * * * ### [Instrucciones](https://opencode.ai/docs/es/config#instrucciones) Puedes configurar las instrucciones para el modelo que estás usando a través de la opción `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Esto requiere una variedad de rutas y patrones globales para archivos de instrucciones. [Más información sobre las reglas aquí](https://opencode.ai/docs/rules) . * * * ### [Proveedores deshabilitados](https://opencode.ai/docs/es/config#proveedores-deshabilitados) Puede deshabilitar proveedores que se cargan automáticamente a través de la opción `disabled_providers`. Esto es útil cuando desea evitar que se carguen ciertos proveedores incluso si sus credenciales están disponibles. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} La opción `disabled_providers` acepta una variedad de ID de proveedores. Cuando un proveedor está deshabilitado: * No se cargará incluso si se establecen variables de entorno. * No se cargará incluso si las teclas API están configuradas mediante el comando `/connect`. * Los modelos del proveedor no aparecerán en la lista de selección de modelos. * * * ### [Proveedores habilitados](https://opencode.ai/docs/es/config#proveedores-habilitados) Puede especificar una lista de proveedores permitidos a través de la opción `enabled_providers`. Cuando se establece, solo se habilitarán los proveedores especificados y se ignorarán todos los demás. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Esto es útil cuando desea restringir OpenCode para que utilice únicamente proveedores específicos en lugar de deshabilitarlos uno por uno. Si un proveedor aparece tanto en `enabled_providers` como en `disabled_providers`, el `disabled_providers` tiene prioridad para la compatibilidad con versiones anteriores. * * * ### [Experimental](https://opencode.ai/docs/es/config#experimental) La clave `experimental` contiene opciones que se encuentran en desarrollo activo. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variables](https://opencode.ai/docs/es/config#variables) ---------------------------------------------------------- Puede utilizar la sustitución de variables en sus archivos de configuración para hacer referencia a variables de entorno y contenidos de archivos. * * * ### [Variables de entorno](https://opencode.ai/docs/es/config#variables-de-entorno) Utilice `{env:VARIABLE_NAME}` para sustituir variables de entorno: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Si la variable de entorno no está configurada, se reemplazará con una cadena vacía. * * * ### [Archivos](https://opencode.ai/docs/es/config#archivos) Utilice `{file:path/to/file}` para sustituir el contenido de un archivo: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Las rutas de los archivos pueden ser: * Relativo al directorio del archivo de configuración * O rutas absolutas que comienzan con `/` o `~` Estos son útiles para: * Mantener datos confidenciales como claves API en archivos separados. * Incluye archivos de instrucciones grandes sin saturar tu configuración. * Compartir fragmentos de configuración comunes en múltiples archivos de configuración. --- # Share | OpenCode [Skip to content](https://opencode.ai/docs/share#_top) Share ===== Share your OpenCode conversations. OpenCode’s share feature allows you to create public links to your OpenCode conversations, so you can collaborate with teammates or get help from others. * * * [How it works](https://opencode.ai/docs/share#how-it-works) ------------------------------------------------------------ When you share a conversation, OpenCode: 1. Creates a unique public URL for your session 2. Syncs your conversation history to our servers 3. Makes the conversation accessible via the shareable link — `opncd.ai/s/` * * * [Sharing](https://opencode.ai/docs/share#sharing) -------------------------------------------------- OpenCode supports three sharing modes that control how conversations are shared: * * * ### [Manual (default)](https://opencode.ai/docs/share#manual-default) By default, OpenCode uses manual sharing mode. Sessions are not shared automatically, but you can manually share them using the `/share` command: /share This will generate a unique URL that’ll be copied to your clipboard. To explicitly set manual mode in your [config file](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Auto-share](https://opencode.ai/docs/share#auto-share) You can enable automatic sharing for all new conversations by setting the `share` option to `"auto"` in your [config file](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} With auto-share enabled, every new conversation will automatically be shared and a link will be generated. * * * ### [Disabled](https://opencode.ai/docs/share#disabled) You can disable sharing entirely by setting the `share` option to `"disabled"` in your [config file](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} To enforce this across your team for a given project, add it to the `opencode.json` in your project and check into Git. * * * [Un-sharing](https://opencode.ai/docs/share#un-sharing) -------------------------------------------------------- To stop sharing a conversation and remove it from public access: /unshare This will remove the share link and delete the data related to the conversation. * * * [Privacy](https://opencode.ai/docs/share#privacy) -------------------------------------------------- There are a few things to keep in mind when sharing a conversation. * * * ### [Data retention](https://opencode.ai/docs/share#data-retention) Shared conversations remain accessible until you explicitly unshare them. This includes: * Full conversation history * All messages and responses * Session metadata * * * ### [Recommendations](https://opencode.ai/docs/share#recommendations) * Only share conversations that don’t contain sensitive information. * Review conversation content before sharing. * Unshare conversations when collaboration is complete. * Avoid sharing conversations with proprietary code or confidential data. * For sensitive projects, disable sharing entirely. * * * [For enterprises](https://opencode.ai/docs/share#for-enterprises) ------------------------------------------------------------------ For enterprise deployments, the share feature can be: * **Disabled** entirely for security compliance * **Restricted** to users authenticated through SSO only * **Self-hosted** on your own infrastructure [Learn more](https://opencode.ai/docs/enterprise) about using opencode in your organization. --- # 分享 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/share#_top) 分享 == 分享您的 OpenCode 對話。 OpenCode 的分享功能允許您建立指向 OpenCode 對話的公開連結,方便與團隊成員協作或向他人尋求幫助。 * * * [工作原理](https://opencode.ai/docs/zh-tw/share#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) ---------------------------------------------------------------------------------- 當您分享一段對話時,OpenCode 會: 1. 為您的工作階段建立一個唯一的公開 URL 2. 將您的對話歷史同步到我們的伺服器 3. 透過可分享的連結使對話可存取 — `opncd.ai/s/` * * * [分享模式](https://opencode.ai/docs/zh-tw/share#%E5%88%86%E4%BA%AB%E6%A8%A1%E5%BC%8F) ---------------------------------------------------------------------------------- OpenCode 支援三種分享模式,用於控制對話的共享方式: * * * ### [手動模式(預設)](https://opencode.ai/docs/zh-tw/share#%E6%89%8B%E5%8B%95%E6%A8%A1%E5%BC%8F%E9%A0%90%E8%A8%AD) 預設情況下,OpenCode 使用手動分享模式。工作階段不會自動共享,但您可以使用 `/share` 指令手動分享: /share 這將產生一個唯一的 URL 並複製到您的剪貼簿。 要在[設定檔](https://opencode.ai/docs/config) 中明確設定手動模式: { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [自動分享](https://opencode.ai/docs/zh-tw/share#%E8%87%AA%E5%8B%95%E5%88%86%E4%BA%AB) 您可以在[設定檔](https://opencode.ai/docs/config) 中將 `share` 選項設定為 `"auto"`,為所有新對話啟用自動分享: { "$schema": "https://opencode.ai/config.json", "share": "auto"} 啟用自動分享後,每個新對話都會自動共享並產生連結。 * * * ### [停用](https://opencode.ai/docs/zh-tw/share#%E5%81%9C%E7%94%A8) 您可以在[設定檔](https://opencode.ai/docs/config) 中將 `share` 選項設定為 `"disabled"`,完全停用分享功能: { "$schema": "https://opencode.ai/config.json", "share": "disabled"} 要在團隊中對特定專案強制執行此設定,請將其新增到專案的 `opencode.json` 檔案中並提交到 Git。 * * * [取消分享](https://opencode.ai/docs/zh-tw/share#%E5%8F%96%E6%B6%88%E5%88%86%E4%BA%AB) ---------------------------------------------------------------------------------- 要停止分享對話並將其從公開存取中移除: /unshare 這將移除分享連結並刪除與該對話相關的資料。 * * * [隱私](https://opencode.ai/docs/zh-tw/share#%E9%9A%B1%E7%A7%81) -------------------------------------------------------------- 分享對話時需要注意以下幾點。 * * * ### [資料保留](https://opencode.ai/docs/zh-tw/share#%E8%B3%87%E6%96%99%E4%BF%9D%E7%95%99) 共享的對話在您明確取消分享之前將一直保持可存取狀態。這包括: * 完整的對話歷史 * 所有訊息和回覆 * 工作階段中繼資料 * * * ### [建議](https://opencode.ai/docs/zh-tw/share#%E5%BB%BA%E8%AD%B0) * 僅分享不包含敏感資訊的對話。 * 分享前請檢查對話內容。 * 協作完成後請取消分享。 * 避免分享包含專有程式碼或機密資料的對話。 * 對於敏感專案,請完全停用分享功能。 * * * [企業版](https://opencode.ai/docs/zh-tw/share#%E4%BC%81%E6%A5%AD%E7%89%88) ------------------------------------------------------------------------ 對於企業部署,分享功能可以: * 出於安全合規考量**完全停用** * **限制**為僅通過 SSO 身分驗證的使用者可用 * **自行託管**在您自己的基礎架構上 [了解更多](https://opencode.ai/docs/enterprise) 關於在您的組織中使用 OpenCode 的資訊。 --- # 分享 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/share#_top) 分享 == 分享您的 OpenCode 对话。 OpenCode 的分享功能允许您创建指向 OpenCode 对话的公开链接,方便与团队成员协作或向他人寻求帮助。 * * * [工作原理](https://opencode.ai/docs/zh-cn/share#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) ---------------------------------------------------------------------------------- 当您分享一段对话时,OpenCode 会: 1. 为您的会话创建一个唯一的公开 URL 2. 将您的对话历史同步到我们的服务器 3. 通过可分享的链接使对话可访问 — `opncd.ai/s/` * * * [分享模式](https://opencode.ai/docs/zh-cn/share#%E5%88%86%E4%BA%AB%E6%A8%A1%E5%BC%8F) ---------------------------------------------------------------------------------- OpenCode 支持三种分享模式,用于控制对话的共享方式: * * * ### [手动模式(默认)](https://opencode.ai/docs/zh-cn/share#%E6%89%8B%E5%8A%A8%E6%A8%A1%E5%BC%8F%E9%BB%98%E8%AE%A4) 默认情况下,OpenCode 使用手动分享模式。会话不会自动共享,但您可以使用 `/share` 命令手动分享: /share 这将生成一个唯一的 URL 并复制到您的剪贴板。 要在[配置文件](https://opencode.ai/docs/config) 中显式设置手动模式: { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [自动分享](https://opencode.ai/docs/zh-cn/share#%E8%87%AA%E5%8A%A8%E5%88%86%E4%BA%AB) 您可以在[配置文件](https://opencode.ai/docs/config) 中将 `share` 选项设置为 `"auto"`,为所有新对话启用自动分享: { "$schema": "https://opencode.ai/config.json", "share": "auto"} 启用自动分享后,每个新对话都会自动共享并生成链接。 * * * ### [禁用](https://opencode.ai/docs/zh-cn/share#%E7%A6%81%E7%94%A8) 您可以在[配置文件](https://opencode.ai/docs/config) 中将 `share` 选项设置为 `"disabled"`,完全禁用分享功能: { "$schema": "https://opencode.ai/config.json", "share": "disabled"} 要在团队中对特定项目强制执行此设置,请将其添加到项目的 `opencode.json` 文件中并提交到 Git。 * * * [取消分享](https://opencode.ai/docs/zh-cn/share#%E5%8F%96%E6%B6%88%E5%88%86%E4%BA%AB) ---------------------------------------------------------------------------------- 要停止分享对话并将其从公开访问中移除: /unshare 这将移除分享链接并删除与该对话相关的数据。 * * * [隐私](https://opencode.ai/docs/zh-cn/share#%E9%9A%90%E7%A7%81) -------------------------------------------------------------- 分享对话时需要注意以下几点。 * * * ### [数据留存](https://opencode.ai/docs/zh-cn/share#%E6%95%B0%E6%8D%AE%E7%95%99%E5%AD%98) 共享的对话在您明确取消分享之前将一直保持可访问状态。这包括: * 完整的对话历史 * 所有消息和回复 * 会话元数据 * * * ### [建议](https://opencode.ai/docs/zh-cn/share#%E5%BB%BA%E8%AE%AE) * 仅分享不包含敏感信息的对话。 * 分享前请检查对话内容。 * 协作完成后请取消分享。 * 避免分享包含专有代码或机密数据的对话。 * 对于敏感项目,请完全禁用分享功能。 * * * [企业版](https://opencode.ai/docs/zh-cn/share#%E4%BC%81%E4%B8%9A%E7%89%88) ------------------------------------------------------------------------ 对于企业部署,分享功能可以: * 出于安全合规考虑**完全禁用** * **限制**为仅通过 SSO 身份验证的用户可用 * **自托管**在您自己的基础设施上 [了解更多](https://opencode.ai/docs/enterprise) 关于在您的组织中使用 OpenCode 的信息。 --- # Compartir | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/share#_top) Compartir ========= Comparte tus conversaciones OpenCode. La función para compartir de OpenCode te permite crear enlaces públicos a tus conversaciones de OpenCode, para que puedas colaborar con compañeros de equipo u obtener ayuda de otros. * * * [Cómo funciona](https://opencode.ai/docs/es/share#c%C3%B3mo-funciona) ---------------------------------------------------------------------- Cuando compartes una conversación, OpenCode: 1. Crea una URL pública única para su sesión. 2. Sincroniza tu historial de conversaciones con nuestros servidores 3. Hace que la conversación sea accesible a través del enlace para compartir: `opncd.ai/s/` * * * [Uso compartido](https://opencode.ai/docs/es/share#uso-compartido) ------------------------------------------------------------------- OpenCode admite tres modos de compartir que controlan cómo se comparten las conversaciones: * * * ### [Manual (predeterminado)](https://opencode.ai/docs/es/share#manual-predeterminado) De forma predeterminada, OpenCode usa el modo de compartir manual. Las sesiones no se comparten automáticamente, pero puedes compartirlas manualmente usando el comando `/share`: /share Esto generará una URL única que se copiará en su portapapeles. Para configurar explícitamente el modo manual en su [archivo de configuración](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Compartir automáticamente](https://opencode.ai/docs/es/share#compartir-autom%C3%A1ticamente) Puede habilitar el uso compartido automático para todas las conversaciones nuevas configurando la opción `share` en `"auto"` en su [archivo de configuración](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} Con el uso compartido automático habilitado, cada nueva conversación se compartirá automáticamente y se generará un enlace. * * * ### [Desactivado](https://opencode.ai/docs/es/share#desactivado) Puede desactivar el uso compartido por completo configurando la opción `share` en `"disabled"` en su [archivo de configuración](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Para aplicar esto en todo su equipo para un proyecto determinado, agréguelo al `opencode.json` en su proyecto y regístrelo en Git. * * * [Dejar de compartir](https://opencode.ai/docs/es/share#dejar-de-compartir) --------------------------------------------------------------------------- Para dejar de compartir una conversación y eliminarla del acceso público: /unshare Esto eliminará el enlace para compartir y eliminará los datos relacionados con la conversación. * * * [Privacidad](https://opencode.ai/docs/es/share#privacidad) ----------------------------------------------------------- Hay algunas cosas a tener en cuenta al compartir una conversación. * * * ### [Retención de datos](https://opencode.ai/docs/es/share#retenci%C3%B3n-de-datos) Las conversaciones compartidas permanecen accesibles hasta que las dejes de compartir explícitamente. Este incluye: * Historial de conversaciones completo * Todos los mensajes y respuestas. * Metadatos de la sesión * * * ### [Recomendaciones](https://opencode.ai/docs/es/share#recomendaciones) * Comparta únicamente conversaciones que no contengan información confidencial. * Revisar el contenido de la conversación antes de compartir. * Dejar de compartir conversaciones cuando se complete la colaboración. * Evite compartir conversaciones con código propietario o datos confidenciales. * Para proyectos confidenciales, deshabilite el uso compartido por completo. * * * [Para empresas](https://opencode.ai/docs/es/share#para-empresas) ----------------------------------------------------------------- Para implementaciones empresariales, la función de compartir puede ser: * **Desactivado** completamente por motivos de seguridad. * **Restringido** solo a usuarios autenticados a través de SSO * **Autohospedado** en tu propia infraestructura [Obtenga más información](https://opencode.ai/docs/enterprise) sobre el uso de opencode en su organización. --- # Deling | OpenCode [Gå til indhold](https://opencode.ai/docs/da/share#_top) Deling ====== Del dine OpenCode-samtaler. OpenCodes delingsfunksjon lar deg lage offentlige lenker til dine OpenCode-samtaler, slik at du kan samarbeide med lagkamerater eller få hjelp fra andre. * * * [Sådan fungerer det](https://opencode.ai/docs/da/share#s%C3%A5dan-fungerer-det) -------------------------------------------------------------------------------- Når du deler en samtale, OpenCode: 1. Opreter en unik offentlig URL for sessionen din 2. Synkroniserer samtaleloggen din til serverne våre 3. Gør samtalen tilgængelig via den delbare lenken — `opncd.ai/s/` * * * [Tilstande](https://opencode.ai/docs/da/share#tilstande) --------------------------------------------------------- OpenCode støtter tre delingsmoduser som kontrollerer hvordan samtaler deles: * * * ### [Manuel (standard)](https://opencode.ai/docs/da/share#manuel-standard) Som standard bruger OpenCode manuell delingsmodus. Sessioner deles ikke automatisk, men du kan dele dem manuelt ved at bruge kommandoen `/share`: /share Dette vil generere en unik URL som vil bli kopiert til utklippstavlen din. For at eksplisitt angi manuell modus i [konfigurasjonsfilen](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Automatisk deling](https://opencode.ai/docs/da/share#automatisk-deling) Du kan aktivere automatisk deling for alle nye samtaler ved at sette alternativet `share` til `"auto"` i [konfigurasjonsfilen](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} Med automatisk deling aktivert, vil hver nye samtale automatisk bli delt og en kobling vil bli generert. * * * ### [Deaktiveret](https://opencode.ai/docs/da/share#deaktiveret) Du kan deaktivere deling helt ved at sette alternativet `share` til `"disabled"` i [konfigurasjonsfilen](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} For at håndheve dette på tvers av teamet ditt for et gitt prosjekt, tilføj det til `opencode.json` i prosjektet ditt og tjek inn i Git. * * * [Ophæv deling](https://opencode.ai/docs/da/share#oph%C3%A6v-deling) -------------------------------------------------------------------- Slik slutter du at dele en samtale og fjerner den fra offentlig tilgang: /unshare Dette vil fjerne delelinken og slette dataene knyttet til samtalen. * * * [Privatliv](https://opencode.ai/docs/da/share#privatliv) --------------------------------------------------------- Det er et par ting du må huske på når du deler en samtale. * * * ### [Datalagring](https://opencode.ai/docs/da/share#datalagring) Delte samtaler forblir tilgængelige til du eksplisitt opphever deling av dem. Dette inkluderer: * Full samtalehistorikk * Alle meldinger og svar * Metadata for sessioner * * * ### [Anbefalinger](https://opencode.ai/docs/da/share#anbefalinger) * Del kun samtaler som ikke inneholder sensitiv informasjon. * Se gjennom samtaleinnholdet før du deler. * Opphev deling av samtaler når samarbeidet er fullført. * Unngå at dele samtaler med proprietær kode eller konfidensielle data. * For sensitive prosjekter, deaktiver deling helt. * * * [For virksomheder](https://opencode.ai/docs/da/share#for-virksomheder) ----------------------------------------------------------------------- For bedriftsimplementeringer kan delingsfunksjonen være: * **Deaktivert** helt for overholdelse av sikkerhet * **Begrenset** til brugere som kun er autentisert gjennom SSO * **Selvvert** på din egen infrastruktur [Finn ut mer](https://opencode.ai/docs/enterprise) om brug av opencode i organisasjonen din. --- # Partager | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/share#_top) Partager ======== Partagez vos conversations OpenCode. La fonctionnalité de partage de OpenCode vous permet de créer des liens publics vers vos conversations OpenCode, afin que vous puissiez collaborer avec vos coéquipiers ou obtenir de l’aide d’autres personnes. * * * [Comment ça marche](https://opencode.ai/docs/fr/share#comment-%C3%A7a-marche) ------------------------------------------------------------------------------ Lorsque vous partagez une conversation, OpenCode : 1. Crée un URL public unique pour votre session 2. Synchronise l’historique de vos conversations avec nos serveurs 3. Rend la conversation accessible via le lien partageable — `opncd.ai/s/` * * * [Partage](https://opencode.ai/docs/fr/share#partage) ----------------------------------------------------- OpenCode prend en charge trois modes de partage qui contrôlent la manière dont les conversations sont partagées : * * * ### [Manuel (par défaut)](https://opencode.ai/docs/fr/share#manuel-par-d%C3%A9faut) Par défaut, OpenCode utilise le mode de partage manuel. Les sessions ne sont pas partagées automatiquement, mais vous pouvez les partager manuellement à l’aide de la commande `/share` : /share Cela générera un URL unique qui sera copié dans votre presse-papiers. Pour définir explicitement le mode manuel dans votre [fichier de configuration](https://opencode.ai/docs/config)  : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Partage automatique](https://opencode.ai/docs/fr/share#partage-automatique) Vous pouvez activer le partage automatique pour toutes les nouvelles conversations en définissant l’option `share` sur `"auto"` dans votre [fichier de configuration](https://opencode.ai/docs/config)  : { "$schema": "https://opencode.ai/config.json", "share": "auto"} Avec le partage automatique activé, chaque nouvelle conversation sera automatiquement partagée et un lien sera généré. * * * ### [Désactivé](https://opencode.ai/docs/fr/share#d%C3%A9sactiv%C3%A9) Vous pouvez désactiver entièrement le partage en définissant l’option `share` sur `"disabled"` dans votre [fichier de configuration](https://opencode.ai/docs/config)  : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Pour appliquer cela au sein de votre équipe pour un projet donné, ajoutez-le au `opencode.json` dans votre projet et enregistrez-vous dans Git. * * * [Annuler le partage](https://opencode.ai/docs/fr/share#annuler-le-partage) --------------------------------------------------------------------------- Pour arrêter de partager une conversation et la supprimer de l’accès public : /unshare Cela supprimera le lien de partage et supprimera les données liées à la conversation. * * * [Confidentialité](https://opencode.ai/docs/fr/share#confidentialit%C3%A9) -------------------------------------------------------------------------- Il y a quelques points à garder à l’esprit lorsque vous partagez une conversation. * * * ### [Conservation des données](https://opencode.ai/docs/fr/share#conservation-des-donn%C3%A9es) Les conversations partagées restent accessibles jusqu’à ce que vous les annuliez explicitement. Ce comprend : * Historique complet des conversations * Tous les messages et réponses * Métadonnées de session * * * ### [Recommandations](https://opencode.ai/docs/fr/share#recommandations) * Partagez uniquement les conversations qui ne contiennent pas d’informations sensibles. * Examinez le contenu de la conversation avant de la partager. * Annulez le partage des conversations une fois la collaboration terminée. * Évitez de partager des conversations avec du code propriétaire ou des données confidentielles. * Pour les projets sensibles, désactivez complètement le partage. * * * [Pour les entreprises](https://opencode.ai/docs/fr/share#pour-les-entreprises) ------------------------------------------------------------------------------- Pour les déploiements en entreprise, la fonctionnalité de partage peut être : * **Désactivé** entièrement pour des raisons de conformité en matière de sécurité * **Réservé** aux utilisateurs authentifiés via SSO uniquement * **Auto-hébergé** sur votre propre infrastructure [En savoir plus](https://opencode.ai/docs/enterprise) sur l’utilisation de opencode dans votre organisation. --- # Teilen | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/share#_top) Teilen ====== Teile OpenCode-Unterhaltungen per oeffentlichem Link. Mit der Share-Funktion erstellst du oeffentliche Links zu OpenCode-Unterhaltungen. So kannst du einfacher mit dem Team zusammenarbeiten oder Hilfe einholen. * * * [Funktionsweise](https://opencode.ai/docs/de/share#funktionsweise) ------------------------------------------------------------------- Wenn du eine Unterhaltung teilst, macht OpenCode Folgendes: 1. Erstellt eine eindeutige oeffentliche URL fuer deine Sitzung 2. Synchronisiert den Verlauf auf unsere Server 3. Stellt die Unterhaltung unter `opncd.ai/s/` bereit * * * [Teilen](https://opencode.ai/docs/de/share#teilen) --------------------------------------------------- OpenCode hat drei Modi, die das Teilen steuern: * * * ### [Manuell (Standard)](https://opencode.ai/docs/de/share#manuell-standard) Standardmaessig nutzt OpenCode den manuellen Modus. Sitzungen werden nicht automatisch geteilt, du kannst sie aber mit `/share` veroeffentlichen: /share Dabei wird eine eindeutige URL erzeugt und in die Zwischenablage kopiert. Um den manuellen Modus explizit in der [Konfiguration](https://opencode.ai/docs/config) zu setzen: { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Auto-Share](https://opencode.ai/docs/de/share#auto-share) Du kannst automatisches Teilen fuer neue Unterhaltungen aktivieren, indem du in der [Konfiguration](https://opencode.ai/docs/config) `share` auf `"auto"` setzt: { "$schema": "https://opencode.ai/config.json", "share": "auto"} Mit aktiviertem Auto-Share wird jede neue Unterhaltung automatisch geteilt und ein Link erstellt. * * * ### [Deaktiviert](https://opencode.ai/docs/de/share#deaktiviert) Du kannst Teilen komplett deaktivieren, indem du in der [Konfiguration](https://opencode.ai/docs/config) `share` auf `"disabled"` setzt: { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Wenn das fuer ein Projekt teamweit gelten soll, lege es in der Projekt-`opencode.json` fest und committe die Datei. * * * [Teilen aufheben](https://opencode.ai/docs/de/share#teilen-aufheben) --------------------------------------------------------------------- Um das Teilen zu beenden und den oeffentlichen Zugriff zu entfernen: /unshare Dadurch wird der Share-Link entfernt und die zugehoerigen Daten werden geloescht. * * * [Datenschutz](https://opencode.ai/docs/de/share#datenschutz) ------------------------------------------------------------- Beim Teilen solltest du ein paar Punkte beachten. * * * ### [Datenaufbewahrung](https://opencode.ai/docs/de/share#datenaufbewahrung) Geteilte Unterhaltungen bleiben veroeffentlicht, bis du sie explizit aufhebst. Das umfasst: * Vollstaendigen Unterhaltungsverlauf * Alle Nachrichten und Antworten * Sitzungsmetadaten * * * ### [Empfehlungen](https://opencode.ai/docs/de/share#empfehlungen) * Teile nur Unterhaltungen ohne sensible Informationen. * Pruefe Inhalte vor dem Teilen. * Hebe das Teilen wieder auf, wenn die Zusammenarbeit beendet ist. * Teile keine proprietaeren Codes oder vertraulichen Daten. * Deaktiviere Teilen komplett bei sensiblen Projekten. * * * [Für Unternehmen](https://opencode.ai/docs/de/share#f%C3%BCr-unternehmen) -------------------------------------------------------------------------- In Enterprise-Umgebungen kann die Share-Funktion: * **Deaktiviert** werden, um Compliance-Vorgaben einzuhalten * Auf **SSO-authentifizierte** Nutzer eingeschraenkt werden * **Self-hosted** auf eigener Infrastruktur betrieben werden [Mehr dazu](https://opencode.ai/docs/enterprise) , wie du opencode in deiner Organisation einsetzt. --- # Compartilhar | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/share#_top) Compartilhar ============ Compartilhe suas conversas do opencode. O recurso de compartilhamento do opencode permite que você crie links públicos para suas conversas do opencode, para que você possa colaborar com colegas de equipe ou obter ajuda de outros. * * * [Como funciona](https://opencode.ai/docs/pt-br/share#como-funciona) -------------------------------------------------------------------- Quando você compartilha uma conversa, o opencode: 1. Cria uma URL pública única para sua sessão 2. Sincroniza seu histórico de conversas com nossos servidores 3. Torna a conversa acessível através do link compartilhável — `opncd.ai/s/` * * * [Compartilhamento](https://opencode.ai/docs/pt-br/share#compartilhamento) -------------------------------------------------------------------------- O opencode suporta três modos de compartilhamento que controlam como as conversas são compartilhadas: * * * ### [Manual (padrão)](https://opencode.ai/docs/pt-br/share#manual-padr%C3%A3o) Por padrão, o opencode usa o modo de compartilhamento manual. As sessões não são compartilhadas automaticamente, mas você pode compartilhá-las manualmente usando o comando `/share`: /share Isso gerará uma URL única que será copiada para sua área de transferência. Para definir explicitamente o modo manual em seu [arquivo de configuração](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Compartilhamento automático](https://opencode.ai/docs/pt-br/share#compartilhamento-autom%C3%A1tico) Você pode habilitar o compartilhamento automático para todas as novas conversas definindo a opção `share` como `"auto"` em seu [arquivo de configuração](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} Com o compartilhamento automático habilitado, cada nova conversa será compartilhada automaticamente e um link será gerado. * * * ### [Desativado](https://opencode.ai/docs/pt-br/share#desativado) Você pode desativar o compartilhamento completamente definindo a opção `share` como `"disabled"` em seu [arquivo de configuração](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Para impor isso em sua equipe para um determinado projeto, adicione-o ao `opencode.json` em seu projeto e faça o check-in no Git. * * * [Cancelar compartilhamento](https://opencode.ai/docs/pt-br/share#cancelar-compartilhamento) -------------------------------------------------------------------------------------------- Para parar de compartilhar uma conversa e removê-la do acesso público: /unshare Isso removerá o link de compartilhamento e excluirá os dados relacionados à conversa. * * * [Privacidade](https://opencode.ai/docs/pt-br/share#privacidade) ---------------------------------------------------------------- Há algumas coisas a serem lembradas ao compartilhar uma conversa. * * * ### [Retenção de dados](https://opencode.ai/docs/pt-br/share#reten%C3%A7%C3%A3o-de-dados) Conversas compartilhadas permanecem acessíveis até que você as descompartilhe explicitamente. Isso inclui: * Histórico completo da conversa * Todas as mensagens e respostas * Metadados da sessão * * * ### [Recomendações](https://opencode.ai/docs/pt-br/share#recomenda%C3%A7%C3%B5es) * Compartilhe apenas conversas que não contenham informações sensíveis. * Revise o conteúdo da conversa antes de compartilhar. * Descompartilhe conversas quando a colaboração estiver completa. * Evite compartilhar conversas com código proprietário ou dados confidenciais. * Para projetos sensíveis, desative o compartilhamento completamente. * * * [Para empresas](https://opencode.ai/docs/pt-br/share#para-empresas) -------------------------------------------------------------------- Para implantações empresariais, o recurso de compartilhamento pode ser: * **Desativado** completamente para conformidade de segurança * **Restrito** a usuários autenticados apenas através de SSO * **Auto-hospedado** em sua própria infraestrutura [Saiba mais](https://opencode.ai/docs/enterprise) sobre como usar o opencode em sua organização. --- # 共有 | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/share#_top) 共有 == OpenCode での会話を共有します。 OpenCode の共有機能を使用すると、OpenCode の会話への公開リンクを作成できるため、チームメイトと共同作業したり、他の人から助けを得ることができます。 * * * [仕組み](https://opencode.ai/docs/ja/share#%E4%BB%95%E7%B5%84%E3%81%BF) --------------------------------------------------------------------- 会話を共有するとき、OpenCode は次のことを行います。 1. セッション用の一意のパブリック URL を作成します 2. 会話履歴をサーバーに同期します 3. 共有可能なリンク — `opncd.ai/s/` を介して会話にアクセスできるようにします * * * [共有](https://opencode.ai/docs/ja/share#%E5%85%B1%E6%9C%89) ----------------------------------------------------------- OpenCode は、会話の共有方法を制御する 3 つの共有モードをサポートしています。 * * * ### [手動(デフォルト)](https://opencode.ai/docs/ja/share#%E6%89%8B%E5%8B%95%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88) デフォルトでは、OpenCode は手動共有モードを使用します。セッションは自動的には共有されませんが、`/share` コマンドを使用して手動で共有できます。 /share これにより、クリップボードにコピーされる一意の URL が生成されます。 [設定ファイル](https://opencode.ai/docs/config) : で手動モードを明示的に設定するには: { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [自動共有](https://opencode.ai/docs/ja/share#%E8%87%AA%E5%8B%95%E5%85%B1%E6%9C%89) [設定ファイル](https://opencode.ai/docs/config) : で `share` オプションを `"auto"` に設定することで、すべての新しい会話の自動共有を有効にできます。 { "$schema": "https://opencode.ai/config.json", "share": "auto"} 自動共有を有効にすると、すべての新しい会話が自動的に共有され、リンクが生成されます。 * * * ### [無効](https://opencode.ai/docs/ja/share#%E7%84%A1%E5%8A%B9) [設定ファイル](https://opencode.ai/docs/config) : で `share` オプションを `"disabled"` に設定することで、共有を完全に無効にすることができます。 { "$schema": "https://opencode.ai/config.json", "share": "disabled"} これを特定のプロジェクトのチーム全体に強制するには、それをプロジェクトの `opencode.json` に追加し、Git にチェックインします。 * * * [共有の解除](https://opencode.ai/docs/ja/share#%E5%85%B1%E6%9C%89%E3%81%AE%E8%A7%A3%E9%99%A4) ----------------------------------------------------------------------------------------- 会話の共有を停止し、パブリックアクセスから削除するには: /unshare これにより、共有リンクが削除され、会話に関連するデータが削除されます。 * * * [プライバシー](https://opencode.ai/docs/ja/share#%E3%83%97%E3%83%A9%E3%82%A4%E3%83%90%E3%82%B7%E3%83%BC) --------------------------------------------------------------------------------------------------- 会話を共有する際には、留意すべき点がいくつかあります。 * * * ### [データの保持](https://opencode.ai/docs/ja/share#%E3%83%87%E3%83%BC%E3%82%BF%E3%81%AE%E4%BF%9D%E6%8C%81) 共有された会話は、明示的に共有を解除するまでアクセス可能なままになります。これ 以下が含まれます: * 完全な会話履歴 * すべてのメッセージと応答 * セッションメタデータ * * * ### [推奨事項](https://opencode.ai/docs/ja/share#%E6%8E%A8%E5%A5%A8%E4%BA%8B%E9%A0%85) * 機密情報を含まない会話のみを共有してください。 * 共有する前に会話の内容を確認してください。 * コラボレーションが完了したら、会話の共有を解除します。 * 独自のコードや機密データを含む会話を共有することは避けてください。 * 機密性の高いプロジェクトの場合は、共有を完全に無効にします。 * * * [企業向け](https://opencode.ai/docs/ja/share#%E4%BC%81%E6%A5%AD%E5%90%91%E3%81%91) ------------------------------------------------------------------------------- エンタープライズ展開の場合、共有機能は次のようになります。 * **セキュリティコンプライアンスのため完全に無効** * **SSO を通じて認証されたユーザーのみに制限** * 独自のインフラストラクチャで **セルフホスト** [組織内での OpenCode の使用について詳しくは、](https://opencode.ai/docs/enterprise) をご覧ください。 --- # المشاركة | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/share#_top) المشاركة ======== شارك محادثات OpenCode الخاصة بك. تتيح لك ميزة المشاركة في OpenCode إنشاء روابط عامة لمحادثات OpenCode الخاصة بك، بحيث يمكنك التعاون مع زملائك أو الحصول على المساعدة من الآخرين. * * * [كيف تعمل](https://opencode.ai/docs/ar/share#%D9%83%D9%8A%D9%81-%D8%AA%D8%B9%D9%85%D9%84) ------------------------------------------------------------------------------------------ عند مشاركة محادثة، يقوم OpenCode بما يلي: 1. ينشئ عنوان URL عاما فريدا لجلستك 2. يزامن سجل محادثتك مع خوادمنا 3. يجعل المحادثة متاحة عبر رابط قابل للمشاركة — `opncd.ai/s/` * * * [المشاركة](https://opencode.ai/docs/ar/share#%D8%A7%D9%84%D9%85%D8%B4%D8%A7%D8%B1%D9%83%D8%A9) ----------------------------------------------------------------------------------------------- يدعم OpenCode ثلاثة أوضاع للمشاركة تتحكم في كيفية مشاركة المحادثات: * * * ### [يدوي (افتراضي)](https://opencode.ai/docs/ar/share#%D9%8A%D8%AF%D9%88%D9%8A-%D8%A7%D9%81%D8%AA%D8%B1%D8%A7%D8%B6%D9%8A) افتراضيا، يستخدم OpenCode وضع المشاركة اليدوي. لا تتم مشاركة الجلسات تلقائيا، لكن يمكنك مشاركتها يدويا باستخدام الأمر `/share`: /share سيُنشئ هذا عنوان URL فريدا وسيُنسخ إلى الحافظة. لضبط الوضع اليدوي صراحة في [ملف الإعدادات](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [المشاركة التلقائية](https://opencode.ai/docs/ar/share#%D8%A7%D9%84%D9%85%D8%B4%D8%A7%D8%B1%D9%83%D8%A9-%D8%A7%D9%84%D8%AA%D9%84%D9%82%D8%A7%D8%A6%D9%8A%D8%A9) يمكنك تفعيل المشاركة التلقائية لجميع المحادثات الجديدة عبر ضبط خيار `share` إلى `"auto"` في [ملف الإعدادات](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} عند تفعيل المشاركة التلقائية، ستتم مشاركة كل محادثة جديدة تلقائيا وسيتم إنشاء رابط لها. * * * ### [معطلة](https://opencode.ai/docs/ar/share#%D9%85%D8%B9%D8%B7%D9%84%D8%A9) يمكنك تعطيل المشاركة بالكامل عبر ضبط خيار `share` إلى `"disabled"` في [ملف الإعدادات](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} لفرض ذلك على مستوى فريقك لمشروع معين، أضفه إلى ملف `opencode.json` في مشروعك ثم قم بإدراجه في Git. * * * [إلغاء المشاركة](https://opencode.ai/docs/ar/share#%D8%A5%D9%84%D8%BA%D8%A7%D8%A1-%D8%A7%D9%84%D9%85%D8%B4%D8%A7%D8%B1%D9%83%D8%A9) ------------------------------------------------------------------------------------------------------------------------------------ لإيقاف مشاركة محادثة وإزالتها من الوصول العام: /unshare سيؤدي ذلك إلى إزالة رابط المشاركة وحذف البيانات المتعلقة بالمحادثة. * * * [الخصوصية](https://opencode.ai/docs/ar/share#%D8%A7%D9%84%D8%AE%D8%B5%D9%88%D8%B5%D9%8A%D8%A9) ----------------------------------------------------------------------------------------------- هناك بعض الأمور التي ينبغي وضعها في الاعتبار عند مشاركة محادثة. * * * ### [الاحتفاظ بالبيانات](https://opencode.ai/docs/ar/share#%D8%A7%D9%84%D8%A7%D8%AD%D8%AA%D9%81%D8%A7%D8%B8-%D8%A8%D8%A7%D9%84%D8%A8%D9%8A%D8%A7%D9%86%D8%A7%D8%AA) تظل المحادثات المشتركة متاحة حتى تقوم بإلغاء مشاركتها صراحة. يشمل ذلك: * سجل المحادثة كاملا * جميع الرسائل والردود * بيانات تعريف الجلسة * * * ### [توصيات](https://opencode.ai/docs/ar/share#%D8%AA%D9%88%D8%B5%D9%8A%D8%A7%D8%AA) * شارك فقط المحادثات التي لا تتضمن معلومات حساسة. * راجع محتوى المحادثة قبل مشاركتها. * ألغِ مشاركة المحادثات عند اكتمال التعاون. * تجنب مشاركة المحادثات التي تتضمن شيفرة مملوكة أو بيانات سرية. * للمشاريع الحساسة، عطّل المشاركة بالكامل. * * * [للمؤسسات](https://opencode.ai/docs/ar/share#%D9%84%D9%84%D9%85%D8%A4%D8%B3%D8%B3%D8%A7%D8%AA) ----------------------------------------------------------------------------------------------- في عمليات النشر الخاصة بالمؤسسات، يمكن أن تكون ميزة المشاركة: * **معطلة** بالكامل للامتثال الأمني * **مقيدة** على المستخدمين الموثقين عبر SSO فقط * **مستضافة ذاتيا** على بنيتك التحتية الخاصة [تعرّف على المزيد](https://opencode.ai/docs/enterprise) حول استخدام OpenCode في مؤسستك. --- # Deling | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/share#_top) Deling ====== Del dine OpenCode-samtaler. Delingsfunksjonen i OpenCode lar deg lage offentlige lenker til dine OpenCode-samtaler, slik at du kan samarbeide med lagkamerater eller få hjelp fra andre. * * * [Slik fungerer det](https://opencode.ai/docs/nb/share#slik-fungerer-det) ------------------------------------------------------------------------- Når du deler en samtale, OpenCode: 1. Oppretter en unik offentlig URL for økten din 2. Synkroniserer samtaleloggen din til serverne våre 3. Gjør samtalen tilgjengelig via den delbare lenken — `opncd.ai/s/` * * * [Deling](https://opencode.ai/docs/nb/share#deling) --------------------------------------------------- OpenCode støtter tre delingsmoduser som kontrollerer hvordan samtaler deles: * * * ### [Manuell (standard)](https://opencode.ai/docs/nb/share#manuell-standard) Som standard bruker OpenCode manuell delingsmodus. Økter deles ikke automatisk, men du kan dele dem manuelt ved å bruke kommandoen `/share`: /share Dette vil generere en unik URL som vil bli kopiert til utklippstavlen din. For å eksplisitt angi manuell modus i [konfigurasjonsfilen](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Automatisk deling](https://opencode.ai/docs/nb/share#automatisk-deling) Du kan aktivere automatisk deling for alle nye samtaler ved å sette alternativet `share` til `"auto"` i [konfigurasjonsfilen](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} Med automatisk deling aktivert, vil hver nye samtale automatisk bli delt og en kobling vil bli generert. * * * ### [Deaktivert](https://opencode.ai/docs/nb/share#deaktivert) Du kan deaktivere deling helt ved å sette alternativet `share` til `"disabled"` i [konfigurasjonsfilen](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} For å håndheve dette på tvers av teamet ditt for et gitt prosjekt, legg det til `opencode.json` i prosjektet ditt og sjekk det inn i Git. * * * [Opphev deling](https://opencode.ai/docs/nb/share#opphev-deling) ----------------------------------------------------------------- Slik slutter du å dele en samtale og fjerner den fra offentlig tilgang: /unshare Dette vil fjerne delelinken og slette dataene knyttet til samtalen. * * * [Personvern](https://opencode.ai/docs/nb/share#personvern) ----------------------------------------------------------- Det er et par ting du må huske på når du deler en samtale. * * * ### [Datalagring](https://opencode.ai/docs/nb/share#datalagring) Delte samtaler forblir tilgjengelige til du eksplisitt opphever deling av dem. Dette inkluderer: * Full samtalehistorikk * Alle meldinger og svar * Metadata for økter * * * ### [Anbefalinger](https://opencode.ai/docs/nb/share#anbefalinger) * Del kun samtaler som ikke inneholder sensitiv informasjon. * Se gjennom samtaleinnholdet før du deler. * Opphev deling av samtaler når samarbeidet er fullført. * Unngå å dele samtaler med proprietær kode eller konfidensielle data. * For sensitive prosjekter, deaktiver deling helt. * * * [For bedrifter](https://opencode.ai/docs/nb/share#for-bedrifter) ----------------------------------------------------------------- For bedriftsimplementeringer kan delingsfunksjonen være: * **Deaktivert** helt for overholdelse av sikkerhet * **Begrenset** til brukere som kun er autentisert gjennom SSO * **Selv-hostet** på din egen infrastruktur [Finn ut mer](https://opencode.ai/docs/enterprise) om bruk av opencode i organisasjonen din. --- # Configurazione | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/config#_top) Configurazione ============== Usa la configurazione JSON di OpenCode. Puoi configurare OpenCode usando un file di configurazione JSON. * * * [Formato](https://opencode.ai/docs/it/config#formato) ------------------------------------------------------ OpenCode supporta sia **JSON** sia **JSONC** (JSON con commenti). { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [Posizioni](https://opencode.ai/docs/it/config#posizioni) ---------------------------------------------------------- Puoi mettere la configurazione in diverse posizioni e ognuna ha un ordine di precedenza diverso. I file di configurazione vengono uniti (merge), non sostituiti. Le impostazioni provenienti dalle posizioni qui sotto vengono combinate. Le configurazioni caricate dopo sovrascrivono quelle precedenti solo per le chiavi in conflitto. Le impostazioni non in conflitto vengono preservate. Per esempio, se la tua configurazione globale imposta `autoupdate: true` e la configurazione del progetto imposta `model: "anthropic/claude-sonnet-4-5"`, la configurazione finale includera entrambe le impostazioni. * * * ### [Ordine di precedenza](https://opencode.ai/docs/it/config#ordine-di-precedenza) Le sorgenti di configurazione vengono caricate in questo ordine (le successive sovrascrivono le precedenti): 1. **Config remota** (da `.well-known/opencode`) - default dell’organizzazione 2. **Config globale** (`~/.config/opencode/opencode.json`) - preferenze utente 3. **Config personalizzata** (variabile d’ambiente `OPENCODE_CONFIG`) - sovrascritture personalizzate 4. **Config di progetto** (`opencode.json` nel progetto) - impostazioni specifiche del progetto 5. **Directory `.opencode`** - agenti, comandi, plugin 6. **Config inline** (variabile d’ambiente `OPENCODE_CONFIG_CONTENT`) - sovrascritture a runtime Questo significa che la configurazione di progetto puo sovrascrivere i default globali, e la configurazione globale puo sovrascrivere i default remoti dell’organizzazione. * * * ### [Configurazione remota](https://opencode.ai/docs/it/config#configurazione-remota) Le organizzazioni possono fornire una configurazione predefinita tramite l’endpoint `.well-known/opencode`. Viene recuperata automaticamente quando ti autentichi con un provider che lo supporta. La configurazione remota viene caricata per prima e fa da livello base. Tutte le altre sorgenti (globale, progetto) possono sovrascrivere questi default. Per esempio, se la tua organizzazione fornisce server MCP disabilitati per impostazione predefinita: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Puoi abilitare server specifici nella tua configurazione locale: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Configurazione globale](https://opencode.ai/docs/it/config#configurazione-globale) Metti la configurazione globale di OpenCode in `~/.config/opencode/opencode.json`. Usa la configurazione globale per preferenze server/runtime valide per l’utente come provider, modelli e permessi. Per le impostazioni specifiche della TUI, usa `~/.config/opencode/tui.json`. La configurazione globale sovrascrive i default remoti dell’organizzazione. * * * ### [Configurazione di progetto](https://opencode.ai/docs/it/config#configurazione-di-progetto) Aggiungi `opencode.json` nella root del progetto. La configurazione di progetto ha la precedenza piu alta tra i file standard: sovrascrive sia la configurazione globale sia quella remota. Per le impostazioni TUI specifiche del progetto, aggiungi `tui.json` nella stessa posizione. Quando OpenCode si avvia, cerca un file di configurazione nella directory corrente oppure risale fino alla directory Git piu vicina. Questo file puo essere tranquillamente versionato in Git e usa lo stesso schema di quello globale. * * * ### [Percorso personalizzato](https://opencode.ai/docs/it/config#percorso-personalizzato) Specifica un percorso personalizzato per il file di configurazione usando la variabile d’ambiente `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" La configurazione personalizzata viene caricata tra quella globale e quella di progetto nell’ordine di precedenza. * * * ### [Directory personalizzata](https://opencode.ai/docs/it/config#directory-personalizzata) Specifica una directory di configurazione personalizzata usando la variabile d’ambiente `OPENCODE_CONFIG_DIR`. Questa directory verra usata per cercare agenti, comandi, modalita e plugin proprio come la directory standard `.opencode` e dovrebbe seguire la stessa struttura. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" La directory personalizzata viene caricata dopo la configurazione globale e le directory `.opencode`, quindi **puo sovrascrivere** le loro impostazioni. * * * [Schema](https://opencode.ai/docs/it/config#schema) ---------------------------------------------------- Il file di configurazione ha uno schema definito in [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . La configurazione TUI usa [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) . Il tuo editor dovrebbe poter validare e suggerire l’autocompletamento in base allo schema. * * * ### [TUI](https://opencode.ai/docs/it/config#tui) Usa un file dedicato `tui.json` (o `tui.jsonc`) per le impostazioni specifiche della TUI. { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Usa `OPENCODE_TUI_CONFIG` per puntare a un file di configurazione TUI personalizzato. Le chiavi legacy `theme`, `keybinds` e `tui` in `opencode.json` sono deprecate e vengono migrate automaticamente quando possibile. [Scopri di piu sulla configurazione TUI](https://opencode.ai/docs/tui#configure) . * * * ### [Server](https://opencode.ai/docs/it/config#server) Puoi configurare le impostazioni del server per i comandi `opencode serve` e `opencode web` tramite l’opzione `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Opzioni disponibili: * `port` - Porta su cui ascoltare. * `hostname` - Nome host su cui ascoltare. Quando `mdns` e abilitato e non e impostato alcun hostname, il default e `0.0.0.0`. * `mdns` - Abilita la scoperta del servizio mDNS. Questo permette ad altri dispositivi sulla rete di scoprire il tuo server OpenCode. * `mdnsDomain` - Nome di dominio personalizzato per il servizio mDNS. Predefinito: `opencode.local`. Utile per eseguire piu istanze sulla stessa rete. * `cors` - Origini aggiuntive da consentire per CORS quando usi il server HTTP da un client basato su browser. I valori devono essere origini complete (schema + host + porta opzionale), ad es. `https://app.example.com`. [Scopri di piu sul server](https://opencode.ai/docs/server) . * * * ### [Strumenti](https://opencode.ai/docs/it/config#strumenti) Puoi gestire gli strumenti che un LLM puo usare tramite l’opzione `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Scopri di piu sugli strumenti](https://opencode.ai/docs/tools) . * * * ### [Modelli](https://opencode.ai/docs/it/config#modelli) Puoi configurare provider e modelli da usare in OpenCode tramite le opzioni `provider`, `model` e `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} L’opzione `small_model` configura un modello separato per task leggeri come la generazione dei titoli. Per impostazione predefinita, OpenCode prova a usare un modello più economico se disponibile dal tuo provider, altrimenti fa fallback sul tuo modello principale. Le opzioni del provider possono includere `timeout` e `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Timeout della richiesta in millisecondi (predefinito: 300000). Imposta a `false` per disabilitare. * `setCacheKey` - Assicura che venga sempre impostata una cache key per il provider indicato. Puoi anche configurare i [modelli locali](https://opencode.ai/docs/models#local) . [Scopri di piu](https://opencode.ai/docs/models) . * * * #### [Opzioni specifiche del provider](https://opencode.ai/docs/it/config#opzioni-specifiche-del-provider) Alcuni provider supportano opzioni di configurazione aggiuntive oltre alle impostazioni generiche `timeout` e `apiKey`. ##### [Amazon Bedrock](https://opencode.ai/docs/it/config#amazon-bedrock) Amazon Bedrock supporta una configurazione specifica per AWS: { "$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` - Regione AWS per Bedrock (default: variabile d’ambiente `AWS_REGION` oppure `us-east-1`) * `profile` - Profilo AWS nominato da `~/.aws/credentials` (default: variabile d’ambiente `AWS_PROFILE`) * `endpoint` - URL endpoint personalizzato per gli endpoint VPC. E un alias dell’opzione generica `baseURL` usando la terminologia AWS. Se sono specificati sia `endpoint` sia `baseURL`, `endpoint` ha precedenza. [Scopri di piu sulla configurazione di Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Temi](https://opencode.ai/docs/it/config#temi) Imposta il tuo tema UI in `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [Scopri di piu](https://opencode.ai/docs/themes) . * * * ### [Agenti](https://opencode.ai/docs/it/config#agenti) Puoi configurare agenti specializzati per task specifici tramite l’opzione `agent`. { "$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, }, }, },} Puoi anche definire agenti usando file markdown in `~/.config/opencode/agents/` o `.opencode/agents/`. [Scopri di piu](https://opencode.ai/docs/agents) . * * * ### [Agente predefinito](https://opencode.ai/docs/it/config#agente-predefinito) Puoi impostare l’agente predefinito usando l’opzione `default_agent`. Questo determina quale agente viene usato quando non ne specifichi uno esplicitamente. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} L’agente predefinito deve essere un agente primary (non un subagent). Puo essere un agente integrato come `"build"` o `"plan"`, oppure un [agente personalizzato](https://opencode.ai/docs/agents) che hai definito. Se l’agente specificato non esiste o e un subagent, OpenCode fara fallback su `"build"` mostrando un avviso. Questa impostazione si applica a tutte le interfacce: TUI, CLI (`opencode run`), app desktop e GitHub Action. * * * ### [Condivisione](https://opencode.ai/docs/it/config#condivisione) Puoi configurare la funzione di [condivisione](https://opencode.ai/docs/share) tramite l’opzione `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Valori supportati: * `"manual"` - Consenti la condivisione manuale tramite comandi (predefinito) * `"auto"` - Condividi automaticamente le nuove conversazioni * `"disabled"` - Disabilita completamente la condivisione Per impostazione predefinita, la condivisione e in modalita manuale e devi condividere esplicitamente le conversazioni usando il comando `/share`. * * * ### [Comandi](https://opencode.ai/docs/it/config#comandi) Puoi configurare comandi personalizzati per task ripetitivi tramite l’opzione `command`. { "$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", }, },} Puoi anche definire comandi usando file markdown in `~/.config/opencode/commands/` o `.opencode/commands/`. [Scopri di piu](https://opencode.ai/docs/commands) . * * * ### [Scorciatoie](https://opencode.ai/docs/it/config#scorciatoie) Personalizza i keybind in `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [Scopri di piu](https://opencode.ai/docs/keybinds) . * * * ### [Aggiornamenti automatici](https://opencode.ai/docs/it/config#aggiornamenti-automatici) OpenCode scarichera automaticamente eventuali aggiornamenti quando si avvia. Puoi disabilitare questa funzione con l’opzione `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Se non vuoi aggiornamenti automatici ma vuoi essere avvisato quando e disponibile una nuova versione, imposta `autoupdate` a `"notify"`. Nota che questo funziona solo se non e stato installato con un package manager come Homebrew. * * * ### [Formatter](https://opencode.ai/docs/it/config#formatter) Puoi configurare i formatter di codice tramite l’opzione `formatter`. { "$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"] } }} [Scopri di piu sui formatter](https://opencode.ai/docs/formatters) . * * * ### [Permessi](https://opencode.ai/docs/it/config#permessi) Per impostazione predefinita, opencode **consente tutte le operazioni** senza richiedere un’approvazione esplicita. Puoi cambiarlo usando l’opzione `permission`. Per esempio, per fare in modo che gli strumenti `edit` e `bash` richiedano l’approvazione dell’utente: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Scopri di piu sui permessi](https://opencode.ai/docs/permissions) . * * * ### [Compattazione](https://opencode.ai/docs/it/config#compattazione) Puoi controllare il comportamento di compattazione del contesto tramite l’opzione `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - Compatta automaticamente la sessione quando il contesto e pieno (predefinito: `true`). * `prune` - Rimuove output vecchi degli strumenti per risparmiare token (predefinito: `true`). * `reserved` - Token buffer per la compattazione. Lascia abbastanza margine per evitare overflow durante la compattazione * * * ### [Monitoraggio file](https://opencode.ai/docs/it/config#monitoraggio-file) Puoi configurare i pattern di ignoramento del file watcher tramite l’opzione `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} I pattern seguono la sintassi glob. Usali per escludere directory rumorose dal monitoraggio dei file. * * * ### [Server MCP](https://opencode.ai/docs/it/config#server-mcp) Puoi configurare i server MCP che vuoi usare tramite l’opzione `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Scopri di piu](https://opencode.ai/docs/mcp-servers) . * * * ### [Plugin](https://opencode.ai/docs/it/config#plugin) [I plugin](https://opencode.ai/docs/plugins) estendono OpenCode con strumenti personalizzati, hook e integrazioni. Metti i file dei plugin in `.opencode/plugins/` o `~/.config/opencode/plugins/`. Puoi anche caricare plugin da npm tramite l’opzione `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Scopri di piu](https://opencode.ai/docs/plugins) . * * * ### [Istruzioni](https://opencode.ai/docs/it/config#istruzioni) Puoi configurare le istruzioni per il modello che stai usando tramite l’opzione `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Accetta un array di percorsi e pattern glob verso file di istruzioni. [Scopri di piu sulle regole](https://opencode.ai/docs/rules) . * * * ### [Provider disabilitati](https://opencode.ai/docs/it/config#provider-disabilitati) Puoi disabilitare i provider caricati automaticamente tramite l’opzione `disabled_providers`. E utile quando vuoi impedire il caricamento di alcuni provider anche se le credenziali sono disponibili. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} L’opzione `disabled_providers` accetta un array di ID provider. Quando un provider e disabilitato: * Non verra caricato anche se sono impostate variabili d’ambiente. * Non verra caricato anche se le chiavi API sono configurate tramite il comando `/connect`. * I modelli del provider non appariranno nella lista di selezione dei modelli. * * * ### [Provider abilitati](https://opencode.ai/docs/it/config#provider-abilitati) Puoi specificare un’allowlist di provider tramite l’opzione `enabled_providers`. Se impostata, solo i provider indicati verranno abilitati e tutti gli altri saranno ignorati. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} E utile quando vuoi limitare OpenCode a usare solo alcuni provider invece di disabilitarli uno per uno. Se un provider appare sia in `enabled_providers` sia in `disabled_providers`, `disabled_providers` ha priorita per retrocompatibilita. * * * ### [Sperimentale](https://opencode.ai/docs/it/config#sperimentale) La chiave `experimental` contiene opzioni in sviluppo attivo. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variabili](https://opencode.ai/docs/it/config#variabili) ---------------------------------------------------------- Puoi usare la sostituzione di variabili nei file di configurazione per referenziare variabili d’ambiente e contenuti di file. * * * ### [Variabili d’ambiente](https://opencode.ai/docs/it/config#variabili-dambiente) Usa `{env:VARIABLE_NAME}` per sostituire variabili d’ambiente: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Se la variabile d’ambiente non e impostata, verra sostituita con una stringa vuota. * * * ### [File](https://opencode.ai/docs/it/config#file) Usa `{file:path/to/file}` per sostituire il contenuto di un file: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} I percorsi dei file possono essere: * Relativi alla directory del file di configurazione * Oppure percorsi assoluti che iniziano con `/` o `~` Sono utili per: * Tenere dati sensibili (come chiavi API) in file separati. * Includere file di istruzioni grandi senza appesantire la configurazione. * Condividere snippet di configurazione comuni tra piu file di configurazione. --- # 設定 | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/config#_top) 設定 == OpenCode JSON 設定を使用します。 JSON 設定ファイルを使用して OpenCode を構成できます。 * * * [形式](https://opencode.ai/docs/ja/config#%E5%BD%A2%E5%BC%8F) ------------------------------------------------------------ OpenCode は、**JSON** と **JSONC** (コメント付きの JSON) 形式の両方をサポートしています。 { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [ファイルの場所](https://opencode.ai/docs/ja/config#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E5%A0%B4%E6%89%80) -------------------------------------------------------------------------------------------------------------- 設定をいくつかの異なる場所に配置できます。それらは異なる優先順位を持ちます。 設定ファイルは結合され、置き換えられません。次の構成場所からの設定が結合されます。競合するキーに対してのみ、後の設定が前の設定を上書きします。すべての構成からの競合しない設定は保持されます。 たとえば、グローバル設定で `autoupdate: true` を設定し、プロジェクト設定で `model: "anthropic/claude-sonnet-4-5"` を設定した場合、最終的な構成には両方の設定が含まれます。 * * * ### [優先順位](https://opencode.ai/docs/ja/config#%E5%84%AA%E5%85%88%E9%A0%86%E4%BD%8D) 設定ソースは次の順序でロードされます (後のソースは前のソースをオーバーライドします)。 1. **リモート設定** (`.well-known/opencode` から) - 組織のデフォルト 2. **グローバル設定** (`~/.config/opencode/opencode.json`) - ユーザー設定 3. **カスタム設定** (`OPENCODE_CONFIG` 環境変数) - カスタムオーバーライド 4. **プロジェクト設定** (プロジェクト内の `opencode.json`) - プロジェクト固有の設定 5. **`.opencode` ディレクトリ** - エージェント、コマンド、プラグイン 6. **インライン設定** (`OPENCODE_CONFIG_CONTENT` 環境変数) - ランタイムオーバーライド つまり、プロジェクト設定はグローバルのデフォルトをオーバーライドでき、グローバル設定はリモート組織のデフォルトをオーバーライドできます。 * * * ### [リモート](https://opencode.ai/docs/ja/config#%E3%83%AA%E3%83%A2%E3%83%BC%E3%83%88) 組織は、`.well-known/opencode` エンドポイント経由でデフォルト設定を提供できます。これは、それをサポートするプロバイダーで認証するときに自動的に取得されます。 リモート設定が最初にロードされ、基本層として機能します。他のすべての設定ソース (グローバル、プロジェクト) は、これらのデフォルトをオーバーライドできます。 たとえば、組織がデフォルトで無効になっている MCP サーバーを提供している場合: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} ローカル設定で特定のサーバーを有効にすることができます。 { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [グローバル](https://opencode.ai/docs/ja/config#%E3%82%B0%E3%83%AD%E3%83%BC%E3%83%90%E3%83%AB) グローバル OpenCode 設定を `~/.config/opencode/opencode.json` に配置します。プロバイダー、モデル、権限などのユーザー全体の設定にはグローバル設定を使用します。 TUI 固有の設定には、`~/.config/opencode/tui.json` を使用します。 グローバル設定はリモート組織のデフォルトをオーバーライドします。 * * * ### [プロジェクトごと](https://opencode.ai/docs/ja/config#%E3%83%97%E3%83%AD%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%94%E3%81%A8) プロジェクトのルートに `opencode.json` を追加します。プロジェクト設定は、標準設定ファイルの中で最も高い優先順位を持ち、グローバル設定とリモート設定の両方をオーバーライドします。 プロジェクト固有の TUI 設定については、その横に `tui.json` を追加します。 OpenCode が起動すると、現在のディレクトリで設定ファイルを検索するか、最も近い Git ディレクトリまで移動します。 これは Git に安全にチェックインでき、グローバルスキーマと同じスキーマを使用します。 * * * ### [カスタムパス](https://opencode.ai/docs/ja/config#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%91%E3%82%B9) `OPENCODE_CONFIG` 環境変数を使用してカスタム設定ファイルのパスを指定します。 export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" カスタム設定は、優先順位でグローバル設定とプロジェクト設定の間にロードされます。 * * * ### [カスタムディレクトリ](https://opencode.ai/docs/ja/config#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA) `OPENCODE_CONFIG_DIR` を使用してカスタム設定ディレクトリを指定します。 環境変数。このディレクトリでは、エージェント、コマンド、 モードとプラグインは標準の `.opencode` ディレクトリと同様であり、次のようにする必要があります。 同じ構造に従います。 export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" カスタムディレクトリはグローバル config ディレクトリと `.opencode` ディレクトリの後にロードされるため、それらの設定を**オーバーライド**できます。 * * * [スキーマ](https://opencode.ai/docs/ja/config#%E3%82%B9%E3%82%AD%E3%83%BC%E3%83%9E) -------------------------------------------------------------------------------- サーバー/ランタイム構成スキーマは [**`opencode.ai/config.json`**](https://opencode.ai/config.json) で定義されています。 TUI 設定は [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) を使用します。 エディターはスキーマに基づいて検証し、オートコンプリートできる必要があります。 * * * ### [TUI](https://opencode.ai/docs/ja/config#tui) TUI 固有の設定には、専用の `tui.json` (または `tui.jsonc`) ファイルを使用します。 { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} カスタム TUI 設定ファイルを指定するには、`OPENCODE_TUI_CONFIG` を使用します。 `opencode.json` 内の従来の `theme`、`keybinds`、および `tui` キーは非推奨となり、可能であれば自動的に移行されます。 [TUI の設定の詳細については、こちら](https://opencode.ai/docs/tui#configure) をご覧ください。 * * * ### [サーバー](https://opencode.ai/docs/ja/config#%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC) `opencode serve` オプションを使用して、`opencode web` および `server` コマンドのサーバー設定を構成できます。 { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} 利用可能なオプション: * `port` - リッスンするポート。 * `hostname` - リッスンするホスト名。 `mdns` が有効でホスト名が設定されていない場合、デフォルトは `0.0.0.0` になります。 * `mdns` - mDNS サービス検出を有効にします。これにより、ネットワーク上の他のデバイスが OpenCode サーバーを検出できるようになります。 * `mdnsDomain` - mDNS サービスのカスタムドメイン名。デフォルトは `opencode.local` です。同じネットワーク上で複数のインスタンスを実行する場合に便利です。 * `cors` - ブラウザベースのクライアントから HTTP サーバーを使用するときに CORS を許可する追加のオリジン。値は完全なオリジン (スキーム + ホスト + オプションのポート) である必要があります (例: `https://app.example.com`)。 [サーバーの詳細については、こちら](https://opencode.ai/docs/server) をご覧ください。 * * * ### [ツール](https://opencode.ai/docs/ja/config#%E3%83%84%E3%83%BC%E3%83%AB) LLM が使用できるツールは、`tools` オプションを通じて管理できます。 { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [ツールの詳細については、こちらをご覧ください](https://opencode.ai/docs/tools) 。 * * * ### [モデル](https://opencode.ai/docs/ja/config#%E3%83%A2%E3%83%87%E3%83%AB) `provider`、`model`、および `small_model` オプションを使用して、OpenCode 設定で使用するプロバイダーとモデルを構成できます。 { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} `small_model` オプションは、タイトルの生成などの軽量タスク用に個別のモデルを構成します。デフォルトでは、OpenCode は、プロバイダーから安価なモデルが入手可能な場合は、より安価なモデルを使用しようとします。そうでない場合は、メインモデルにフォールバックします。 プロバイダーオプションには、`timeout` および `setCacheKey` を含めることができます。 { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - リクエストのタイムアウト (ミリ秒単位) (デフォルト: 300000)。無効にするには、`false` に設定します。 * `setCacheKey` - 指定されたプロバイダーに対してキャッシュキーが常に設定されていることを確認します。 [ローカルモデル](https://opencode.ai/docs/models#local) も設定できます。[詳細はこちら](https://opencode.ai/docs/models) 。 * * * #### [プロバイダー固有のオプション](https://opencode.ai/docs/ja/config#%E3%83%97%E3%83%AD%E3%83%90%E3%82%A4%E3%83%80%E3%83%BC%E5%9B%BA%E6%9C%89%E3%81%AE%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%B3) 一部のプロバイダーは、一般的な `timeout` および `apiKey` 設定を超える追加の構成オプションをサポートしています。 ##### [Amazon Bedrock](https://opencode.ai/docs/ja/config#amazon-bedrock) Amazon Bedrock は、AWS 固有の設定をサポートしています。 { "$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` - Bedrock の AWS リージョン (デフォルトは `AWS_REGION` 環境変数または `us-east-1`) * `profile` - `~/.aws/credentials` からの AWS 名前付きプロファイル (デフォルトは `AWS_PROFILE` 環境変数) * `endpoint` - VPC エンドポイントのカスタムエンドポイント URL。これは、AWS 固有の用語を使用した汎用 `baseURL` オプションのエイリアスです。両方を指定した場合は、`endpoint` が優先されます。 [Amazon Bedrock 設定](https://opencode.ai/docs/providers#amazon-bedrock) の詳細をご覧ください。 * * * ### [テーマ](https://opencode.ai/docs/ja/config#%E3%83%86%E3%83%BC%E3%83%9E) UI テーマを `tui.json` で設定します。 { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [詳細はこちら](https://opencode.ai/docs/themes) 。 * * * ### [エージェント](https://opencode.ai/docs/ja/config#%E3%82%A8%E3%83%BC%E3%82%B8%E3%82%A7%E3%83%B3%E3%83%88) `agent` オプションを使用して、特定のタスクに特化したエージェントを構成できます。 { "$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, }, }, },} `~/.config/opencode/agents/` または `.opencode/agents/` の Markdown ファイルを使用してエージェントを定義することもできます。 [詳細はこちら](https://opencode.ai/docs/agents) 。 * * * ### [デフォルトエージェント](https://opencode.ai/docs/ja/config#%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%82%A8%E3%83%BC%E3%82%B8%E3%82%A7%E3%83%B3%E3%83%88) `default_agent` オプションを使用してデフォルトのエージェントを設定できます。これにより、明示的に何も指定されていない場合にどのエージェントが使用されるかが決まります。 { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} デフォルトのエージェントはプライマリエージェントである必要があります (サブエージェントではありません)。これは、`"build"` や `"plan"` のような組み込みエージェント、または定義した[カスタムエージェント](https://opencode.ai/docs/agents) にすることができます。指定されたエージェントが存在しないか、サブエージェントである場合、OpenCode は警告とともに `"build"` にフォールバックします。 この設定は、TUI、CLI (`opencode run`)、デスクトップアプリ、および GitHub Action のすべてのインターフェイスに適用されます。 * * * ### [共有](https://opencode.ai/docs/ja/config#%E5%85%B1%E6%9C%89) `share` オプションを使用して [share](https://opencode.ai/docs/share) 機能を設定できます。 { "$schema": "https://opencode.ai/config.json", "share": "manual"} これには以下が必要です: * `"manual"` - コマンドによる手動共有を許可します (デフォルト) * `"auto"` - 新しい会話を自動的に共有します * `"disabled"` - 共有を完全に無効にする デフォルトでは、共有は手動モードに設定されており、`/share` コマンドを使用して会話を明示的に共有する必要があります。 * * * ### [コマンド](https://opencode.ai/docs/ja/config#%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89) `command` オプションを使用して、反復タスク用のカスタムコマンドを構成できます。 { "$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", }, },} `~/.config/opencode/commands/` または `.opencode/commands/` の Markdown ファイルを使用してコマンドを定義することもできます。 [詳細はこちら](https://opencode.ai/docs/commands) 。 * * * ### [キーバインド](https://opencode.ai/docs/ja/config#%E3%82%AD%E3%83%BC%E3%83%90%E3%82%A4%E3%83%B3%E3%83%89) `tui.json` でキーバインドをカスタマイズします。 { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [詳細はこちら](https://opencode.ai/docs/keybinds) 。 * * * ### [自動更新](https://opencode.ai/docs/ja/config#%E8%87%AA%E5%8B%95%E6%9B%B4%E6%96%B0) OpenCode は起動時に新しいアップデートを自動的にダウンロードします。 `autoupdate` オプションを使用してこれを無効にできます。 { "$schema": "https://opencode.ai/config.json", "autoupdate": false} 更新は必要ないが、新しいバージョンが利用可能になったときに通知を受け取りたい場合は、`autoupdate` を `"notify"` に設定します。 これは、Homebrew などのパッケージマネージャーを使用してインストールされていない場合にのみ機能することに注意してください。 * * * ### [フォーマッタ](https://opencode.ai/docs/ja/config#%E3%83%95%E3%82%A9%E3%83%BC%E3%83%9E%E3%83%83%E3%82%BF) `formatter` オプションを使用してコードフォーマッタを設定できます。 { "$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"] } }} [フォーマッタの詳細については、こちら](https://opencode.ai/docs/formatters) をご覧ください。 * * * ### [権限](https://opencode.ai/docs/ja/config#%E6%A8%A9%E9%99%90) デフォルトでは、opencode は明示的な承認を必要とせずに **すべての操作を許可**します。これは、`permission` オプションを使用して変更できます。 たとえば、`edit` ツールと `bash` ツールにユーザーの承認が必要であることを確認するには、次のようにします。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [権限の詳細については、こちら](https://opencode.ai/docs/permissions) をご覧ください。 * * * ### [圧縮](https://opencode.ai/docs/ja/config#%E5%9C%A7%E7%B8%AE) `compaction` オプションを使用してコンテキストの圧縮動作を制御できます。 { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true }} * `auto` - コンテキストがいっぱいのときにセッションを自動的に圧縮します (デフォルト: `true`)。 * `prune` - 古いツールの出力を削除してトークンを保存します (デフォルト: `true`)。 * * * ### [ウォッチャー](https://opencode.ai/docs/ja/config#%E3%82%A6%E3%82%A9%E3%83%83%E3%83%81%E3%83%A3%E3%83%BC) `watcher` オプションを使用して、ファイルウォッチャーの無視パターンを構成できます。 { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} パターンは glob 構文に従います。これを使用して、ノイズの多いディレクトリをファイル監視から除外します。 * * * ### [MCPサーバー](https://opencode.ai/docs/ja/config#mcp%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC) `mcp` オプションを使用して、使用する MCP サーバーを構成できます。 { "$schema": "https://opencode.ai/config.json", "mcp": {}} [詳細はこちら](https://opencode.ai/docs/mcp-servers) 。 * * * ### [プラグイン](https://opencode.ai/docs/ja/config#%E3%83%97%E3%83%A9%E3%82%B0%E3%82%A4%E3%83%B3) [Plugins](https://opencode.ai/docs/plugins) は、カスタムツール、フック、統合を使用して OpenCode を拡張します。 プラグインファイルを `.opencode/plugins/` または `~/.config/opencode/plugins/` に配置します。 `plugin` オプションを使用して npm からプラグインをロードすることもできます。 { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [詳細はこちら](https://opencode.ai/docs/plugins) 。 * * * ### [指示](https://opencode.ai/docs/ja/config#%E6%8C%87%E7%A4%BA) `instructions` オプションを使用して、使用しているモデルの指示を構成できます。 { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} これは、指示ファイルへのパスとグロブパターンの配列を受け取ります。 [ルールについて詳しくはこちら](https://opencode.ai/docs/rules) 。 * * * ### [無効なプロバイダー](https://opencode.ai/docs/ja/config#%E7%84%A1%E5%8A%B9%E3%81%AA%E3%83%97%E3%83%AD%E3%83%90%E3%82%A4%E3%83%80%E3%83%BC) `disabled_providers` オプションを使用して、自動的にロードされるプロバイダーを無効にすることができます。これは、認証情報が利用可能な場合でも、特定のプロバイダーが読み込まれないようにしたい場合に便利です。 { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} `disabled_providers` オプションは、プロバイダー ID の配列を受け入れます。プロバイダーが無効になっている場合: * 環境変数を設定してもロードされません。 * `/connect` コマンドで API キーを設定してもロードされません。 * プロバイダーのモデルはモデル選択リストに表示されません。 * * * ### [有効なプロバイダー](https://opencode.ai/docs/ja/config#%E6%9C%89%E5%8A%B9%E3%81%AA%E3%83%97%E3%83%AD%E3%83%90%E3%82%A4%E3%83%80%E3%83%BC) `enabled_providers` オプションを使用してプロバイダーの許可リストを指定できます。設定すると、指定されたプロバイダーのみが有効になり、その他はすべて無視されます。 { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} これは、OpenCode を 1 つずつ無効にするのではなく、特定のプロバイダーのみを使用するように制限したい場合に便利です。 プロバイダーが `enabled_providers` と `disabled_providers` の両方に表示される場合、下位互換性のために `disabled_providers` が優先されます。 * * * ### [実験的](https://opencode.ai/docs/ja/config#%E5%AE%9F%E9%A8%93%E7%9A%84) `experimental` キーには、現在開発中のオプションが含まれています。 { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [変数](https://opencode.ai/docs/ja/config#%E5%A4%89%E6%95%B0) ------------------------------------------------------------ 設定ファイル内で変数置換を使用して、環境変数とファイルの内容を参照できます。 * * * ### [環境変数](https://opencode.ai/docs/ja/config#%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0) `{env:VARIABLE_NAME}` を使用して環境変数を置き換えます。 { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} 環境変数が設定されていない場合は、空の文字列に置き換えられます。 * * * ### [ファイル](https://opencode.ai/docs/ja/config#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB) `{file:path/to/file}` を使用してファイルの内容を置き換えます。 { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} ファイルパスは次のとおりです。 * 設定ファイルのディレクトリからの相対パス * または、`/` または `~` で始まる絶対パス これらは次の場合に役立ちます。 * API キーなどの機密データを別のファイルに保存します。 * 設定を乱雑にすることなく、大きな指示ファイルを含めることができます。 * 複数の設定ファイル間で共通の設定スニペットを共有します。 --- # แบ่งปัน | OpenCode [Skip to content](https://opencode.ai/docs/th/share#_top) แบ่งปัน ======= แบ่งปันการสนทนา OpenCode ของคุณ คุณลักษณะการแชร์ของ OpenCode ช่วยให้คุณสร้างลิงก์สาธารณะไปยังการสนทนา OpenCode ของคุณ เพื่อให้คุณสามารถทำงานร่วมกับเพื่อนร่วมทีมหรือรับความช่วยเหลือจากผู้อื่นได้ * * * [มันทำงานอย่างไร](https://opencode.ai/docs/th/share#%E0%B8%A1%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B9%84%E0%B8%A3) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เมื่อคุณแบ่งปันการสนทนา OpenCode: 1. สร้าง URL สาธารณะที่ไม่ซ้ำสำหรับเซสชันของคุณ 2. ซิงค์ประวัติการสนทนาของคุณกับเซิร์ฟเวอร์ของเรา 3. ทำให้สามารถเข้าถึงการสนทนาผ่านลิงก์ที่แชร์ได้ — `opncd.ai/s/` * * * [การแบ่งปัน](https://opencode.ai/docs/th/share#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%81%E0%B8%9A%E0%B9%88%E0%B8%87%E0%B8%9B%E0%B8%B1%E0%B8%99) ------------------------------------------------------------------------------------------------------------------------------------------- OpenCode รองรับโหมดการแชร์สามโหมดที่ควบคุมวิธีการแชร์การสนทนา: * * * ### [Manual (ค่าเริ่มต้น)](https://opencode.ai/docs/th/share#manual-%E0%B8%84%E0%B9%88%E0%B8%B2%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%95%E0%B9%89%E0%B8%99) ตามค่าเริ่มต้น OpenCode จะใช้โหมดการแชร์ด้วยตนเอง เซสชันจะไม่ถูกแชร์โดยอัตโนมัติ แต่คุณสามารถแชร์ได้ด้วยตนเองโดยใช้คำสั่ง `/share`: /share สิ่งนี้จะสร้าง URL ที่ไม่ซ้ำกันซึ่งจะถูกคัดลอกไปยังคลิปบอร์ดของคุณ หากต้องการตั้งค่าโหมดแมนนวลอย่างชัดเจนใน [ไฟล์ปรับแต่ง](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [แชร์อัตโนมัติ](https://opencode.ai/docs/th/share#%E0%B9%81%E0%B8%8A%E0%B8%A3%E0%B9%8C%E0%B8%AD%E0%B8%B1%E0%B8%95%E0%B9%82%E0%B8%99%E0%B8%A1%E0%B8%B1%E0%B8%95%E0%B8%B4) คุณสามารถเปิดใช้งานการแบ่งปันอัตโนมัติสำหรับการสนทนาใหม่ทั้งหมดโดยตั้งค่าตัวเลือก `share` เป็น `"auto"` ใน [ไฟล์กำหนดค่า](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} เมื่อเปิดใช้งานการแชร์อัตโนมัติ ทุกการสนทนาใหม่จะถูกแชร์โดยอัตโนมัติและลิงก์จะถูกสร้างขึ้น * * * ### [ปิดการใช้งาน](https://opencode.ai/docs/th/share#%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99) คุณสามารถปิดการแชร์ทั้งหมดได้โดยตั้งค่าตัวเลือก `share` เป็น `"disabled"` ใน [ไฟล์กำหนดค่า](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} หากต้องการบังคับใช้สิ่งนี้กับทีมของคุณสำหรับโปรเจ็กต์ที่กำหนด ให้เพิ่มลงใน `opencode.json` ในโปรเจ็กต์ของคุณและตรวจสอบใน Git * * * [ยกเลิกการแชร์](https://opencode.ai/docs/th/share#%E0%B8%A2%E0%B8%81%E0%B9%80%E0%B8%A5%E0%B8%B4%E0%B8%81%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%81%E0%B8%8A%E0%B8%A3%E0%B9%8C) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- หากต้องการหยุดแชร์การสนทนาและลบออกจากการเข้าถึงแบบสาธารณะ: /unshare การดำเนินการนี้จะลบลิงก์แชร์และลบข้อมูลที่เกี่ยวข้องกับการสนทนา * * * [ความเป็นส่วนตัว](https://opencode.ai/docs/th/share#%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B9%80%E0%B8%9B%E0%B9%87%E0%B8%99%E0%B8%AA%E0%B9%88%E0%B8%A7%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- มีบางสิ่งที่ต้องคำนึงถึงเมื่อแบ่งปันการสนทนา * * * ### [การเก็บรักษาข้อมูล](https://opencode.ai/docs/th/share#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%81%E0%B9%87%E0%B8%9A%E0%B8%A3%E0%B8%B1%E0%B8%81%E0%B8%A9%E0%B8%B2%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5) การสนทนาที่แชร์จะยังสามารถเข้าถึงได้จนกว่าคุณจะยกเลิกการแชร์อย่างชัดเจน นี้ รวมถึง: * ประวัติการสนทนาแบบเต็ม * ทุกข้อความและการตอบกลับ * ข้อมูลเมตาของเซสชัน * * * ### [ข้อแนะนำ](https://opencode.ai/docs/th/share#%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B9%81%E0%B8%99%E0%B8%B0%E0%B8%99%E0%B8%B3) * แชร์การสนทนาที่ไม่มีข้อมูลที่ละเอียดอ่อนเท่านั้น * ตรวจสอบเนื้อหาการสนทนาก่อนที่จะแบ่งปัน * ยกเลิกการแชร์การสนทนาเมื่อการทำงานร่วมกันเสร็จสมบูรณ์ * หลีกเลี่ยงการแบ่งปันการสนทนาด้วยรหัสที่เป็นกรรมสิทธิ์หรือข้อมูลที่เป็นความลับ * สำหรับโปรเจ็กต์ที่มีความละเอียดอ่อน ให้ปิดการแชร์ทั้งหมด * * * [สำหรับสถานประกอบการ](https://opencode.ai/docs/th/share#%E0%B8%AA%E0%B8%B3%E0%B8%AB%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%AA%E0%B8%96%E0%B8%B2%E0%B8%99%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%81%E0%B8%AD%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- สำหรับการปรับใช้ระดับองค์กร คุณสมบัติการแชร์อาจเป็น: * **ปิดการใช้งาน** ทั้งหมดเพื่อความปลอดภัย * **จำกัด** สำหรับผู้ใช้ที่ผ่านการรับรองความถูกต้องผ่าน SSO เท่านั้น * **โฮสต์เอง** บนโครงสร้างพื้นฐานของคุณเอง [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/enterprise) เกี่ยวกับการใช้ opencode ในองค์กรของคุณ --- # Udostępnianie | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/share#_top) Udostępnianie ============= Udostępnij swoje rozmowy dotyczące opencode. Funkcja udostępniania opencode umożliwia tworzenie publicznych linków do konwersacji opencode, dzięki czemu możesz współpracować z członkami zespołu lub uzyskać pomoc od innych. * * * [Jak to działa](https://opencode.ai/docs/pl/share#jak-to-dzia%C5%82a) ---------------------------------------------------------------------- Kiedy udostępniasz rozmowę, opencode: 1. Tworzy unikalny publiczny adres URL sesji 2. Synchronizuje historię rozmów z naszymi serwerami 3. Udostępnia rozmowę za pośrednictwem łącza do udostępniania — `opncd.ai/s/` * * * [Udostępnianie](https://opencode.ai/docs/pl/share#udost%C4%99pnianie) ---------------------------------------------------------------------- opencode obsługuje trzy tryby udostępniania, które kontrolują sposób udostępniania rozmów: * * * ### [Ręczne (domyślne)](https://opencode.ai/docs/pl/share#r%C4%99czne-domy%C5%9Blne) Domyślnie opencode korzysta z ręcznego trybu udostępniania. Sesje nie są udostępniane automatycznie, ale możesz je udostępnić ręcznie za pomocą polecenia `/share`: /share Spowoduje to wygenerowanie unikalnego adresu URL, który zostanie skopiowany do schowka. Aby jawnie ustawić tryb ręczny w \[pliku konfiguracyjnym\] (./config): { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Automatyczne udostępnianie](https://opencode.ai/docs/pl/share#automatyczne-udost%C4%99pnianie) Możesz włączyć automatyczne udostępnianie dla wszystkich nowych rozmów, ustawiając opcję `share` na `"auto"` w \[pliku konfiguracyjnym\] (./config): { "$schema": "https://opencode.ai/config.json", "share": "auto"} Po włączeniu automatycznego udostępniania każda nowa rozmowa będzie automatycznie udostępniana i generowany będzie link. * * * ### [Wyłączone](https://opencode.ai/docs/pl/share#wy%C5%82%C4%85czone) Możesz całkowicie wyłączyć udostępnianie, ustawiając opcję `share` na `"disabled"` w \[pliku konfiguracyjnym\] (./config): { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Aby wymusić to w całym zespole dla danego projektu, dodaj go do `opencode.json` w swoim projekcie i sprawdź w Git. * * * [Cofnięcie udostępnienia](https://opencode.ai/docs/pl/share#cofni%C4%99cie-udost%C4%99pnienia) ----------------------------------------------------------------------------------------------- Aby zatrzymać udostępnianie rozmowy i usunąć ją z dostępu publicznego: /unshare Spowoduje to usunięcie łącza udostępniania i danych związanych z rozmową. * * * [Prywatność](https://opencode.ai/docs/pl/share#prywatno%C5%9B%C4%87) --------------------------------------------------------------------- Podczas udostępniania rozmowy należy pamiętać o kilku rzeczach. * * * ### [Przechowywanie danych](https://opencode.ai/docs/pl/share#przechowywanie-danych) Udostępnione rozmowy pozostają dostępne, dopóki wyraźnie ich nie udostępnisz. Ten includes: * Pełna historia rozmów * Wszystkie wiadomości i odpowiedzi * Metadane sesji * * * ### [Zalecenia](https://opencode.ai/docs/pl/share#zalecenia) * Udostępniaj tylko rozmowy, które nie zawierają poufnych informacji. * Przejrzyj treść rozmowy przed udostępnieniem. * Cofnij udostępnianie rozmów po zakończeniu współpracy. * Unikaj udostępniania rozmów zawierających zastrzeżony kod lub poufne dane. * W przypadku wrażliwych projektów całkowicie wyłącz udostępnianie. * * * [Dla przedsiębiorstw](https://opencode.ai/docs/pl/share#dla-przedsi%C4%99biorstw) ---------------------------------------------------------------------------------- W przypadku wdrożeń korporacyjnych funkcją udostępniania może być: * **Wyłączone** całkowicie ze względu na bezpieczeństwo * **Restricted** to users authenticated through SSO only * **Własny hosting** na własnej infrastrukturze [Dowiedz się więcej](https://opencode.ai/docs/enterprise) o używaniu opencode w Twojej organizacji. --- # Paylasim | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/share#_top) Paylasim ======== opencode konusmalarini genel baglantilarla paylasin. opencode’un paylasim ozelligi, konusmalariniz icin genel baglantilar olusturmanizi saglar. Boylece ekip arkadaslarinizla birlikte calisabilir veya diger kisilerden yardim alabilirsiniz. * * * [Nasil calisir](https://opencode.ai/docs/tr/share#nasil-calisir) ----------------------------------------------------------------- Bir konusmayi paylastiginizda opencode: 1. Oturumunuz icin benzersiz bir genel URL olusturur 2. Konusma gecmisinizi sunucularimiza senkronize eder 3. Konusmayi paylasim baglantisiyla erisilebilir hale getirir - `opncd.ai/s/` * * * [Paylasim](https://opencode.ai/docs/tr/share#paylasim) ------------------------------------------------------- opencode, konusmalarin nasil paylasilacagini kontrol eden uc farkli paylasim modu sunar: * * * ### [Manuel (varsayilan)](https://opencode.ai/docs/tr/share#manuel-varsayilan) Varsayilan olarak opencode manuel paylasim modunu kullanir. Oturumlar otomatik paylasilmaz, ancak `/share` komutuyla manuel olarak paylasabilirsiniz: /share Bu komut benzersiz bir URL uretir ve panoya kopyalar. Manuel modu acikca ayarlamak icin [config dosyaniza](https://opencode.ai/docs/config) sunu ekleyin: { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Otomatik paylasim](https://opencode.ai/docs/tr/share#otomatik-paylasim) Tum yeni konusmalar icin otomatik paylasimi acmak isterseniz, [config dosyanizda](https://opencode.ai/docs/config) `share` degerini `"auto"` yapin: { "$schema": "https://opencode.ai/config.json", "share": "auto"} Otomatik paylasim acikken her yeni konusma otomatik olarak paylasilir ve bir baglanti olusturulur. * * * ### [Devre disi](https://opencode.ai/docs/tr/share#devre-disi) Paylasimi tamamen kapatmak icin [config dosyanizda](https://opencode.ai/docs/config) `share` degerini `"disabled"` yapin: { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Bunu belirli bir projede tum ekip icin zorunlu kilmak icin proje icindeki `opencode.json` dosyasina ekleyip Git’e commit edin. * * * [Paylasimi kaldirma](https://opencode.ai/docs/tr/share#paylasimi-kaldirma) --------------------------------------------------------------------------- Bir konusmanin paylasimini durdurmak ve genel erisimi kaldirmak icin: /unshare Bu komut paylasim baglantisini kaldirir ve konusmaya ait verileri siler. * * * [Gizlilik](https://opencode.ai/docs/tr/share#gizlilik) ------------------------------------------------------- Bir konusmayi paylasirken akilda tutulmasi gereken bazi noktalar vardir. * * * ### [Veri saklama](https://opencode.ai/docs/tr/share#veri-saklama) Paylasilan konusmalar, siz acikca paylasimi kaldirana kadar erisilebilir kalir. Buna sunlar dahildir: * Tum konusma gecmisi * Tum mesajlar ve yanitlar * Oturum metaverisi * * * ### [Oneriler](https://opencode.ai/docs/tr/share#oneriler) * Hassas bilgi icermeyen konusmalari paylasin. * Paylasmadan once konusma icerigini gozden gecirin. * Is birligi bittiginde paylasimi kaldirin. * Tescilli kod veya gizli veri iceren konusmalari paylasmayin. * Hassas projelerde paylasimi tamamen kapatin. * * * [Kurumsal kullanim](https://opencode.ai/docs/tr/share#kurumsal-kullanim) ------------------------------------------------------------------------- Kurumsal kurulumlarda paylasim ozelligi su sekillerde yapilandirilabilir: * Guvenlik uyumu icin tamamen **devre disi** birakilabilir * Sadece SSO ile dogrulanan kullanicilarla **sinirlandirilabilir** * Kendi altyapinizda **self-hosted** olarak calistirilabilir Kurulusunuzda opencode kullanimi icin [daha fazla bilgi alin](https://opencode.ai/docs/enterprise) . --- # 공유 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/share#_top) 공유 == OpenCode 대화를 공유하세요. opencode의 공유 기능은 opencode 대화에 대한 공개 링크를 만들 수 있으므로 Teammates와 협업하거나 다른 곳에서 도움을받을 수 있습니다. * * * [작동 방식](https://opencode.ai/docs/ko/share#%EC%9E%91%EB%8F%99-%EB%B0%A9%EC%8B%9D) --------------------------------------------------------------------------------- 대화를 공유할 때, opencode: 1. 세션에 대한 독특한 공개 URL 만들기 2. 우리의 서버에 대화 기록 동기화 3. 공유 가능한 링크를 통해 접근 할 수있는 대화 만들기 — `opncd.ai/s/` * * * [공유](https://opencode.ai/docs/ko/share#%EA%B3%B5%EC%9C%A0) ----------------------------------------------------------- opencode는 대화가 공유되는 방법을 제어하는 세 가지 공유 모드를 지원합니다. * * * [수동 (기본)](https://opencode.ai/docs/ko/share#%EC%88%98%EB%8F%99-%EA%B8%B0%EB%B3%B8) ----------------------------------------------------------------------------------- 기본적으로 opencode는 수동 공유 모드를 사용합니다. 세션은 자동으로 공유되지 않지만 `/share` 명령을 사용하여 수동으로 공유 할 수 있습니다. /share 클립보드에 복사할 수 있는 독특한 URL을 생성합니다. [config 파일](https://opencode.ai/docs/config) 에서 수동 모드를 명시적으로 설정하려면: { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * [자동 공유](https://opencode.ai/docs/ko/share#%EC%9E%90%EB%8F%99-%EA%B3%B5%EC%9C%A0) --------------------------------------------------------------------------------- `share` 옵션을 설정하여 모든 새로운 대화에 대한 자동 공유를 활성화 할 수 있습니다 `"auto"` 당신의 [config 파일](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} 자동 공유 활성화로 모든 새로운 대화는 자동으로 공유되고 링크가 생성됩니다. * * * #### [비활성화](https://opencode.ai/docs/ko/share#%EB%B9%84%ED%99%9C%EC%84%B1%ED%99%94) `share` 옵션을 설정하여 완전히 공유할 수 있습니다. `"disabled"`에 [config file](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} 주어진 프로젝트를 위해 팀 전반에 걸쳐 이것을 시행하려면 프로젝트에 `opencode.json`에 추가하고 Git로 확인하십시오. * * * [공유 취소](https://opencode.ai/docs/ko/share#%EA%B3%B5%EC%9C%A0-%EC%B7%A8%EC%86%8C) --------------------------------------------------------------------------------- 대화를 중지하고 공공 액세스에서 제거 : /unshare 이 공유 링크를 제거하고 대화와 관련된 데이터를 삭제합니다. * * * [개인 정보](https://opencode.ai/docs/ko/share#%EA%B0%9C%EC%9D%B8-%EC%A0%95%EB%B3%B4) --------------------------------------------------------------------------------- 대화를 나누면 마음이 유지되는 몇 가지가 있습니다. * * * [데이터 보유](https://opencode.ai/docs/ko/share#%EB%8D%B0%EC%9D%B4%ED%84%B0-%EB%B3%B4%EC%9C%A0) ------------------------------------------------------------------------------------------- 공유 대화는 명시적으로 그들을 공유 할 때까지 접근 할 수 있습니다. 이름 \* 다음: * 전체 대화 기록 * 모든 메시지 및 응답 * 세션 메타데이터 * * * ### [추천](https://opencode.ai/docs/ko/share#%EC%B6%94%EC%B2%9C) * 민감한 정보를 포함하지 않는 대화 만 공유합니다. * 공유하기 전에 대화 내용을 검토하십시오. * 협업이 완료되면 Unshare 대화. * 독점 코드 또는 기밀 데이터와 대화를 공유하지 마십시오. * 민감한 프로젝트를 위해, 완전히 공유할 수 있습니다. * * * [기업용](https://opencode.ai/docs/ko/share#%EA%B8%B0%EC%97%85%EC%9A%A9) --------------------------------------------------------------------- 기업 배포를 위해, 공유 기능은: * \*\* 보안 준수를 위해 완전히 비활성화 \*\* * \*\*SSO를 통해 인증된 사용자에 대한 제한 \*\* * \*\* 자체 인프라 \*\* [Learn more](https://opencode.ai/docs/enterprise) 귀하의 조직에서 opencode를 사용하여. --- # Делиться | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/share#_top) Делиться ======== Поделитесь своими разговорами об opencode. Функция общего доступа opencode позволяет вам создавать общедоступные ссылки на ваши беседы opencode, чтобы вы могли сотрудничать с товарищами по команде или получать помощь от других. * * * [Как это работает](https://opencode.ai/docs/ru/share#%D0%BA%D0%B0%D0%BA-%D1%8D%D1%82%D0%BE-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82) --------------------------------------------------------------------------------------------------------------------------------------------- Когда вы делитесь беседой, opencode: 1. Создает уникальный общедоступный URL-адрес для вашего сеанса. 2. Синхронизирует историю ваших разговоров с нашими серверами 3. Делает беседу доступной по общей ссылке — `opncd.ai/s/`. * * * [Совместное использование](https://opencode.ai/docs/ru/share#%D1%81%D0%BE%D0%B2%D0%BC%D0%B5%D1%81%D1%82%D0%BD%D0%BE%D0%B5-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- opencode поддерживает три режима общего доступа, которые контролируют общий доступ к разговорам: * * * ### [Ручной (по умолчанию)](https://opencode.ai/docs/ru/share#%D1%80%D1%83%D1%87%D0%BD%D0%BE%D0%B9-%D0%BF%D0%BE-%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E) По умолчанию opencode использует режим совместного использования вручную. Сессии не передаются автоматически, но вы можете поделиться ими вручную с помощью команды `/share`: /share Это создаст уникальный URL-адрес, который будет скопирован в буфер обмена. Чтобы явно установить ручной режим в вашем [файле конфигурации](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Автоматическая публикация](https://opencode.ai/docs/ru/share#%D0%B0%D0%B2%D1%82%D0%BE%D0%BC%D0%B0%D1%82%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B0%D1%8F-%D0%BF%D1%83%D0%B1%D0%BB%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F) Вы можете включить автоматический общий доступ для всех новых разговоров, установив для параметра `share` значение `"auto"` в вашем [файле конфигурации](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} Если функция автоматического обмена включена, каждый новый разговор будет автоматически опубликован и будет создана ссылка. * * * ### [Отключено](https://opencode.ai/docs/ru/share#%D0%BE%D1%82%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%BE) Вы можете полностью отключить общий доступ, установив для параметра `share` значение `"disabled"` в вашем [файле конфигурации](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Чтобы обеспечить соблюдение этого правила для всей вашей команды в конкретном проекте, добавьте его в `opencode.json` вашего проекта и зарегистрируйтесь в Git. * * * [Отменить совместное использование](https://opencode.ai/docs/ru/share#%D0%BE%D1%82%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C-%D1%81%D0%BE%D0%B2%D0%BC%D0%B5%D1%81%D1%82%D0%BD%D0%BE%D0%B5-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Чтобы прекратить делиться беседой и удалить ее из общего доступа: /unshare Это приведет к удалению ссылки общего доступа и удалению данных, связанных с разговором. * * * [Конфиденциальность](https://opencode.ai/docs/ru/share#%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B4%D0%B5%D0%BD%D1%86%D0%B8%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C) --------------------------------------------------------------------------------------------------------------------------------------------------------------------- Есть несколько вещей, которые следует учитывать при общении. * * * ### [Хранение данных](https://opencode.ai/docs/ru/share#%D1%85%D1%80%D0%B0%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85) Общие разговоры остаются доступными до тех пор, пока вы явно не отмените общий доступ к ним. Этот включает в себя: * Полная история разговоров * Все сообщения и ответы * Метаданные сеанса * * * ### [Рекомендации](https://opencode.ai/docs/ru/share#%D1%80%D0%B5%D0%BA%D0%BE%D0%BC%D0%B5%D0%BD%D0%B4%D0%B0%D1%86%D0%B8%D0%B8) * Делитесь только разговорами, которые не содержат конфиденциальной информации. * Прежде чем поделиться, просмотрите содержимое разговора. * Отмените общий доступ к разговорам после завершения сотрудничества. * Избегайте обмена разговорами с проприетарным кодом или конфиденциальными данными. * Для конфиденциальных проектов полностью отключите общий доступ. * * * [Для предприятий](https://opencode.ai/docs/ru/share#%D0%B4%D0%BB%D1%8F-%D0%BF%D1%80%D0%B5%D0%B4%D0%BF%D1%80%D0%B8%D1%8F%D1%82%D0%B8%D0%B9) ------------------------------------------------------------------------------------------------------------------------------------------- Для корпоративных развертываний функция общего доступа может быть: * **Отключено** полностью из соображений безопасности. * **Доступно только** для пользователей, прошедших аутентификацию посредством единого входа. * **Автономное размещение** в вашей собственной инфраструктуре [Узнайте больше](https://opencode.ai/docs/enterprise) об использовании opencode в вашей организации. --- # Condivisione | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/share#_top) Condivisione ============ Condividi le tue conversazioni OpenCode. La funzione di condivisione di OpenCode ti permette di creare link pubblici alle tue conversazioni, cosi puoi collaborare con i colleghi o chiedere aiuto ad altre persone. * * * [Come funziona](https://opencode.ai/docs/it/share#come-funziona) ----------------------------------------------------------------- Quando condividi una conversazione, OpenCode: 1. Crea un URL pubblico univoco per la sessione 2. Sincronizza la cronologia della conversazione sui nostri server 3. Rende la conversazione accessibile tramite il link condivisibile: `opncd.ai/s/` * * * [Condivisione](https://opencode.ai/docs/it/share#condivisione) --------------------------------------------------------------- OpenCode supporta tre modalita di condivisione che controllano come vengono condivise le conversazioni: * * * ### [Manuale (predefinito)](https://opencode.ai/docs/it/share#manuale-predefinito) Per impostazione predefinita, OpenCode usa la condivisione manuale. Le sessioni non vengono condivise automaticamente, ma puoi condividerle manualmente con il comando `/share`: /share Questo genera un URL univoco che viene copiato negli appunti. Per impostare esplicitamente la modalita manuale nel tuo [file di config](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "manual"} * * * ### [Automatico](https://opencode.ai/docs/it/share#automatico) Puoi abilitare la condivisione automatica per tutte le nuove conversazioni impostando l’opzione `share` su `"auto"` nel tuo [file di config](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "auto"} Con la condivisione automatica attiva, ogni nuova conversazione verra condivisa automaticamente e verra generato un link. * * * ### [Disabilitato](https://opencode.ai/docs/it/share#disabilitato) Puoi disabilitare completamente la condivisione impostando l’opzione `share` su `"disabled"` nel tuo [file di config](https://opencode.ai/docs/config) : { "$schema": "https://opencode.ai/config.json", "share": "disabled"} Per applicarlo al tuo team in un progetto specifico, aggiungilo a `opencode.json` nel progetto e versionalo su Git. * * * [Annullare la condivisione](https://opencode.ai/docs/it/share#annullare-la-condivisione) ----------------------------------------------------------------------------------------- Per smettere di condividere una conversazione e rimuoverla dall’accesso pubblico: /unshare Questo rimuove il link di condivisione ed elimina i dati associati alla conversazione. * * * [Privacy](https://opencode.ai/docs/it/share#privacy) ----------------------------------------------------- Ci sono alcune cose da tenere a mente quando condividi una conversazione. * * * ### [Conservazione dati](https://opencode.ai/docs/it/share#conservazione-dati) Le conversazioni condivise restano accessibili finche non le annulli esplicitamente. Questo include: * La cronologia completa della conversazione * Tutti i messaggi e le risposte * I metadati della sessione * * * ### [Raccomandazioni](https://opencode.ai/docs/it/share#raccomandazioni) * Condividi solo conversazioni che non contengono informazioni sensibili. * Rivedi il contenuto della conversazione prima di condividerla. * Annulla la condivisione quando la collaborazione e conclusa. * Evita di condividere conversazioni con codice proprietario o dati riservati. * Per progetti sensibili, disabilita completamente la condivisione. * * * [Per le aziende](https://opencode.ai/docs/it/share#per-le-aziende) ------------------------------------------------------------------- Per deploy enterprise, la condivisione puo essere: * **Disabilitata** completamente per requisiti di conformita e sicurezza * **Limitata** ai soli utenti autenticati tramite SSO * **Self-hosted** sulla tua infrastruttura [Scopri di piu](https://opencode.ai/docs/enterprise) su come usare opencode nella tua organizzazione. --- # 伺服器 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/server#_top) 伺服器 === 透過 HTTP 與 opencode 伺服器互動。 `opencode serve` 指令執行一個無介面的 HTTP 伺服器,暴露一個 OpenAPI 端點供 opencode 客戶端使用。 * * * ### [用法](https://opencode.ai/docs/zh-tw/server#%E7%94%A8%E6%B3%95) opencode serve [--port ] [--hostname ] [--cors ] #### [選項](https://opencode.ai/docs/zh-tw/server#%E9%81%B8%E9%A0%85) | 旗標 | 描述 | 預設 | | --- | --- | --- | | `--port` | 監聽連接埠 | `4096` | | `--hostname` | 監聽的主機名稱 | `127.0.0.1` | | `--mdns` | 啟用 mDNS 探索 | `false` | | `--mdns-domain` | mDNS 服務的自訂網域名稱 | `opencode.local` | | `--cors` | 額外允許的瀏覽器來源 | `[]` | `--cors` 可以多次傳遞: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [認證](https://opencode.ai/docs/zh-tw/server#%E8%AA%8D%E8%AD%89) 設定 `OPENCODE_SERVER_PASSWORD` 以使用 HTTP 基本認證保護伺服器。使用者名稱預設為 `opencode`,也可以設定 `OPENCODE_SERVER_USERNAME` 來覆蓋它。這適用於 `opencode serve` 和 `opencode web`。 OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [工作原理](https://opencode.ai/docs/zh-tw/server#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) 當你執行 `opencode` 時,它會啟動一個 TUI 和一個伺服器。TUI 是與伺服器通訊的客戶端。伺服器暴露一個 OpenAPI 3.1 規範端點。該端點也用於產生 [SDK](https://opencode.ai/docs/sdk) 。 這種架構讓 opencode 支援多個客戶端,並允許你以程式化方式與 opencode 互動。 你可以執行 `opencode serve` 來啟動一個獨立的伺服器。如果你已經在執行 opencode TUI,`opencode serve` 會啟動一個新的伺服器。 * * * #### [連接到現有伺服器](https://opencode.ai/docs/zh-tw/server#%E9%80%A3%E6%8E%A5%E5%88%B0%E7%8F%BE%E6%9C%89%E4%BC%BA%E6%9C%8D%E5%99%A8) 當你啟動 TUI 時,它會隨機分配連接埠和主機名稱。你也可以傳入 `--hostname` 和 `--port` [旗標](https://opencode.ai/docs/cli) ,然後用它來連接對應的伺服器。 [`/tui`](https://opencode.ai/docs/zh-tw/server#tui) 端點可用於透過伺服器驅動 TUI。例如,你可以預填充或執行一個提示詞。此方式被 OpenCode [IDE](https://opencode.ai/docs/ide) 外掛所使用。 * * * [規範](https://opencode.ai/docs/zh-tw/server#%E8%A6%8F%E7%AF%84) --------------------------------------------------------------- 伺服器發布了一個 OpenAPI 3.1 規範,可在以下位址查看: http://:/doc 例如,`http://localhost:4096/doc`。使用該規範可以產生客戶端或檢查請求和回應類型,也可以在 Swagger 瀏覽器中查看。 * * * [API](https://opencode.ai/docs/zh-tw/server#api) ------------------------------------------------- opencode 伺服器暴露以下 API。 * * * ### [全域](https://opencode.ai/docs/zh-tw/server#%E5%85%A8%E5%9F%9F) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/global/health` | 取得伺服器健康狀態和版本 | `{ healthy: true, version: string }` | | `GET` | `/global/event` | 取得全域事件(SSE 串流) | 事件串流 | * * * ### [專案](https://opencode.ai/docs/zh-tw/server#%E5%B0%88%E6%A1%88) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/project` | 列出所有專案 | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | 取得當前專案 | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [路徑和 VCS](https://opencode.ai/docs/zh-tw/server#%E8%B7%AF%E5%BE%91%E5%92%8C-vcs) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/path` | 取得當前路徑 | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | 取得當前專案的 VCS 資訊 | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [實例](https://opencode.ai/docs/zh-tw/server#%E5%AF%A6%E4%BE%8B) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | 銷毀當前實例 | `boolean` | * * * ### [設定](https://opencode.ai/docs/zh-tw/server#%E8%A8%AD%E5%AE%9A) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/config` | 取得設定資訊 | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | 更新設定 | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | 列出供應商和預設模型 | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [供應商](https://opencode.ai/docs/zh-tw/server#%E4%BE%9B%E6%87%89%E5%95%86) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/provider` | 列出所有供應商 | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | 取得供應商認證方式 | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | 使用 OAuth 授權供應商 | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | 處理供應商的 OAuth 回呼 | `boolean` | * * * ### [工作階段](https://opencode.ai/docs/zh-tw/server#%E5%B7%A5%E4%BD%9C%E9%9A%8E%E6%AE%B5) | 方法 | 路徑 | 描述 | 說明 | | --- | --- | --- | --- | | `GET` | `/session` | 列出所有工作階段 | 回傳 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | 建立新工作階段 | 請求主體:`{ parentID?, title? }`,回傳 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | 取得所有工作階段的狀態 | 回傳 `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | 取得工作階段詳情 | 回傳 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | 刪除工作階段及其所有資料 | 回傳 `boolean` | | `PATCH` | `/session/:id` | 更新工作階段屬性 | 請求主體:`{ title? }`,回傳 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | 取得工作階段的子工作階段 | 回傳 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | 取得工作階段的待辦事項清單 | 回傳 [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | 分析應用程式並建立 `AGENTS.md` | 請求主體:`{ messageID, providerID, modelID }`,回傳 `boolean` | | `POST` | `/session/:id/fork` | 在某條訊息處分岔現有工作階段 | 請求主體:`{ messageID? }`,回傳 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | 中止正在執行的工作階段 | 回傳 `boolean` | | `POST` | `/session/:id/share` | 分享工作階段 | 回傳 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | 取消分享工作階段 | 回傳 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | 取得本次工作階段的差異 | 查詢參數:`messageID?`,回傳 [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | 摘要工作階段 | 請求主體:`{ providerID, modelID }`,回傳 `boolean` | | `POST` | `/session/:id/revert` | 還原訊息 | 請求主體:`{ messageID, partID? }`,回傳 `boolean` | | `POST` | `/session/:id/unrevert` | 恢復所有已還原的訊息 | 回傳 `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | 回應權限請求 | 請求主體:`{ response, remember? }`,回傳 `boolean` | * * * ### [訊息](https://opencode.ai/docs/zh-tw/server#%E8%A8%8A%E6%81%AF) | 方法 | 路徑 | 描述 | 說明 | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | 列出工作階段中的訊息 | 查詢參數:`limit?`,回傳 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | 傳送訊息並等待回應 | 請求主體:`{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`,回傳 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | 取得訊息詳情 | 回傳 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | 非同步傳送訊息(不等待回應) | 請求主體:與 `/session/:id/message` 相同,回傳 `204 No Content` | | `POST` | `/session/:id/command` | 執行斜線指令 | 請求主體:`{ messageID?, agent?, model?, command, arguments }`,回傳 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | 執行 shell 指令 | 請求主體:`{ agent, model?, command }`,回傳 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [指令](https://opencode.ai/docs/zh-tw/server#%E6%8C%87%E4%BB%A4) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/command` | 列出所有指令 | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [檔案](https://opencode.ai/docs/zh-tw/server#%E6%AA%94%E6%A1%88) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | 在檔案中搜尋文字 | 包含 `path`、`lines`、`line_number`、`absolute_offset`、`submatches` 的匹配物件陣列 | | `GET` | `/find/file?query=` | 按名稱尋找檔案和目錄 | `string[]`(路徑) | | `GET` | `/find/symbol?query=` | 尋找工作區符號 | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | 列出檔案和目錄 | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | 讀取檔案 | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | 取得已追蹤檔案的狀態 | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` 查詢參數](https://opencode.ai/docs/zh-tw/server#findfile-%E6%9F%A5%E8%A9%A2%E5%8F%83%E6%95%B8) * `query`(必填)— 搜尋字串(模糊匹配) * `type`(選填)— 將結果限制為 `"file"` 或 `"directory"` * `directory`(選填)— 覆蓋搜尋的專案根目錄 * `limit`(選填)— 最大結果數(1–200) * `dirs`(選填)— 舊版旗標(`"false"` 僅回傳檔案) * * * ### [工具(實驗性)](https://opencode.ai/docs/zh-tw/server#%E5%B7%A5%E5%85%B7%E5%AF%A6%E9%A9%97%E6%80%A7) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | 列出所有工具 ID | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | 列出指定模型的工具及其 JSON Schema | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP、格式化工具和 MCP](https://opencode.ai/docs/zh-tw/server#lsp%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%B7%A5%E5%85%B7%E5%92%8C-mcp) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/lsp` | 取得 LSP 伺服器狀態 | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | 取得格式化工具狀態 | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | 取得 MCP 伺服器狀態 | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | 動態新增 MCP 伺服器 | 請求主體:`{ name, config }`,回傳 MCP 狀態物件 | * * * ### [代理](https://opencode.ai/docs/zh-tw/server#%E4%BB%A3%E7%90%86) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/agent` | 列出所有可用的代理 | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [日誌](https://opencode.ai/docs/zh-tw/server#%E6%97%A5%E8%AA%8C) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `POST` | `/log` | 寫入日誌項目。請求主體:`{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/zh-tw/server#tui) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | 向提示詞附加文字 | `boolean` | | `POST` | `/tui/open-help` | 開啟說明對話框 | `boolean` | | `POST` | `/tui/open-sessions` | 開啟工作階段選擇器 | `boolean` | | `POST` | `/tui/open-themes` | 開啟主題選擇器 | `boolean` | | `POST` | `/tui/open-models` | 開啟模型選擇器 | `boolean` | | `POST` | `/tui/submit-prompt` | 提交當前提示詞 | `boolean` | | `POST` | `/tui/clear-prompt` | 清除提示詞 | `boolean` | | `POST` | `/tui/execute-command` | 執行指令(`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | 顯示提示訊息(`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | 等待下一個控制請求 | 控制請求物件 | | `POST` | `/tui/control/response` | 回應控制請求(`{ body }`) | `boolean` | * * * ### [認證](https://opencode.ai/docs/zh-tw/server#%E8%AA%8D%E8%AD%89-1) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | 設定認證憑證。請求主體必須匹配供應商的資料結構 | `boolean` | * * * ### [事件](https://opencode.ai/docs/zh-tw/server#%E4%BA%8B%E4%BB%B6) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/event` | 伺服器傳送事件串流。第一個事件是 `server.connected`,之後是匯流排事件 | 伺服器傳送事件串流 | * * * ### [文件](https://opencode.ai/docs/zh-tw/server#%E6%96%87%E4%BB%B6) | 方法 | 路徑 | 描述 | 回應 | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1 規範 | 包含 OpenAPI 規範的 HTML 頁面 | --- # Formatters | OpenCode [Skip to content](https://opencode.ai/docs/formatters#_top) Formatters ========== OpenCode uses language specific formatters. OpenCode automatically formats files after they are written or edited using language-specific formatters. This ensures that the code that is generated follows the code styles of your project. * * * [Built-in](https://opencode.ai/docs/formatters#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](https://biomejs.dev/) | `biome.json(c)` config file | | cargofmt | .rs | `cargo fmt` command available | | clang-format | .c, .cpp, .h, .hpp, .ino, and [more](https://clang.llvm.org/docs/ClangFormat.html) | `.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](https://opencode.ai/docs/cli/#experimental) | | pint | .php | `laravel/pint` dependency in `composer.json` | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://prettier.io/docs/en/index.html) | `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 | So if your project has `prettier` in your `package.json`, OpenCode will automatically use it. * * * [How it works](https://opencode.ai/docs/formatters#how-it-works) ----------------------------------------------------------------- When OpenCode writes or edits a file, it: 1. Checks the file extension against all enabled formatters. 2. Runs the appropriate formatter command on the file. 3. Applies the formatting changes automatically. This process happens in the background, ensuring your code styles are maintained without any manual steps. * * * [Configure](https://opencode.ai/docs/formatters#configure) ----------------------------------------------------------- You can customize formatters through the `formatter` section in your OpenCode config. { "$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 | | `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](https://opencode.ai/docs/formatters#disabling-formatters) To disable **all** formatters globally, set `formatter` to `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} To disable a **specific** formatter, set `disabled` to `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Custom formatters](https://opencode.ai/docs/formatters#custom-formatters) You can override the built-in formatters or add new ones by specifying the command, environment variables, and file extensions: { "$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. --- # 服务器 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/server#_top) 服务器 === 通过 HTTP 与 opencode 服务器交互。 `opencode serve` 命令运行一个无界面的 HTTP 服务器,暴露一个 OpenAPI 端点供 opencode 客户端使用。 * * * ### [用法](https://opencode.ai/docs/zh-cn/server#%E7%94%A8%E6%B3%95) opencode serve [--port ] [--hostname ] [--cors ] #### [选项](https://opencode.ai/docs/zh-cn/server#%E9%80%89%E9%A1%B9) | 标志 | 描述 | 默认值 | | --- | --- | --- | | `--port` | 监听端口 | `4096` | | `--hostname` | 监听的主机名 | `127.0.0.1` | | `--mdns` | 启用 mDNS 发现 | `false` | | `--mdns-domain` | mDNS 服务的自定义域名 | `opencode.local` | | `--cors` | 额外允许的浏览器来源 | `[]` | `--cors` 可以多次传递: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [认证](https://opencode.ai/docs/zh-cn/server#%E8%AE%A4%E8%AF%81) 设置 `OPENCODE_SERVER_PASSWORD` 以使用 HTTP 基本认证保护服务器。用户名默认为 `opencode`,也可以设置 `OPENCODE_SERVER_USERNAME` 来覆盖它。这适用于 `opencode serve` 和 `opencode web`。 OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [工作原理](https://opencode.ai/docs/zh-cn/server#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) 当你运行 `opencode` 时,它会启动一个 TUI 和一个服务器。TUI 是与服务器通信的客户端。服务器暴露一个 OpenAPI 3.1 规范端点。该端点也用于生成 [SDK](https://opencode.ai/docs/sdk) 。 这种架构让 opencode 支持多个客户端,并允许你以编程方式与 opencode 交互。 你可以运行 `opencode serve` 来启动一个独立的服务器。如果你已经在运行 opencode TUI,`opencode serve` 会启动一个新的服务器。 * * * #### [连接到现有服务器](https://opencode.ai/docs/zh-cn/server#%E8%BF%9E%E6%8E%A5%E5%88%B0%E7%8E%B0%E6%9C%89%E6%9C%8D%E5%8A%A1%E5%99%A8) 当你启动 TUI 时,它会随机分配端口和主机名。你也可以传入 `--hostname` 和 `--port` [标志](https://opencode.ai/docs/cli) ,然后用它来连接对应的服务器。 [`/tui`](https://opencode.ai/docs/zh-cn/server#tui) 端点可用于通过服务器驱动 TUI。例如,你可以预填充或运行一个提示词。此方式被 OpenCode [IDE](https://opencode.ai/docs/ide) 插件所使用。 * * * [规范](https://opencode.ai/docs/zh-cn/server#%E8%A7%84%E8%8C%83) --------------------------------------------------------------- 服务器发布了一个 OpenAPI 3.1 规范,可在以下地址查看: http://:/doc 例如,`http://localhost:4096/doc`。使用该规范可以生成客户端或检查请求和响应类型,也可以在 Swagger 浏览器中查看。 * * * [API](https://opencode.ai/docs/zh-cn/server#api) ------------------------------------------------- opencode 服务器暴露以下 API。 * * * ### [全局](https://opencode.ai/docs/zh-cn/server#%E5%85%A8%E5%B1%80) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/global/health` | 获取服务器健康状态和版本 | `{ healthy: true, version: string }` | | `GET` | `/global/event` | 获取全局事件(SSE 流) | 事件流 | * * * ### [项目](https://opencode.ai/docs/zh-cn/server#%E9%A1%B9%E7%9B%AE) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/project` | 列出所有项目 | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | 获取当前项目 | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [路径和 VCS](https://opencode.ai/docs/zh-cn/server#%E8%B7%AF%E5%BE%84%E5%92%8C-vcs) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/path` | 获取当前路径 | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | 获取当前项目的 VCS 信息 | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [实例](https://opencode.ai/docs/zh-cn/server#%E5%AE%9E%E4%BE%8B) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | 销毁当前实例 | `boolean` | * * * ### [配置](https://opencode.ai/docs/zh-cn/server#%E9%85%8D%E7%BD%AE) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/config` | 获取配置信息 | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | 更新配置 | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | 列出提供商和默认模型 | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [提供商](https://opencode.ai/docs/zh-cn/server#%E6%8F%90%E4%BE%9B%E5%95%86) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/provider` | 列出所有提供商 | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | 获取提供商认证方式 | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | 使用 OAuth 授权提供商 | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | 处理提供商的 OAuth 回调 | `boolean` | * * * ### [会话](https://opencode.ai/docs/zh-cn/server#%E4%BC%9A%E8%AF%9D) | 方法 | 路径 | 描述 | 说明 | | --- | --- | --- | --- | | `GET` | `/session` | 列出所有会话 | 返回 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | 创建新会话 | 请求体:`{ parentID?, title? }`,返回 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | 获取所有会话的状态 | 返回 `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | 获取会话详情 | 返回 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | 删除会话及其所有数据 | 返回 `boolean` | | `PATCH` | `/session/:id` | 更新会话属性 | 请求体:`{ title? }`,返回 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | 获取会话的子会话 | 返回 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | 获取会话的待办事项列表 | 返回 [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | 分析应用并创建 `AGENTS.md` | 请求体:`{ messageID, providerID, modelID }`,返回 `boolean` | | `POST` | `/session/:id/fork` | 在某条消息处分叉现有会话 | 请求体:`{ messageID? }`,返回 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | 中止正在运行的会话 | 返回 `boolean` | | `POST` | `/session/:id/share` | 分享会话 | 返回 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | 取消分享会话 | 返回 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | 获取本次会话的差异 | 查询参数:`messageID?`,返回 [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | 总结会话 | 请求体:`{ providerID, modelID }`,返回 `boolean` | | `POST` | `/session/:id/revert` | 回退消息 | 请求体:`{ messageID, partID? }`,返回 `boolean` | | `POST` | `/session/:id/unrevert` | 恢复所有已回退的消息 | 返回 `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | 响应权限请求 | 请求体:`{ response, remember? }`,返回 `boolean` | * * * ### [消息](https://opencode.ai/docs/zh-cn/server#%E6%B6%88%E6%81%AF) | 方法 | 路径 | 描述 | 说明 | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | 列出会话中的消息 | 查询参数:`limit?`,返回 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | 发送消息并等待响应 | 请求体:`{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`,返回 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | 获取消息详情 | 返回 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | 异步发送消息(不等待响应) | 请求体:与 `/session/:id/message` 相同,返回 `204 No Content` | | `POST` | `/session/:id/command` | 执行斜杠命令 | 请求体:`{ messageID?, agent?, model?, command, arguments }`,返回 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | 运行 shell 命令 | 请求体:`{ agent, model?, command }`,返回 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [命令](https://opencode.ai/docs/zh-cn/server#%E5%91%BD%E4%BB%A4) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/command` | 列出所有命令 | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [文件](https://opencode.ai/docs/zh-cn/server#%E6%96%87%E4%BB%B6) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | 在文件中搜索文本 | 包含 `path`、`lines`、`line_number`、`absolute_offset`、`submatches` 的匹配对象数组 | | `GET` | `/find/file?query=` | 按名称查找文件和目录 | `string[]`(路径) | | `GET` | `/find/symbol?query=` | 查找工作区符号 | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | 列出文件和目录 | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | 读取文件 | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | 获取已跟踪文件的状态 | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` 查询参数](https://opencode.ai/docs/zh-cn/server#findfile-%E6%9F%A5%E8%AF%A2%E5%8F%82%E6%95%B0) * `query`(必需)— 搜索字符串(模糊匹配) * `type`(可选)— 将结果限制为 `"file"` 或 `"directory"` * `directory`(可选)— 覆盖搜索的项目根目录 * `limit`(可选)— 最大结果数(1–200) * `dirs`(可选)— 旧版标志(`"false"` 仅返回文件) * * * ### [工具(实验性)](https://opencode.ai/docs/zh-cn/server#%E5%B7%A5%E5%85%B7%E5%AE%9E%E9%AA%8C%E6%80%A7) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | 列出所有工具 ID | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | 列出指定模型的工具及其 JSON Schema | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP、格式化器和 MCP](https://opencode.ai/docs/zh-cn/server#lsp%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%99%A8%E5%92%8C-mcp) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/lsp` | 获取 LSP 服务器状态 | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | 获取格式化器状态 | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | 获取 MCP 服务器状态 | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | 动态添加 MCP 服务器 | 请求体:`{ name, config }`,返回 MCP 状态对象 | * * * ### [代理](https://opencode.ai/docs/zh-cn/server#%E4%BB%A3%E7%90%86) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/agent` | 列出所有可用的代理 | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [日志](https://opencode.ai/docs/zh-cn/server#%E6%97%A5%E5%BF%97) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `POST` | `/log` | 写入日志条目。请求体:`{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/zh-cn/server#tui) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | 向提示词追加文本 | `boolean` | | `POST` | `/tui/open-help` | 打开帮助对话框 | `boolean` | | `POST` | `/tui/open-sessions` | 打开会话选择器 | `boolean` | | `POST` | `/tui/open-themes` | 打开主题选择器 | `boolean` | | `POST` | `/tui/open-models` | 打开模型选择器 | `boolean` | | `POST` | `/tui/submit-prompt` | 提交当前提示词 | `boolean` | | `POST` | `/tui/clear-prompt` | 清除提示词 | `boolean` | | `POST` | `/tui/execute-command` | 执行命令(`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | 显示提示消息(`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | 等待下一个控制请求 | 控制请求对象 | | `POST` | `/tui/control/response` | 响应控制请求(`{ body }`) | `boolean` | * * * ### [认证](https://opencode.ai/docs/zh-cn/server#%E8%AE%A4%E8%AF%81-1) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | 设置认证凭据。请求体必须匹配提供商的数据结构 | `boolean` | * * * ### [事件](https://opencode.ai/docs/zh-cn/server#%E4%BA%8B%E4%BB%B6) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/event` | 服务器发送事件流。第一个事件是 `server.connected`,之后是总线事件 | 服务器发送事件流 | * * * ### [文档](https://opencode.ai/docs/zh-cn/server#%E6%96%87%E6%A1%A3) | 方法 | 路径 | 描述 | 响应 | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1 规范 | 包含 OpenAPI 规范的 HTML 页面 | --- # 서버 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/server#_top) 서버 == HTTP를 통해 OpenCode 서버와 상호 작용합니다. `opencode serve` 명령은 opencode 클라이언트가 사용할 수 있는 OpenAPI 엔드포인트를 노출하는 headless HTTP 서버를 실행합니다. * * * ### [사용법](https://opencode.ai/docs/ko/server#%EC%82%AC%EC%9A%A9%EB%B2%95) opencode serve [--port ] [--hostname ] [--cors ] #### [옵션](https://opencode.ai/docs/ko/server#%EC%98%B5%EC%85%98) | 플래그 | 설명 | 기본값 | | --- | --- | --- | | `--port` | 수신 대기할 포트 | `4096` | | `--hostname` | 수신 대기할 호스트명 | `127.0.0.1` | | `--mdns` | mDNS 탐지 활성화 | `false` | | `--mdns-domain` | mDNS 서비스의 사용자 지정 도메인 이름 | `opencode.local` | | `--cors` | 허용할 추가 브라우저 origin | `[]` | `--cors`는 다수 시간을 통과될 수 있습니다: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [인증](https://opencode.ai/docs/ko/server#%EC%9D%B8%EC%A6%9D) `OPENCODE_SERVER_PASSWORD`를 설정하여 서버를 HTTP Basic auth로 보호합니다. `opencode` 또는 `OPENCODE_SERVER_USERNAME`를 오버라이드로 설정하는 사용자의 기본값. 이것은 `opencode serve`와 `opencode web` 둘 다에 적용합니다. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [작동 방식](https://opencode.ai/docs/ko/server#%EC%9E%91%EB%8F%99-%EB%B0%A9%EC%8B%9D) `opencode`를 실행하면 TUI와 서버를 시작합니다. TUI는 어디에 있습니까? 서버와 대화하는 클라이언트. 서버는 OpenAPI 3.1 spec을 노출 끝점. 이 엔드포인트는 [SDK](https://opencode.ai/docs/sdk) 을 생성하는 데도 사용됩니다. 이 아키텍처는 opencode 지원 여러 클라이언트를 허용하고 opencode programmatically와 상호 작용 할 수 있습니다. 독립 서버를 시작하려면 `opencode serve`를 실행할 수 있습니다. 당신이 있는 경우에 opencode TUI 실행, `opencode serve` 새로운 서버를 시작합니다. * * * #### [기존 서버에 연결](https://opencode.ai/docs/ko/server#%EA%B8%B0%EC%A1%B4-%EC%84%9C%EB%B2%84%EC%97%90-%EC%97%B0%EA%B2%B0) TUI를 시작하면 무작위로 포트와 호스트 이름을 할당합니다. 대신 `--hostname`와 `--port` [flags](https://opencode.ai/docs/cli) 에서 전달할 수 있습니다. 그런 다음 서버에 연결하십시오. [`/tui`](https://opencode.ai/docs/ko/server#tui) 엔드포인트는 서버를 통해 TUI를 구동하는 데 사용될 수 있습니다. 예를 들어 미리 작성하거나 프롬프트를 실행할 수 있습니다. 이 설정은 opencode [IDE](https://opencode.ai/docs/ide) 플러그인에 의해 사용됩니다. * * * [사양](https://opencode.ai/docs/ko/server#%EC%82%AC%EC%96%91) ------------------------------------------------------------ 서버는 OpenAPI 3.1 spec을 게시합니다. http://:/doc 예를 들어, `http://localhost:4096/doc`. 클라이언트를 생성하거나 요청 및 응답 유형을 검사하는 spec를 사용하십시오. 또는 Swagger 탐험가에서 볼 수 있습니다. * * * [API](https://opencode.ai/docs/ko/server#api) ---------------------------------------------- opencode 서버는 다음과 같은 API를 노출합니다. * * * [글로벌](https://opencode.ai/docs/ko/server#%EA%B8%80%EB%A1%9C%EB%B2%8C) ---------------------------------------------------------------------- | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/global/health` | 서버 건강 및 버전 | `{ healthy: true, version: string }` | | `GET` | `/global/event` | 글로벌 이벤트(SSE 스트림) | 이벤트 스트림 | * * * [프로젝트](https://opencode.ai/docs/ko/server#%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8) -------------------------------------------------------------------------------- | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/project` | 모든 프로젝트 보기 | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | 현재 프로젝트 가져 오기 | [`프로젝트`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [경로 & VCS](https://opencode.ai/docs/ko/server#%EA%B2%BD%EB%A1%9C--vcs) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/path` | 현재 경로 받기 | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | 현재 프로젝트의 VCS 정보 받기 | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [인스턴스](https://opencode.ai/docs/ko/server#%EC%9D%B8%EC%8A%A4%ED%84%B4%EC%8A%A4) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | 현재 인스턴스를 해제 | `boolean` | * * * ### [구성](https://opencode.ai/docs/ko/server#%EA%B5%AC%EC%84%B1) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/config` | 구성정보 | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | 업데이트 구성 | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | 목록 제공업체 및 기본 모델 | `{ providers:` [사이트 맵](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * [공급자](https://opencode.ai/docs/ko/server#%EA%B3%B5%EA%B8%89%EC%9E%90) ---------------------------------------------------------------------- | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/provider` | 모든 공급자 목록 | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | 공급자 인증 메서드 가져오기 | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | OAuth를 사용한 공급자 허가 | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | 공급자를 위한 OAuth 콜백 | `boolean` | * * * [세션](https://opencode.ai/docs/ko/server#%EC%84%B8%EC%85%98) ------------------------------------------------------------ | 메서드 | 경로 | 설명 | 비고 | | --- | --- | --- | --- | | `GET` | `/session` | 모든 세션 일람표 | 반환 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | 새 세션 만들기 | 몸: `{ parentID?, title? }`, 반환 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | 모든 세션의 세션 상태를 가져옵니다 | `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | 세션 상세보기 | 반품 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | 세션 삭제 및 모든 데이터 | `boolean` | | `PATCH` | `/session/:id` | 업데이트 세션 속성 | 본체: `{ title? }`, 반환 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | 세션의 하위 세션 | 리턴 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | 세션의 할 일(Todo) 목록 받기 | [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | 앱 초기화 및 `AGENTS.md` 분석 | 몸: `{ messageID, providerID, modelID }`, 반환 `boolean` | | `POST` | `/session/:id/fork` | 메시지의 기존 세션 | 몸: `{ messageID? }`, 반환 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | 운영 중인 세션 | 반품 `boolean` | | `POST` | `/session/:id/share` | 세션 공유 | [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | 세션 공유 | [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | `/session/:id/diff` | `messageID?`, 반환 [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | 세션을 요약 | 본체: `{ providerID, modelID }`, `boolean` 반환 | | `POST` | `/session/:id/revert` | 메시지 재생 | 몸: `{ messageID, partID? }`, 반환 `boolean` | | `POST` | `/session/:id/unrevert` | 메시지 되돌리기 취소 | 반품 `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | 허가 요청 대응 | 본체: `{ response, remember? }`, `boolean` | * * * [메시지](https://opencode.ai/docs/ko/server#%EB%A9%94%EC%8B%9C%EC%A7%80) ---------------------------------------------------------------------- | 방법 | 경로 | 설명 | 주 | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | 세션의 목록 메시지 | 쿼리: `limit?`, `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | 응답을 위해 메시지를 보내고 기다립니다 | 몸: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, 반환 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | 메시지 보내기 | `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | 비동기적으로 메시지 보내기 | 몸: `/session/:id/message`와 동일, `204 No Content`를 반환 | | `POST` | `/session/:id/command` | 슬래시 명령어 실행 | 본체: `{ messageID?, agent?, model?, command, arguments }`, 반환 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | shell 명령 실행 | 체: `{ agent, model?, command }`, 반환 `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * [명령](https://opencode.ai/docs/ko/server#%EB%AA%85%EB%A0%B9) ------------------------------------------------------------ | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/command` | 모든 명령 | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * [파일](https://opencode.ai/docs/ko/server#%ED%8C%8C%EC%9D%BC) ------------------------------------------------------------ | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | 파일에서 텍스트 검색 | `path`, `lines`, `line_number`, `absolute_offset`, `submatches`가 포함된 일치 객체 배열 | | `GET` | `/find/file?query=` | 이름으로 파일/디렉터리 찾기 | `string[]` (경로) | | `GET` | `/find/symbol?query=` | 워크스페이스 심볼 찾기 | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | 파일 및 디렉터리 목록 | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | 파일 읽기 | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | 추적 중인 파일 상태 가져오기 | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` 쿼리 매개 변수](https://opencode.ai/docs/ko/server#findfile-%EC%BF%BC%EB%A6%AC-%EB%A7%A4%EA%B0%9C-%EB%B3%80%EC%88%98) * `query` (required) - 검색 문자열 (fuzzy 일치) * `type` (선택 사항) - `"file"` 또는 `"directory"`에 제한 결과 * `directory` (선택 사항) - 검색에 대한 프로젝트 루트를 무시 * (선택) `limit` - 최대 결과 (1-200) * `dirs` (옵션) - 레거시 플래그 (`"false"`는 파일만 반환) * * * [도구 (실험적)](https://opencode.ai/docs/ko/server#%EB%8F%84%EA%B5%AC-%EC%8B%A4%ED%97%98%EC%A0%81) ---------------------------------------------------------------------------------------------- | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | 모든 도구 ID | [`도구`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | 모델용 JSON 스키마 목록 | [`도구 목록`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, 포매터 & MCP](https://opencode.ai/docs/ko/server#lsp-%ED%8F%AC%EB%A7%A4%ED%84%B0--mcp) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/lsp` | LSP 서버 상태 | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | 형식의 상태를 확인 | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | MCP 서버 상태를 얻는다 | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | MCP 서버가 동적 | 본체: `{ name, config }`, MCP 상태 객체를 반환 | * * * [에이전트](https://opencode.ai/docs/ko/server#%EC%97%90%EC%9D%B4%EC%A0%84%ED%8A%B8) -------------------------------------------------------------------------------- | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/agent` | 이용 가능한 모든 에이전트 | [`에이전트[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [로깅](https://opencode.ai/docs/ko/server#%EB%A1%9C%EA%B9%85) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `POST` | `/log` | 로그 입력 바디: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/ko/server#tui) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | 프롬프트에 텍스트를 부여 | `boolean` | | `POST` | `/tui/open-help` | 도움말 대화 열기 | `boolean` | | `POST` | `/tui/open-sessions` | 세션 선택 안내 | `boolean` | | `POST` | `/tui/open-themes` | 테마 선택 안내 | `boolean` | | `POST` | `/tui/open-models` | 모델 선택 안내 | `boolean` | | `POST` | `/tui/submit-prompt` | 현재 프롬프트 제출 | `boolean` | | `POST` | `/tui/clear-prompt` | 시프트 클리어 | `boolean` | | `POST` | `/tui/execute-command` | 명령어 실행(`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | 쇼 토스트(`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | 다음 컨트롤 요청 시 기다리고 | 제어 요청 개체 | | `POST` | `/tui/control/response` | 통제 요청(`{ body }`) 대응 | `boolean` | * * * ### [인증](https://opencode.ai/docs/ko/server#%EC%9D%B8%EC%A6%9D-1) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | 인증 자격 증명 몸은 공급자 스키마를 일치해야 합니다 | `boolean` | * * * [이벤트](https://opencode.ai/docs/ko/server#%EC%9D%B4%EB%B2%A4%ED%8A%B8) ---------------------------------------------------------------------- | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/event` | 서버 전송 이벤트 스트림. 첫 번째 이벤트는 `server.connected`, 그 후 버스 이벤트 | Server-sent event stream | * * * ### [문서](https://opencode.ai/docs/ko/server#%EB%AC%B8%EC%84%9C) | 방법 | 경로 | 설명 | 응답 | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1 사양 | HTML 페이지 OpenAPI 사양 | --- # Server | OpenCode [Skip to content](https://opencode.ai/docs/server#_top) Server ====== Interact with opencode server over HTTP. The `opencode serve` command runs a headless HTTP server that exposes an OpenAPI endpoint that an opencode client can use. * * * ### [Usage](https://opencode.ai/docs/server#usage) opencode serve [--port ] [--hostname ] [--cors ] #### [Options](https://opencode.ai/docs/server#options) | Flag | Description | Default | | --- | --- | --- | | `--port` | Port to listen on | `4096` | | `--hostname` | Hostname to listen on | `127.0.0.1` | | `--mdns` | Enable mDNS discovery | `false` | | `--mdns-domain` | Custom domain name for mDNS service | `opencode.local` | | `--cors` | Additional browser origins to allow | `[]` | `--cors` can be passed multiple times: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Authentication](https://opencode.ai/docs/server#authentication) Set `OPENCODE_SERVER_PASSWORD` to protect the server with HTTP basic auth. The username defaults to `opencode`, or set `OPENCODE_SERVER_USERNAME` to override it. This applies to both `opencode serve` and `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [How it works](https://opencode.ai/docs/server#how-it-works) When you run `opencode` it starts a TUI and a server. Where the TUI is the client that talks to the server. The server exposes an OpenAPI 3.1 spec endpoint. This endpoint is also used to generate an [SDK](https://opencode.ai/docs/sdk) . This architecture lets opencode support multiple clients and allows you to interact with opencode programmatically. You can run `opencode serve` to start a standalone server. If you have the opencode TUI running, `opencode serve` will start a new server. * * * #### [Connect to an existing server](https://opencode.ai/docs/server#connect-to-an-existing-server) When you start the TUI it randomly assigns a port and hostname. You can instead pass in the `--hostname` and `--port` [flags](https://opencode.ai/docs/cli) . Then use this to connect to its server. The [`/tui`](https://opencode.ai/docs/server#tui) endpoint can be used to drive the TUI through the server. For example, you can prefill or run a prompt. This setup is used by the OpenCode [IDE](https://opencode.ai/docs/ide) plugins. * * * [Spec](https://opencode.ai/docs/server#spec) --------------------------------------------- The server publishes an OpenAPI 3.1 spec that can be viewed at: http://:/doc For example, `http://localhost:4096/doc`. Use the spec to generate clients or inspect request and response types. Or view it in a Swagger explorer. * * * [APIs](https://opencode.ai/docs/server#apis) --------------------------------------------- The opencode server exposes the following APIs. * * * ### [Global](https://opencode.ai/docs/server#global) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/global/health` | Get server health and version | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Get global events (SSE stream) | Event stream | * * * ### [Project](https://opencode.ai/docs/server#project) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/project` | List all projects | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Get the current project | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Path & VCS](https://opencode.ai/docs/server#path--vcs) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/path` | Get the current path | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Get VCS info for the current project | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Instance](https://opencode.ai/docs/server#instance) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Dispose the current instance | `boolean` | * * * ### [Config](https://opencode.ai/docs/server#config) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/config` | Get config info | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Update config | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | List providers and default models | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Provider](https://opencode.ai/docs/server#provider) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/provider` | List all providers | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Get provider authentication methods | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Authorize a provider using OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Handle OAuth callback for a provider | `boolean` | * * * ### [Sessions](https://opencode.ai/docs/server#sessions) | Method | Path | Description | Notes | | --- | --- | --- | --- | | `GET` | `/session` | List all sessions | Returns [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Create a new session | body: `{ parentID?, title? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Get session status for all sessions | Returns `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Get session details | Returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Delete a session and all its data | Returns `boolean` | | `PATCH` | `/session/:id` | Update session properties | body: `{ title? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Get a session’s child sessions | Returns [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Get the todo list for a session | Returns [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Analyze app and create `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | | `POST` | `/session/:id/fork` | Fork an existing session at a message | body: `{ messageID? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Abort a running session | Returns `boolean` | | `POST` | `/session/:id/share` | Share a session | Returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Unshare a session | Returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Get the diff for this session | query: `messageID?`, returns [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Summarize the session | body: `{ providerID, modelID }`, returns `boolean` | | `POST` | `/session/:id/revert` | Revert a message | body: `{ messageID, partID? }`, returns `boolean` | | `POST` | `/session/:id/unrevert` | Restore all reverted messages | Returns `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Respond to a permission request | body: `{ response, remember? }`, returns `boolean` | * * * ### [Messages](https://opencode.ai/docs/server#messages) | Method | Path | Description | Notes | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | List messages in a session | query: `limit?`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Send a message and wait for response | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Get message details | Returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Send a message asynchronously (no wait) | body: same as `/session/:id/message`, returns `204 No Content` | | `POST` | `/session/:id/command` | Execute a slash command | body: `{ messageID?, agent?, model?, command, arguments }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Run a shell command | body: `{ agent, model?, command }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Commands](https://opencode.ai/docs/server#commands) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/command` | List all commands | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Files](https://opencode.ai/docs/server#files) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Find files and directories by name | `string[]` (paths) | | `GET` | `/find/symbol?query=` | Find workspace symbols | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | List files and directories | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Read a file | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Get status for tracked files | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` query parameters](https://opencode.ai/docs/server#findfile-query-parameters) * `query` (required) — search string (fuzzy match) * `type` (optional) — limit results to `"file"` or `"directory"` * `directory` (optional) — override the project root for the search * `limit` (optional) — max results (1–200) * `dirs` (optional) — legacy flag (`"false"` returns only files) * * * ### [Tools (Experimental)](https://opencode.ai/docs/server#tools-experimental) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | List all tool IDs | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | List tools with JSON schemas for a model | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, Formatters & MCP](https://opencode.ai/docs/server#lsp-formatters--mcp) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/lsp` | Get LSP server status | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Get formatter status | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Get MCP server status | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Add MCP server dynamically | body: `{ name, config }`, returns MCP status object | * * * ### [Agents](https://opencode.ai/docs/server#agents) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/agent` | List all available agents | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Logging](https://opencode.ai/docs/server#logging) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/server#tui) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Append text to the prompt | `boolean` | | `POST` | `/tui/open-help` | Open the help dialog | `boolean` | | `POST` | `/tui/open-sessions` | Open the session selector | `boolean` | | `POST` | `/tui/open-themes` | Open the theme selector | `boolean` | | `POST` | `/tui/open-models` | Open the model selector | `boolean` | | `POST` | `/tui/submit-prompt` | Submit the current prompt | `boolean` | | `POST` | `/tui/clear-prompt` | Clear the prompt | `boolean` | | `POST` | `/tui/execute-command` | Execute a command (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Show toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Wait for the next control request | Control request object | | `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | * * * ### [Auth](https://opencode.ai/docs/server#auth) | Method | Path | Description | Response | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Set authentication credentials. Body must match provider schema | `boolean` | * * * ### [Events](https://opencode.ai/docs/server#events) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/event` | Server-sent events stream. First event is `server.connected`, then bus events | Server-sent events stream | * * * ### [Docs](https://opencode.ai/docs/server#docs) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1 specification | HTML page with OpenAPI spec | --- # Server | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/server#_top) Server ====== Nutze den opencode-Server ueber HTTP. Der Befehl `opencode serve` startet einen headless HTTP-Server. Er stellt einen OpenAPI-Endpunkt bereit, den ein opencode-Client nutzen kann. * * * ### [Nutzung](https://opencode.ai/docs/de/server#nutzung) opencode serve [--port ] [--hostname ] [--cors ] #### [Optionen](https://opencode.ai/docs/de/server#optionen) | Flag | Description | Default | | --- | --- | --- | | `--port` | Port to listen on | `4096` | | `--hostname` | Hostname to listen on | `127.0.0.1` | | `--mdns` | Enable mDNS discovery | `false` | | `--mdns-domain` | Custom domain name for mDNS service | `opencode.local` | | `--cors` | Additional browser origins to allow | `[]` | `--cors` kann mehrfach angegeben werden: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Authentifizierung](https://opencode.ai/docs/de/server#authentifizierung) Setze `OPENCODE_SERVER_PASSWORD`, um den Server mit HTTP Basic Auth zu schuetzen. Der Benutzername ist standardmaessig `opencode`, kann aber mit `OPENCODE_SERVER_USERNAME` ueberschrieben werden. Das gilt fuer `opencode serve` und `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Funktionsweise](https://opencode.ai/docs/de/server#funktionsweise) Wenn du `opencode` startest, werden TUI und Server gestartet. Die TUI ist dabei der Client, der mit dem Server spricht; dessen OpenAPI-3.1-Endpunkt dient auch zur Generierung des [SDK](https://opencode.ai/docs/sdk) . Diese Architektur erlaubt mehrere Clients und programmatische Nutzung. Mit `opencode serve` startest du einen eigenstaendigen Server. Laeuft bereits eine TUI, startet `opencode serve` trotzdem eine neue Serverinstanz. * * * #### [Mit bestehendem Server verbinden](https://opencode.ai/docs/de/server#mit-bestehendem-server-verbinden) Beim TUI-Start werden Port und Hostname zufaellig gewaehlt. Alternativ gibst du `--hostname` und `--port` als [Flags](https://opencode.ai/docs/cli) vor und verbindest dich dann gezielt damit. Der Endpunkt [`/tui`](https://opencode.ai/docs/de/server#tui) kann die TUI ueber den Server steuern, etwa zum Vorbelegen oder Abschicken von Prompts. Dieses Muster nutzen auch die OpenCode-[IDE](https://opencode.ai/docs/ide) \-Plugins. * * * [Spec](https://opencode.ai/docs/de/server#spec) ------------------------------------------------ Der Server veroeffentlicht eine OpenAPI-3.1-Spezifikation unter: http://:/doc Zum Beispiel `http://localhost:4096/doc`. Nutze die Spec zum Generieren von Clients, zum Pruefen von Request/Response-Typen oder in einem Swagger-Explorer. * * * [APIs](https://opencode.ai/docs/de/server#apis) ------------------------------------------------ Der opencode-Server stellt folgende APIs bereit. * * * ### [Global](https://opencode.ai/docs/de/server#global) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/global/health` | Ruft Server-Status und Version ab | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Ruft globale Events ab (SSE-Stream) | Event stream | * * * ### [Project](https://opencode.ai/docs/de/server#project) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/project` | Listet alle Projekte | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Ruft das aktuelle Projekt ab | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Path & VCS](https://opencode.ai/docs/de/server#path--vcs) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/path` | Ruft den aktuellen Pfad ab | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Ruft VCS-Infos fuer das aktuelle Projekt ab | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Instanz](https://opencode.ai/docs/de/server#instanz) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Beendet die aktuelle Instanz | `boolean` | * * * ### [Konfiguration](https://opencode.ai/docs/de/server#konfiguration) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/config` | Ruft Konfigurationsinfos ab | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Aktualisiert Konfiguration | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Listet Provider und Standard-Modelle | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Anbieter](https://opencode.ai/docs/de/server#anbieter) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/provider` | Listet alle Provider | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Ruft Authentifizierungsmethoden der Provider ab | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autorisiert einen Provider per OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Behandelt OAuth-Callback fuer einen Provider | `boolean` | * * * ### [Sitzungen](https://opencode.ai/docs/de/server#sitzungen) | Method | Path | Description | Notes | | --- | --- | --- | --- | | `GET` | `/session` | Listet alle Sitzungen | Gibt [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
zurueck | | `POST` | `/session` | Erstellt eine neue Sitzung | body: `{ parentID?, title? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Ruft Status aller Sitzungen ab | Gibt `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` zurueck | | `GET` | `/session/:id` | Ruft Sitzungsdetails ab | Gibt [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
zurueck | | `DELETE` | `/session/:id` | Loescht eine Sitzung und alle Daten | Gibt `boolean` zurueck | | `PATCH` | `/session/:id` | Aktualisiert Sitzungseigenschaften | body: `{ title? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Ruft Kind-Sitzungen einer Sitzung ab | Gibt [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
zurueck | | `GET` | `/session/:id/todo` | Ruft die Todo-Liste einer Sitzung ab | Gibt [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
zurueck | | `POST` | `/session/:id/init` | Analysiert App und erstellt `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | | `POST` | `/session/:id/fork` | Forkt eine bestehende Sitzung an einer Nachricht | body: `{ messageID? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Bricht eine laufende Sitzung ab | Gibt `boolean` zurueck | | `POST` | `/session/:id/share` | Teilt eine Sitzung | Gibt [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
zurueck | | `DELETE` | `/session/:id/share` | Hebt Teilen einer Sitzung auf | Gibt [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
zurueck | | `GET` | `/session/:id/diff` | Ruft den Diff fuer diese Sitzung ab | query: `messageID?`, returns [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Fasst die Sitzung zusammen | body: `{ providerID, modelID }`, returns `boolean` | | `POST` | `/session/:id/revert` | Setzt eine Nachricht zurueck | body: `{ messageID, partID? }`, returns `boolean` | | `POST` | `/session/:id/unrevert` | Stellt alle zurueckgesetzten Nachrichten wieder her | Gibt `boolean` zurueck | | `POST` | `/session/:id/permissions/:permissionID` | Antwortet auf eine Berechtigungsanfrage | body: `{ response, remember? }`, returns `boolean` | * * * ### [Nachrichten](https://opencode.ai/docs/de/server#nachrichten) | Method | Path | Description | Notes | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Listet Nachrichten in einer Sitzung | query: `limit?`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Sendet eine Nachricht und wartet auf Antwort | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Ruft Nachrichtendetails ab | Returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Sendet eine Nachricht asynchron (ohne Warten) | body: same as `/session/:id/message`, returns `204 No Content` | | `POST` | `/session/:id/command` | Fuehrt einen Slash-Befehl aus | body: `{ messageID?, agent?, model?, command, arguments }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Fuehrt einen Shell-Befehl aus | body: `{ agent, model?, command }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Befehle](https://opencode.ai/docs/de/server#befehle) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/command` | Listet alle Befehle | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Dateien](https://opencode.ai/docs/de/server#dateien) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Sucht Text in Dateien | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Findet Dateien und Verzeichnisse nach Namen | `string[]` (paths) | | `GET` | `/find/symbol?query=` | Findet Workspace-Symbole | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Listet Dateien und Verzeichnisse | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Liest eine Datei | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Ruft Status fuer getrackte Dateien ab | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` Abfrageparameter](https://opencode.ai/docs/de/server#findfile-abfrageparameter) * `query` (erforderlich) — Suchbegriff (Fuzzy-Suche) * `type` (optional) — Ergebnisse auf `"file"` oder `"directory"` beschränken * `directory` (optional) — Projektstammverzeichnis für die Suche überschreiben * `limit` (optional) — Maximale Ergebnisse (1–200) * `dirs` (optional) — Legacy-Flag (`"false"` gibt nur Dateien zurück) * * * ### [Werkzeuge (Experimentell)](https://opencode.ai/docs/de/server#werkzeuge-experimentell) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Listet alle Tool-IDs | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Listet Tools mit JSON-Schemas fuer ein Modell | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, Formatierer & MCP](https://opencode.ai/docs/de/server#lsp-formatierer--mcp) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/lsp` | Ruft LSP-Server-Status ab | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Ruft Formatter-Status ab | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Ruft MCP-Server-Status ab | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Fuegt MCP-Server dynamisch hinzu | body: `{ name, config }`, returns MCP status object | * * * ### [Agenten](https://opencode.ai/docs/de/server#agenten) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/agent` | Listet alle verfuegbaren Agenten | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Logging](https://opencode.ai/docs/de/server#logging) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/log` | Schreibt Log-Eintrag. Body: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/de/server#tui) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Haengt Text an den Prompt an | `boolean` | | `POST` | `/tui/open-help` | Oeffnet den Hilfedialog | `boolean` | | `POST` | `/tui/open-sessions` | Oeffnet die Session-Auswahl | `boolean` | | `POST` | `/tui/open-themes` | Oeffnet die Theme-Auswahl | `boolean` | | `POST` | `/tui/open-models` | Oeffnet die Modell-Auswahl | `boolean` | | `POST` | `/tui/submit-prompt` | Sendet den aktuellen Prompt ab | `boolean` | | `POST` | `/tui/clear-prompt` | Leert den Prompt | `boolean` | | `POST` | `/tui/execute-command` | Fuehrt einen Befehl aus (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Zeigt Toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Wartet auf die naechste Kontrollanfrage | Control request object | | `POST` | `/tui/control/response` | Antwortet auf eine Kontrollanfrage (`{ body }`) | `boolean` | * * * ### [Authentifizierung](https://opencode.ai/docs/de/server#authentifizierung-1) | Method | Path | Description | Response | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Setzt Authentifizierungsdaten. Body muss dem Provider-Schema entsprechen | `boolean` | * * * ### [Events](https://opencode.ai/docs/de/server#events) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/event` | Server-Sent Events Stream. Erstes Event ist `server.connected`, dann Bus-Events | Server-sent events stream | * * * ### [Dokumentation](https://opencode.ai/docs/de/server#dokumentation) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1 Spezifikation | HTML page with OpenAPI spec | --- # Servidor | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/server#_top) Servidor ======== Interactuar con el servidor opencode a través de HTTP. El comando `opencode serve` ejecuta un servidor HTTP sin cabeza que expone un punto final OpenAPI que un cliente opencode puede usar. * * * ### [Uso](https://opencode.ai/docs/es/server#uso) opencode serve [--port ] [--hostname ] [--cors ] #### [Opciones](https://opencode.ai/docs/es/server#opciones) | Bandera | Descripción | Predeterminado | | --- | --- | --- | | `--port` | Puerto para escuchar | `4096` | | `--hostname` | Nombre de host para escuchar | `127.0.0.1` | | `--mdns` | Habilitar el descubrimiento de mDNS | `false` | | `--mdns-domain` | Nombre de dominio personalizado para el servicio mDNS | `opencode.local` | | `--cors` | Orígenes de navegador adicionales para permitir | `[]` | `--cors` se puede pasar varias veces: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Autenticación](https://opencode.ai/docs/es/server#autenticaci%C3%B3n) Configure `OPENCODE_SERVER_PASSWORD` para proteger el servidor con autenticación básica HTTP. El nombre de usuario predeterminado es `opencode`, o configure `OPENCODE_SERVER_USERNAME` para anularlo. Esto se aplica tanto a `opencode serve` como a `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Cómo funciona](https://opencode.ai/docs/es/server#c%C3%B3mo-funciona) Cuando ejecuta `opencode`, inicia un TUI y un servidor. Donde el TUI es el Cliente que habla con el servidor. El servidor expone una especificación OpenAPI 3.1 punto final. Este punto final también se utiliza para generar un [SDK](https://opencode.ai/docs/sdk) . Esta arquitectura permite que opencode admita múltiples clientes y le permite interactuar con opencode mediante programación. Puede ejecutar `opencode serve` para iniciar un servidor independiente. Si tienes el opencode TUI ejecutándose, `opencode serve` iniciará un nuevo servidor. * * * #### [Conectarse a un servidor existente](https://opencode.ai/docs/es/server#conectarse-a-un-servidor-existente) Cuando inicia el TUI, asigna aleatoriamente un puerto y un nombre de host. En su lugar, puede pasar `--hostname` y `--port` [banderas](https://opencode.ai/docs/cli) . Luego use esto para conectarse a su servidor. El punto final [`/tui`](https://opencode.ai/docs/es/server#tui) se puede utilizar para conducir el TUI a través del servidor. Por ejemplo, puede completar previamente o ejecutar un mensaje. Esta configuración es utilizada por los complementos OpenCode [IDE](https://opencode.ai/docs/ide) . * * * [Especificaciones](https://opencode.ai/docs/es/server#especificaciones) ------------------------------------------------------------------------ El servidor publica una especificación OpenAPI 3.1 que se puede ver en: http://:/doc Por ejemplo, `http://localhost:4096/doc`. Utilice la especificación para generar clientes o inspeccionar tipos de solicitudes y respuestas. O verlo en un explorador Swagger. * * * [API](https://opencode.ai/docs/es/server#api) ---------------------------------------------- El servidor opencode expone las siguientes API. * * * ### [Global](https://opencode.ai/docs/es/server#global) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/global/health` | Obtener el estado y la versión del servidor | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Obtenga eventos globales (transmisión SSE) | Flujo de eventos | * * * ### [Proyecto](https://opencode.ai/docs/es/server#proyecto) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/project` | Listar todos los proyectos | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Obtener el proyecto actual | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Ruta y VCS](https://opencode.ai/docs/es/server#ruta-y-vcs) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/path` | Obtener la ruta actual | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Obtenga información de VCS para el proyecto actual | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Instancia](https://opencode.ai/docs/es/server#instancia) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Eliminar la instancia actual | `boolean` | * * * ### [Configuración](https://opencode.ai/docs/es/server#configuraci%C3%B3n) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/config` | Obtener información de configuración | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Actualizar configuración | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Lista de proveedores y modelos predeterminados | `{ providers:` [Proveedor\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Proveedor](https://opencode.ai/docs/es/server#proveedor) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/provider` | Listar todos los proveedores | `{ all:` [Proveedor\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Obtener métodos de autenticación de proveedores | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autorizar a un proveedor usando OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Manejar la devolución de llamada OAuth para un proveedor | `boolean` | * * * ### [Sesiones](https://opencode.ai/docs/es/server#sesiones) | Método | Ruta | Descripción | Notas | | --- | --- | --- | --- | | `GET` | `/session` | Listar todas las sesiones | Devuelve [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Crear una nueva sesión | cuerpo: `{ parentID?, title? }`, devuelve [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Obtener el estado de la sesión para todas las sesiones | Devuelve `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Obtener detalles de la sesión | Devuelve [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Eliminar una sesión y todos sus datos | Devuelve `boolean` | | `PATCH` | `/session/:id` | Actualizar propiedades de sesión | cuerpo: `{ title? }`, devuelve [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Obtener las sesiones secundarias de una sesión | Devuelve [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Obtener la lista de tareas pendientes para una sesión | Devuelve [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Analizar aplicación y crear `AGENTS.md` | cuerpo: `{ messageID, providerID, modelID }`, devuelve `boolean` | | `POST` | `/session/:id/fork` | Bifurca una sesión existente en un mensaje | cuerpo: `{ messageID? }`, devuelve [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Cancelar una sesión en ejecución | Devuelve `boolean` | | `POST` | `/session/:id/share` | Compartir una sesión | Devuelve [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Dejar de compartir una sesión | Devuelve [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Obtenga la diferencia para esta sesión | consulta: `messageID?`, devuelve [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Resumir la sesión | cuerpo: `{ providerID, modelID }`, devuelve `boolean` | | `POST` | `/session/:id/revert` | Revertir un mensaje | cuerpo: `{ messageID, partID? }`, devuelve `boolean` | | `POST` | `/session/:id/unrevert` | Restaurar todos los mensajes revertidos | Devuelve `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Responder a una solicitud de permiso | cuerpo: `{ response, remember? }`, devuelve `boolean` | * * * ### [Mensajes](https://opencode.ai/docs/es/server#mensajes) | Método | Ruta | Descripción | Notas | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Listar mensajes en una sesión | consulta: `limit?`, devuelve `{ info:` [Mensaje](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Parte\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Envía un mensaje y espera respuesta | cuerpo: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, devuelve `{ info:` [Mensaje](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Parte\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Obtener detalles del mensaje | Devuelve `{ info:` [Mensaje](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Parte\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Enviar un mensaje de forma asincrónica (sin espera) | cuerpo: igual que `/session/:id/message`, devuelve `204 No Content` | | `POST` | `/session/:id/command` | Ejecutar un comando de barra diagonal | cuerpo: `{ messageID?, agent?, model?, command, arguments }`, devuelve `{ info:` [Mensaje](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Parte\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Ejecute un comando de shell | cuerpo: `{ agent, model?, command }`, devuelve `{ info:` [Mensaje](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Parte\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Comandos](https://opencode.ai/docs/es/server#comandos) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/command` | Listar todos los comandos | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Archivos](https://opencode.ai/docs/es/server#archivos) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Buscar texto en archivos | Matriz de objetos coincidentes con `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Buscar archivos y directorios por nombre | `string[]` (caminos) | | `GET` | `/find/symbol?query=` | Buscar símbolos del espacio de trabajo | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Listar archivos y directorios | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Leer un archivo | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Obtener el estado de los archivos rastreados | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [Parámetros de consulta de /find/file](https://opencode.ai/docs/es/server#par%C3%A1metros-de-consulta-de-findfile) * `query` (obligatorio) — cadena de búsqueda (coincidencia aproximada) * `type` (opcional): limita los resultados a `"file"` o `"directory"` * `directory` (opcional): anula la raíz del proyecto para la búsqueda. * `limit` (opcional) — resultados máximos (1–200) * `dirs` (opcional): indicador heredado (`"false"` devuelve solo archivos) * * * ### [Herramientas (experimentales)](https://opencode.ai/docs/es/server#herramientas-experimentales) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Listar todos los ID de herramientas | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Listar herramientas con esquemas JSON para un modelo | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, formateadores y MCP](https://opencode.ai/docs/es/server#lsp-formateadores-y-mcp) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/lsp` | Obtener el estado del servidor LSP | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Obtener estado del formateador | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Obtener el estado del servidor MCP | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Agregue el servidor MCP dinámicamente | cuerpo: `{ name, config }`, devuelve MCP objeto de estado | * * * ### [Agentes](https://opencode.ai/docs/es/server#agentes) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/agent` | Listar todos los agentes disponibles | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Registro](https://opencode.ai/docs/es/server#registro) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `POST` | `/log` | Escribir entrada de registro. Cuerpo: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/es/server#tui) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Agregar texto al mensaje | `boolean` | | `POST` | `/tui/open-help` | Abra el cuadro de diálogo de ayuda | `boolean` | | `POST` | `/tui/open-sessions` | Abrir el selector de sesiones | `boolean` | | `POST` | `/tui/open-themes` | Abra el selector de temas | `boolean` | | `POST` | `/tui/open-models` | Abrir el selector de modelo | `boolean` | | `POST` | `/tui/submit-prompt` | Enviar el mensaje actual | `boolean` | | `POST` | `/tui/clear-prompt` | Borrar el mensaje | `boolean` | | `POST` | `/tui/execute-command` | Ejecutar un comando (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Mostrar brindis (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Espere la próxima solicitud de control | Objeto de solicitud de control | | `POST` | `/tui/control/response` | Responder a una solicitud de control (`{ body }`) | `boolean` | * * * ### [Autenticación](https://opencode.ai/docs/es/server#autenticaci%C3%B3n-1) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Establecer credenciales de autenticación. El cuerpo debe coincidir con el esquema del proveedor | `boolean` | * * * ### [Eventos](https://opencode.ai/docs/es/server#eventos) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/event` | Transmisión de eventos enviados por el servidor. El primer evento es `server.connected`, luego eventos de bus | Transmisión de eventos enviados por el servidor | * * * ### [Documentación](https://opencode.ai/docs/es/server#documentaci%C3%B3n) | Método | Ruta | Descripción | Respuesta | | --- | --- | --- | --- | | `GET` | `/doc` | Especificación OpenAPI 3.1 | Página HTML con especificación OpenAPI | --- # 포매터 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/formatters#_top) 포매터 === OpenCode는 언어별 포매터를 사용합니다. OpenCode는 파일을 write하거나 edit한 뒤, 언어별 포매터를 사용해 자동으로 포맷합니다. 이를 통해 생성된 코드가 프로젝트의 코드 스타일을 따르도록 보장합니다. * * * [내장](https://opencode.ai/docs/ko/formatters#%EB%82%B4%EC%9E%A5) ---------------------------------------------------------------- OpenCode는 주요 언어와 프레임워크를 위한 여러 내장 포매터를 제공합니다. 아래는 포매터 목록, 지원 확장자, 필요한 명령 또는 config 옵션입니다. | 포매터 | 확장자 | 요구 사항 | | --- | --- | --- | | air | .R | `air` 명령 사용 가능 | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, [기타](https://biomejs.dev/) | `biome.json(c)` config 파일 | | cargofmt | .rs | `cargo fmt` 명령 사용 가능 | | clang-format | .c, .cpp, .h, .hpp, .ino, [기타](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` config 파일 | | cljfmt | .clj, .cljs, .cljc, .edn | `cljfmt` 명령 사용 가능 | | dart | .dart | `dart` 명령 사용 가능 | | dfmt | .d | `dfmt` 명령 사용 가능 | | gleam | .gleam | `gleam` 명령 사용 가능 | | gofmt | .go | `gofmt` 명령 사용 가능 | | htmlbeautifier | .erb, .html.erb | `htmlbeautifier` 명령 사용 가능 | | ktlint | .kt, .kts | `ktlint` 명령 사용 가능 | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` 명령 사용 가능 | | nixfmt | .nix | `nixfmt` 명령 사용 가능 | | ocamlformat | .ml, .mli | `ocamlformat` 명령 사용 가능 및 `.ocamlformat` config 파일 필요 | | ormolu | .hs | `ormolu` 명령 사용 가능 | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | `package.json`에 `oxfmt` dependency 필요 및 [experimental env variable flag](https://opencode.ai/docs/cli/#experimental) | | pint | .php | `composer.json`에 `laravel/pint` dependency 필요 | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, [기타](https://prettier.io/docs/en/index.html) | `package.json`에 `prettier` dependency 필요 | | rubocop | .rb, .rake, .gemspec, .ru | `rubocop` 명령 사용 가능 | | ruff | .py, .pyi | `ruff` 명령 사용 가능 및 관련 config 필요 | | rustfmt | .rs | `rustfmt` 명령 사용 가능 | | shfmt | .sh, .bash | `shfmt` 명령 사용 가능 | | standardrb | .rb, .rake, .gemspec, .ru | `standardrb` 명령 사용 가능 | | terraform | .tf, .tfvars | `terraform` 명령 사용 가능 | | uv | .py, .pyi | `uv` 명령 사용 가능 | | zig | .zig, .zon | `zig` 명령 사용 가능 | 예를 들어 프로젝트 `package.json`에 `prettier`가 있으면 OpenCode가 자동으로 해당 포매터를 사용합니다. * * * [작동 방식](https://opencode.ai/docs/ko/formatters#%EC%9E%91%EB%8F%99-%EB%B0%A9%EC%8B%9D) -------------------------------------------------------------------------------------- OpenCode가 파일을 write하거나 edit할 때 다음 순서로 동작합니다. 1. 활성화된 모든 포매터와 파일 확장자를 대조합니다. 2. 파일에 맞는 포매터 명령을 실행합니다. 3. 포맷 변경 사항을 자동으로 적용합니다. 이 과정은 background에서 실행되며, 수동 작업 없이 코드 스타일이 유지됩니다. * * * [구성](https://opencode.ai/docs/ko/formatters#%EA%B5%AC%EC%84%B1) ---------------------------------------------------------------- OpenCode config의 `formatter` 섹션에서 포매터를 커스터마이즈할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "formatter": {}} 각 formatter 설정에서 지원하는 항목은 다음과 같습니다. | 속성 | 타입 | 설명 | | --- | --- | --- | | `disabled` | boolean | `true`로 설정하면 해당 포매터를 비활성화합니다 | | `command` | string\[\] | 포맷 실행 명령입니다 | | `environment` | object | 포매터 실행 시 설정할 환경 변수입니다 | | `extensions` | string\[\] | 해당 포매터가 처리할 파일 확장자입니다 | 아래 예시를 참고하세요. * * * ### [포매터 비활성화](https://opencode.ai/docs/ko/formatters#%ED%8F%AC%EB%A7%A4%ED%84%B0-%EB%B9%84%ED%99%9C%EC%84%B1%ED%99%94) 전체 포매터를 전역에서 비활성화하려면 `formatter`를 `false`로 설정하세요. { "$schema": "https://opencode.ai/config.json", "formatter": false} 특정 포매터만 비활성화하려면 `disabled`를 `true`로 설정하세요. { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [사용자 정의 포매터](https://opencode.ai/docs/ko/formatters#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98-%ED%8F%AC%EB%A7%A4%ED%84%B0) 명령, 환경 변수, 파일 확장자를 지정해 내장 포매터를 override하거나 새 포매터를 추가할 수 있습니다. { "$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"] } }} 명령의 **`$FILE` placeholder**는 포맷 대상 파일 경로로 치환됩니다. --- # 格式化工具 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/formatters#_top) 格式化工具 ===== OpenCode 使用特定语言的格式化工具。 OpenCode 会在文件写入或编辑后,自动使用特定语言的格式化工具对其进行格式化。这确保了生成的代码遵循你项目的代码风格。 * * * [内置格式化工具](https://opencode.ai/docs/zh-cn/formatters#%E5%86%85%E7%BD%AE%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%B7%A5%E5%85%B7) --------------------------------------------------------------------------------------------------------------------- OpenCode 内置了多种适用于主流语言和框架的格式化工具。下表列出了各格式化工具、支持的文件扩展名以及所需的命令或配置选项。 | 格式化工具 | 扩展名 | 要求 | | --- | --- | --- | | air | .R | `air` 命令可用 | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml 及[更多](https://biomejs.dev/) | `biome.json(c)` 配置文件 | | cargofmt | .rs | `cargo fmt` 命令可用 | | clang-format | .c, .cpp, .h, .hpp, .ino 及[更多](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` 配置文件 | | cljfmt | .clj, .cljs, .cljc, .edn | `cljfmt` 命令可用 | | dart | .dart | `dart` 命令可用 | | dfmt | .d | `dfmt` 命令可用 | | gleam | .gleam | `gleam` 命令可用 | | gofmt | .go | `gofmt` 命令可用 | | htmlbeautifier | .erb, .html.erb | `htmlbeautifier` 命令可用 | | ktlint | .kt, .kts | `ktlint` 命令可用 | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` 命令可用 | | nixfmt | .nix | `nixfmt` 命令可用 | | ocamlformat | .ml, .mli | `ocamlformat` 命令可用且存在 `.ocamlformat` 配置文件 | | ormolu | .hs | `ormolu` 命令可用 | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | `package.json` 中有 `oxfmt` 依赖,且设置了[实验性环境变量标志](https://opencode.ai/docs/cli/#experimental) | | pint | .php | `composer.json` 中有 `laravel/pint` 依赖 | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml 及[更多](https://prettier.io/docs/en/index.html) | `package.json` 中有 `prettier` 依赖 | | rubocop | .rb, .rake, .gemspec, .ru | `rubocop` 命令可用 | | ruff | .py, .pyi | `ruff` 命令可用且有相应配置 | | rustfmt | .rs | `rustfmt` 命令可用 | | shfmt | .sh, .bash | `shfmt` 命令可用 | | standardrb | .rb, .rake, .gemspec, .ru | `standardrb` 命令可用 | | terraform | .tf, .tfvars | `terraform` 命令可用 | | uv | .py, .pyi | `uv` 命令可用 | | zig | .zig, .zon | `zig` 命令可用 | 因此,如果你的项目 `package.json` 中包含 `prettier`,OpenCode 会自动使用它进行格式化。 * * * [工作原理](https://opencode.ai/docs/zh-cn/formatters#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) --------------------------------------------------------------------------------------- 当 OpenCode 写入或编辑文件时,它会: 1. 根据所有已启用的格式化工具检查文件扩展名。 2. 对文件运行相应的格式化命令。 3. 自动应用格式化更改。 整个过程在后台完成,无需任何手动操作即可保持代码风格的一致性。 * * * [配置](https://opencode.ai/docs/zh-cn/formatters#%E9%85%8D%E7%BD%AE) ------------------------------------------------------------------- 你可以通过 OpenCode 配置中的 `formatter` 部分自定义格式化工具。 { "$schema": "https://opencode.ai/config.json", "formatter": {}} 每个格式化工具的配置支持以下属性: | 属性 | 类型 | 描述 | | --- | --- | --- | | `disabled` | boolean | 设为 `true` 可禁用该格式化工具 | | `command` | string\[\] | 执行格式化的命令 | | `environment` | object | 运行格式化工具时设置的环境变量 | | `extensions` | string\[\] | 该格式化工具处理的文件扩展名 | 下面来看一些示例。 * * * ### [禁用格式化工具](https://opencode.ai/docs/zh-cn/formatters#%E7%A6%81%E7%94%A8%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%B7%A5%E5%85%B7) 要全局禁用**所有**格式化工具,将 `formatter` 设为 `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} 要禁用**特定**格式化工具,将 `disabled` 设为 `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [自定义格式化工具](https://opencode.ai/docs/zh-cn/formatters#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%B7%A5%E5%85%B7) 你可以通过指定命令、环境变量和文件扩展名来覆盖内置格式化工具或添加新的格式化工具: { "$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"] } }} 命令中的 **`$FILE` 占位符**会被替换为待格式化文件的路径。 --- # 格式化器 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/formatters#_top) 格式化器 ==== OpenCode 使用特定語言的格式化器。 OpenCode 會在檔案寫入或編輯後,自動使用特定語言的格式化器對其進行格式化。這確保了生成的程式碼遵循您專案的程式碼風格。 * * * [內建格式化器](https://opencode.ai/docs/zh-tw/formatters#%E5%85%A7%E5%BB%BA%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%99%A8) ----------------------------------------------------------------------------------------------------------- OpenCode 內建了多種適用於主流語言和框架的格式化器。下表列出了各格式化器、支援的副檔名以及所需的指令或設定選項。 | 格式化器 | 副檔名 | 要求 | | --- | --- | --- | | air | .R | `air` 指令可用 | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml 及[更多](https://biomejs.dev/) | `biome.json(c)` 設定檔 | | cargofmt | .rs | `cargo fmt` 指令可用 | | clang-format | .c, .cpp, .h, .hpp, .ino 及[更多](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` 設定檔 | | cljfmt | .clj, .cljs, .cljc, .edn | `cljfmt` 指令可用 | | dart | .dart | `dart` 指令可用 | | dfmt | .d | `dfmt` 指令可用 | | gleam | .gleam | `gleam` 指令可用 | | gofmt | .go | `gofmt` 指令可用 | | htmlbeautifier | .erb, .html.erb | `htmlbeautifier` 指令可用 | | ktlint | .kt, .kts | `ktlint` 指令可用 | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` 指令可用 | | nixfmt | .nix | `nixfmt` 指令可用 | | ocamlformat | .ml, .mli | `ocamlformat` 指令可用且存在 `.ocamlformat` 設定檔 | | ormolu | .hs | `ormolu` 指令可用 | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | `package.json` 中有 `oxfmt` 相依套件,且設定了[實驗性環境變數旗標](https://opencode.ai/docs/cli/#experimental) | | pint | .php | `composer.json` 中有 `laravel/pint` 相依套件 | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml 及[更多](https://prettier.io/docs/en/index.html) | `package.json` 中有 `prettier` 相依套件 | | rubocop | .rb, .rake, .gemspec, .ru | `rubocop` 指令可用 | | ruff | .py, .pyi | `ruff` 指令可用且有相應設定 | | rustfmt | .rs | `rustfmt` 指令可用 | | shfmt | .sh, .bash | `shfmt` 指令可用 | | standardrb | .rb, .rake, .gemspec, .ru | `standardrb` 指令可用 | | terraform | .tf, .tfvars | `terraform` 指令可用 | | uv | .py, .pyi | `uv` 指令可用 | | zig | .zig, .zon | `zig` 指令可用 | 因此,如果您的專案 `package.json` 中包含 `prettier`,OpenCode 會自動使用它進行格式化。 * * * [工作原理](https://opencode.ai/docs/zh-tw/formatters#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) --------------------------------------------------------------------------------------- 當 OpenCode 寫入或編輯檔案時,它會: 1. 根據所有已啟用的格式化器檢查副檔名。 2. 對檔案執行相應的格式化指令。 3. 自動套用格式化變更。 整個過程在背景完成,無需任何手動操作即可保持程式碼風格的一致性。 * * * [設定](https://opencode.ai/docs/zh-tw/formatters#%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------------- 您可以透過 OpenCode 設定中的 `formatter` 部分自訂格式化器。 { "$schema": "https://opencode.ai/config.json", "formatter": {}} 每個格式化器的設定支援以下屬性: | 屬性 | 型別 | 說明 | | --- | --- | --- | | `disabled` | boolean | 設為 `true` 可停用該格式化器 | | `command` | string\[\] | 執行格式化的指令 | | `environment` | object | 執行格式化器時設定的環境變數 | | `extensions` | string\[\] | 該格式化器處理的副檔名 | 下面來看一些範例。 * * * ### [停用格式化器](https://opencode.ai/docs/zh-tw/formatters#%E5%81%9C%E7%94%A8%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%99%A8) 要全域停用**所有**格式化器,將 `formatter` 設為 `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} 要停用**特定**格式化器,將 `disabled` 設為 `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [自訂格式化器](https://opencode.ai/docs/zh-tw/formatters#%E8%87%AA%E8%A8%82%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%99%A8) 您可以透過指定指令、環境變數和副檔名來覆寫內建格式化器或新增新的格式化器: { "$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"] } }} 指令中的 **`$FILE` 佔位符**會被替換為待格式化檔案的路徑。 --- # Formatierer | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/formatters#_top) Formatierer =========== OpenCode verwendet sprachspezifische Formatierer. OpenCode formatiert Dateien automatisch, nachdem sie mit sprachspezifischen Formatierern geschrieben oder bearbeitet wurden. Dadurch wird sichergestellt, dass der generierte Code dem Codestil Ihres Projekts entspricht. * * * [Integriert](https://opencode.ai/docs/de/formatters#integriert) ---------------------------------------------------------------- OpenCode verfügt über mehrere integrierte Formatierer für gängige Sprachen und Frameworks. Nachfolgend finden Sie eine Liste der Formatierer, unterstützten Dateierweiterungen und benötigten Befehle oder Konfigurationsoptionen. | Formatierer | Erweiterungen | Anforderungen | | --- | --- | --- | | gofmt | .go | `gofmt`\-Befehl verfügbar | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix`\-Befehl verfügbar | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, und [more](https://prettier.io/docs/en/index.html) | `prettier`\-Abhängigkeit in `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, und [more](https://biomejs.dev/) | `biome.json(c)` Konfigurationsdatei | | zig | .zig, .zon | `zig`\-Befehl verfügbar | | clang-format | .c, .cpp, .h, .hpp, .ino und [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` Konfigurationsdatei | | ktlint | .kt, .kts | `ktlint`\-Befehl verfügbar | | ruff | .py, .pyi | `ruff`\-Befehl verfügbar mit config | | rustfmt | .rs | `rustfmt`\-Befehl verfügbar | | cargofmt | .rs | `cargo fmt`\-Befehl verfügbar | | uv | .py, .pyi | `uv`\-Befehl verfügbar | | rubocop | .rb, .rake, .gemspec, .ru | `rubocop`\-Befehl verfügbar | | standardrb | .rb, .rake, .gemspec, .ru | `standardrb`\-Befehl verfügbar | | htmlbeautifier | .erb, .html.erb | `htmlbeautifier`\-Befehl verfügbar | | air | .R | `air`\-Befehl verfügbar | | dart | .dart | `dart`\-Befehl verfügbar | | dfmt | .d | `dfmt`\-Befehl verfügbar | | ocamlformat | .ml, .mli | `ocamlformat` Befehl verfügbar und `.ocamlformat` Konfigurationsdatei | | terraform | .tf, .tfvars | `terraform`\-Befehl verfügbar | | gleam | .gleam | `gleam`\-Befehl verfügbar | | nixfmt | .nix | `nixfmt`\-Befehl verfügbar | | shfmt | .sh, .bash | `shfmt`\-Befehl verfügbar | | pint | .php | `laravel/pint`\-Abhängigkeit in `composer.json` | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | `oxfmt`\-Abhängigkeit in `package.json` und einer [experimental env variable flag](https://opencode.ai/docs/cli/#experimental) | | Ormolu | .hs | `ormolu`\-Befehl verfügbar | Wenn Ihr Projekt auch `prettier` in Ihrem `package.json` hat, wird OpenCode automatisch verwendet. * * * [Funktionsweise](https://opencode.ai/docs/de/formatters#funktionsweise) ------------------------------------------------------------------------ Wenn OpenCode eine Datei schreibt oder bearbeitet, geschieht Folgendes: 1. Überprüft die Dateierweiterung anhand aller aktivierten Formatierer. 2. Führt den entsprechenden Formatierungsbefehl für die Datei aus. 3. Wendet die Formatierungsänderungen automatisch an. Dieser Prozess findet im Hintergrund statt und stellt sicher, dass Ihr Codestile ohne manuelle Schritte beibehalten werden. * * * [Konfiguration](https://opencode.ai/docs/de/formatters#konfiguration) ---------------------------------------------------------------------- Sie können Formatierer über den Abschnitt `formatter` in Ihrer OpenCode-Konfiguration anpassen. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Jede Formatierungskonfiguration unterstützt Folgendes: | Eigenschaft | Typ | Beschreibung | | --- | --- | --- | | `disabled` | boolescher Wert | Setzen Sie dies auf `true`, um den Formatierer zu deaktivieren | | `command` | string\[\] | Der zum Formatieren auszuführende Befehl | | `environment` | Objekt | Umgebungsvariablen, die beim Ausführen des Formatierers festgelegt werden sollen | | `extensions` | string\[\] | Dateierweiterungen, die dieser Formatierer verarbeiten soll | Schauen wir uns einige Beispiele an. * * * ### [Formatierer deaktivieren](https://opencode.ai/docs/de/formatters#formatierer-deaktivieren) Um **alle** Formatierer global zu deaktivieren, setzen Sie `formatter` auf `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} Um einen **bestimmten** Formatierer zu deaktivieren, setzen Sie `disabled` auf `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Benutzerdefinierter Formatierer](https://opencode.ai/docs/de/formatters#benutzerdefinierter-formatierer) Sie können den integrierten Formatierer überschreiben oder neu hinzufügen, indem Sie den Befehl, Umgebungsvariablen und Dateierweiterungen angeben: { "$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"] } }} Der Platzhalter **`$FILE`** im Befehl wird durch den Pfad zur zu formatierenden Datei ersetzt. --- # Serveur | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/server#_top) Serveur ======= Interagissez avec le serveur opencode via HTTP. La commande `opencode serve` exécute un serveur HTTP sans tête qui expose un point de terminaison OpenAPI qu’un client opencode peut utiliser. * * * ### [Usage](https://opencode.ai/docs/fr/server#usage) opencode serve [--port ] [--hostname ] [--cors ] #### [Options](https://opencode.ai/docs/fr/server#options) | Drapeau | Descriptif | Par défaut | | --- | --- | --- | | `--port` | Port à écouter sur | `4096` | | `--hostname` | Nom d’hôte sur lequel écouter | `127.0.0.1` | | `--mdns` | Activer la découverte mDNS | `false` | | `--mdns-domain` | Nom de domaine personnalisé pour le service mDNS | `opencode.local` | | `--cors` | Origines de navigateur supplémentaires à autoriser | `[]` | `--cors` peut être transmis plusieurs fois : opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Authentification](https://opencode.ai/docs/fr/server#authentification) Définissez `OPENCODE_SERVER_PASSWORD` pour protéger le serveur avec l’authentification de base HTTP. Le nom d’utilisateur est par défaut `opencode`, ou définissez `OPENCODE_SERVER_USERNAME` pour le remplacer. Cela s’applique à la fois à `opencode serve` et à `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Comment ça marche](https://opencode.ai/docs/fr/server#comment-%C3%A7a-marche) Lorsque vous exécutez `opencode`, il démarre un TUI et un serveur. Où le TUI est le client qui parle au serveur. Le serveur expose une spécification OpenAPI 3.1 point final. Ce point de terminaison est également utilisé pour générer un [SDK](https://opencode.ai/docs/sdk) . Cette architecture permet à opencode de prendre en charge plusieurs clients et vous permet d’interagir avec opencode par programme. Vous pouvez exécuter `opencode serve` pour démarrer un serveur autonome. Si vous avez le opencode TUI en cours d’exécution, `opencode serve` démarrera un nouveau serveur. * * * #### [Connectez-vous à un serveur existant](https://opencode.ai/docs/fr/server#connectez-vous-%C3%A0-un-serveur-existant) Lorsque vous démarrez le TUI, il attribue de manière aléatoire un port et un nom d’hôte. Vous pouvez à la place transmettre les `--hostname` et `--port` [flags](https://opencode.ai/docs/cli) . Utilisez-le ensuite pour vous connecter à son serveur. Le point de terminaison [`/tui`](https://opencode.ai/docs/fr/server#tui) peut être utilisé pour piloter le TUI via le serveur. Par exemple, vous pouvez pré-remplir ou exécuter une invite. Cette configuration est utilisée par les plugins OpenCode [IDE](https://opencode.ai/docs/ide) . * * * [Spécification](https://opencode.ai/docs/fr/server#sp%C3%A9cification) ----------------------------------------------------------------------- Le serveur publie une spécification OpenAPI 3.1 qui peut être consultée à l’adresse : http://:/doc Par exemple, `http://localhost:4096/doc`. Utilisez la spécification pour générer des clients ou inspecter les types de requêtes et de réponses. Ou visualisez-le dans un explorateur Swagger. * * * [APIs](https://opencode.ai/docs/fr/server#apis) ------------------------------------------------ Le serveur opencode expose les API suivantes. * * * ### [Mondial](https://opencode.ai/docs/fr/server#mondial) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/global/health` | Obtenir l’état et la version du serveur | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Obtenez des événements mondiaux (flux SSE) | Flux d’événements | * * * ### [Projet](https://opencode.ai/docs/fr/server#projet) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/project` | Lister tous les projets | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Obtenez le projet en cours | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Chemin et VCS](https://opencode.ai/docs/fr/server#chemin-et-vcs) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/path` | Obtenir le chemin actuel | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Obtenir des informations VCS pour le projet en cours | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Exemple](https://opencode.ai/docs/fr/server#exemple) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Supprimer l’instance actuelle | `boolean` | * * * ### [Configuration](https://opencode.ai/docs/fr/server#configuration) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/config` | Obtenir des informations de configuration | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Mettre à jour la configuration | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Liste des fournisseurs et modèles par défaut | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Fournisseur](https://opencode.ai/docs/fr/server#fournisseur) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/provider` | Liste de tous les fournisseurs | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Obtenir les méthodes d’authentification du fournisseur | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autoriser un fournisseur en utilisant OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Gérer le rappel OAuth pour un fournisseur | `boolean` | * * * ### [Séances](https://opencode.ai/docs/fr/server#s%C3%A9ances) | Méthode | Chemin | Descriptif | Remarques | | --- | --- | --- | --- | | `GET` | `/session` | Liste toutes les sessions | Renvoie [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Créer une nouvelle session | corps : `{ parentID?, title? }`, renvoie [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Obtenir l’état de la session pour toutes les sessions | Renvoie `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Obtenez les détails de la session | Renvoie [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Supprimer une session et toutes ses données | Renvoie `boolean` | | `PATCH` | `/session/:id` | Mettre à jour les propriétés de la session | corps : `{ title? }`, renvoie [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Obtenir les sessions enfants d’une session | Renvoie [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Obtenez la liste de tâches pour une session | Renvoie [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Analysez l’application et créez `AGENTS.md` | corps : `{ messageID, providerID, modelID }`, renvoie `boolean` | | `POST` | `/session/:id/fork` | Forkez une session existante à un message | corps : `{ messageID? }`, renvoie [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Abandonner une session en cours | Renvoie `boolean` | | `POST` | `/session/:id/share` | Partager une séance | Renvoie [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Annuler le partage d’une session | Renvoie [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Obtenez le diff pour cette session | requête : `messageID?`, renvoie [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Résumer la séance | corps : `{ providerID, modelID }`, renvoie `boolean` | | `POST` | `/session/:id/revert` | Rétablir un message | corps : `{ messageID, partID? }`, renvoie `boolean` | | `POST` | `/session/:id/unrevert` | Restaurer tous les messages annulés | Renvoie `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Répondre à une demande d’autorisation | corps : `{ response, remember? }`, renvoie `boolean` | * * * ### [Messages](https://opencode.ai/docs/fr/server#messages) | Méthode | Chemin | Descriptif | Remarques | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Liste des messages dans une session | requête : `limit?`, renvoie `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Envoyer un message et attendre une réponse | corps : `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, renvoie `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Obtenir les détails du message | Renvoie `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Envoyer un message de manière asynchrone (pas d’attente) | body : identique à `/session/:id/message`, renvoie `204 No Content` | | `POST` | `/session/:id/command` | Exécuter une commande slash | corps : `{ messageID?, agent?, model?, command, arguments }`, renvoie `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Exécuter une commande shell | corps : `{ agent, model?, command }`, renvoie `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Commandes](https://opencode.ai/docs/fr/server#commandes) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/command` | Liste toutes les commandes | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Fichiers](https://opencode.ai/docs/fr/server#fichiers) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Rechercher du texte dans des fichiers | Tableau d’objets correspondant avec `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Rechercher des fichiers et des répertoires par nom | `string[]` (chemins) | | `GET` | `/find/symbol?query=` | Rechercher des symboles d’espace de travail | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Liste des fichiers et répertoires | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Lire un fichier | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Obtenir le statut des fichiers suivis | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [Paramètres de requête `/find/file`](https://opencode.ai/docs/fr/server#param%C3%A8tres-de-requ%C3%AAte-findfile) * `query` (obligatoire) — chaîne de recherche (correspondance floue) * `type` (facultatif) — limiter les résultats à `"file"` ou `"directory"` * `directory` (facultatif) — remplace la racine du projet pour la recherche * `limit` (facultatif) — résultats maximum (1 à 200) * `dirs` (facultatif) — indicateur hérité (`"false"` renvoie uniquement les fichiers) * * * ### [Outils (expérimentaux)](https://opencode.ai/docs/fr/server#outils-exp%C3%A9rimentaux) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Répertorier tous les ID d’outils | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Répertorier les outils avec des schémas JSON pour un modèle | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, formateurs et MCP](https://opencode.ai/docs/fr/server#lsp-formateurs-et-mcp) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/lsp` | Obtenir l’état du serveur LSP | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Obtenir le statut du formateur | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Obtenir l’état du serveur MCP | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Ajouter dynamiquement le serveur MCP | corps : `{ name, config }`, renvoie l’objet d’état MCP | * * * ### [Agents](https://opencode.ai/docs/fr/server#agents) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/agent` | Liste tous les agents disponibles | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Enregistrement](https://opencode.ai/docs/fr/server#enregistrement) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `POST` | `/log` | Écrire une entrée de journal. Corps : `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/fr/server#tui) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Ajouter du texte à l’invite | `boolean` | | `POST` | `/tui/open-help` | Ouvrir la boîte de dialogue d’aide | `boolean` | | `POST` | `/tui/open-sessions` | Ouvrez le sélecteur de session | `boolean` | | `POST` | `/tui/open-themes` | Ouvrez le sélecteur de thème | `boolean` | | `POST` | `/tui/open-models` | Ouvrez le sélecteur de modèle | `boolean` | | `POST` | `/tui/submit-prompt` | Soumettre l’invite actuelle | `boolean` | | `POST` | `/tui/clear-prompt` | Effacez l’invite | `boolean` | | `POST` | `/tui/execute-command` | Exécuter une commande (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Afficher le toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Attendre la prochaine demande de contrôle | Objet de demande de contrôle | | `POST` | `/tui/control/response` | Répondre à une demande de contrôle (`{ body }`) | `boolean` | * * * ### [Authentification](https://opencode.ai/docs/fr/server#authentification-1) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Définissez les informations d’authentification. Le corps doit correspondre au schéma du fournisseur | `boolean` | * * * ### [Événements](https://opencode.ai/docs/fr/server#%C3%A9v%C3%A9nements) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/event` | Flux d’événements envoyés par le serveur. Le premier événement est `server.connected`, puis les événements de bus | Flux d’événements envoyés par le serveur | * * * ### [Documents](https://opencode.ai/docs/fr/server#documents) | Méthode | Chemin | Descriptif | Réponse | | --- | --- | --- | --- | | `GET` | `/doc` | Spécification OpenAPI 3.1 | Page HTML avec spécification OpenAPI | --- # Formateadores | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/formatters#_top) Formateadores ============= OpenCode utiliza formateadores específicos del idioma. OpenCode formatea automáticamente los archivos después de escribirlos o editarlos utilizando formateadores específicos del idioma. Esto garantiza que el código generado siga los estilos de código de su proyecto. * * * [Integrados](https://opencode.ai/docs/es/formatters#integrados) ---------------------------------------------------------------- OpenCode viene con varios formateadores integrados para lenguajes y marcos populares. A continuación se muestra una lista de los formateadores, las extensiones de archivo compatibles y los comandos u opciones de configuración que necesita. | Formateador | Extensiones | Requisitos | | --- | --- | --- | | gofmt | .go | Comando `gofmt` disponible | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Comando `mix` disponible | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml y [más](https://prettier.io/docs/en/index.html) | dependencia `prettier` en `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml y [más](https://biomejs.dev/) | `biome.json(c)` archivo de configuración | | zig | .zig, .zon | Comando `zig` disponible | | clang-format | .c, .cpp, .h, .hpp, .ino y [más](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` archivo de configuración | | ktlint | .kt, .kts | Comando `ktlint` disponible | | ruff | .py, .pyi | Comando `ruff` disponible con configuración | | rustfmt | .rs | Comando `rustfmt` disponible | | cargo fmt | .rs | Comando `cargo fmt` disponible | | uv | .py, .pyi | Comando `uv` disponible | | rubocop | .rb, .rake, .gemspec, .ru | Comando `rubocop` disponible | | standardrb | .rb, .rake, .gemspec, .ru | Comando `standardrb` disponible | | htmlbeautifier | .erb, .html.erb | Comando `htmlbeautifier` disponible | | air | .R | Comando `air` disponible | | dart | .dart | Comando `dart` disponible | | dfmt | .d | Comando `dfmt` disponible | | ocamlformat | .ml, .mli | Comando `ocamlformat` disponible y archivo de configuración `.ocamlformat` | | terraform | .tf, .tfvars | Comando `terraform` disponible | | gleam | .gleam | Comando `gleam` disponible | | nixfmt | .nix | Comando `nixfmt` disponible | | shfmt | .sh, .bash | Comando `shfmt` disponible | | pint | .php | dependencia `laravel/pint` en `composer.json` | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | Dependencia de `oxfmt` en `package.json` y un [indicador de variable de entorno experimental](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | Comando `ormolu` disponible | Entonces, si su proyecto tiene `prettier` en su `package.json`, OpenCode lo usará automáticamente. * * * [Cómo funciona](https://opencode.ai/docs/es/formatters#c%C3%B3mo-funciona) --------------------------------------------------------------------------- Cuando OpenCode escribe o edita un archivo: 1. Comprueba la extensión del archivo con todos los formateadores habilitados. 2. Ejecuta el comando de formateo apropiado en el archivo. 3. Aplica los cambios de formato automáticamente. Este proceso ocurre en segundo plano, lo que garantiza que los estilos de su código se mantengan sin ningún paso manual. * * * [Configuración](https://opencode.ai/docs/es/formatters#configuraci%C3%B3n) --------------------------------------------------------------------------- Puede personalizar los formateadores a través de la sección `formatter` en su configuración OpenCode. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Cada configuración del formateador admite lo siguiente: | Propiedad | Tipo | Descripción | | --- | --- | --- | | `disabled` | booleano | Establezca esto en `true` para deshabilitar el formateador | | `command` | cadena\[\] | El comando a ejecutar para formatear | | `environment` | objeto | Variables de entorno para configurar al ejecutar el formateador | | `extensions` | cadena\[\] | Extensiones de archivo que este formateador debería manejar | Veamos algunos ejemplos. * * * ### [Deshabilitar formateadores](https://opencode.ai/docs/es/formatters#deshabilitar-formateadores) Para deshabilitar **todos** los formateadores globalmente, configure `formatter` en `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} Para deshabilitar un formateador **específico**, establezca `disabled` en `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Formateadores personalizados](https://opencode.ai/docs/es/formatters#formateadores-personalizados) Puede anular los formateadores integrados o agregar otros nuevos especificando el comando, las variables de entorno y las extensiones de archivo: { "$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"] } }} El marcador de posición **`$FILE`** en el comando se reemplazará con la ruta al archivo que se está formateando. --- # Server | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/server#_top) Server ====== Interagisci con il server opencode via HTTP. Il comando `opencode serve` avvia un server HTTP headless che espone un endpoint OpenAPI utilizzabile da un client opencode. * * * ### [Utilizzo](https://opencode.ai/docs/it/server#utilizzo) opencode serve [--port ] [--hostname ] [--cors ] #### [Opzioni](https://opencode.ai/docs/it/server#opzioni) | Flag | Descrizione | Predefinito | | --- | --- | --- | | `--port` | Porta su cui ascoltare | `4096` | | `--hostname` | Hostname su cui ascoltare | `127.0.0.1` | | `--mdns` | Abilita la scoperta mDNS | `false` | | `--mdns-domain` | Nome di dominio personalizzato mDNS | `opencode.local` | | `--cors` | Origin browser aggiuntive da permettere | `[]` | `--cors` puo essere passato piu volte: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Autenticazione](https://opencode.ai/docs/it/server#autenticazione) Imposta `OPENCODE_SERVER_PASSWORD` per proteggere il server con HTTP basic auth. Lo username predefinito e `opencode`, oppure imposta `OPENCODE_SERVER_USERNAME` per sovrascriverlo. Questo vale sia per `opencode serve` sia per `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Come funziona](https://opencode.ai/docs/it/server#come-funziona) Quando esegui `opencode` avvia una TUI e un server. La TUI e il client che parla col server. Il server espone un endpoint con specifica OpenAPI 3.1. Questo endpoint viene anche usato per generare un [SDK](https://opencode.ai/docs/sdk) . Questa architettura permette a opencode di supportare piu client e di essere usato in modo programmatico. Puoi eseguire `opencode serve` per avviare un server standalone. Se la TUI di opencode e gia in esecuzione, `opencode serve` avviera un nuovo server. * * * #### [Connettersi a un server esistente](https://opencode.ai/docs/it/server#connettersi-a-un-server-esistente) Quando avvii la TUI assegna casualmente porta e hostname. In alternativa puoi passare i [flag](https://opencode.ai/docs/cli) `--hostname` e `--port` e poi usare questi valori per connetterti al suo server. L’endpoint [`/tui`](https://opencode.ai/docs/it/server#tui) puo essere usato per pilotare la TUI tramite il server. Per esempio, puoi precompilare o eseguire un prompt. Questa configurazione e usata dai plugin [IDE](https://opencode.ai/docs/ide) di OpenCode. * * * [Specifica](https://opencode.ai/docs/it/server#specifica) ---------------------------------------------------------- Il server pubblica una specifica OpenAPI 3.1 visualizzabile su: http://:/doc Per esempio, `http://localhost:4096/doc`. Usa la spec per generare client o ispezionare i tipi di request/response, oppure visualizzala in uno Swagger explorer. * * * [API](https://opencode.ai/docs/it/server#api) ---------------------------------------------- Il server opencode espone le seguenti API. * * * ### [Globale](https://opencode.ai/docs/it/server#globale) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/global/health` | Stato di salute e versione | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Eventi globali (stream SSE) | Event stream | * * * ### [Progetto](https://opencode.ai/docs/it/server#progetto) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/project` | Elenca tutti i progetti | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Progetto corrente | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Percorso e VCS](https://opencode.ai/docs/it/server#percorso-e-vcs) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/path` | Percorso corrente | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Info VCS per il progetto corrente | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Istanza](https://opencode.ai/docs/it/server#istanza) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Rilascia l’istanza corrente | `boolean` | * * * ### [Configurazione](https://opencode.ai/docs/it/server#configurazione) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/config` | Info sulla config | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Aggiorna la config | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Elenca provider e modelli default | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Fornitori](https://opencode.ai/docs/it/server#fornitori) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/provider` | Elenca tutti i provider | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Metodi auth dei provider | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autorizza un provider via OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Gestisce callback OAuth | `boolean` | * * * ### [Sessioni](https://opencode.ai/docs/it/server#sessioni) | Metodo | Path | Descrizione | Note | | --- | --- | --- | --- | | `GET` | `/session` | Elenca tutte le sessioni | Returns [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Crea una nuova sessione | body: `{ parentID?, title? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Stato di tutte le sessioni | Returns `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Dettagli di sessione | Returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Elimina una sessione e i suoi dati | Returns `boolean` | | `PATCH` | `/session/:id` | Aggiorna proprieta sessione | body: `{ title? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Sessioni figlie | Returns [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Todo list della sessione | Returns [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Analizza app e crea `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returns `boolean` | | `POST` | `/session/:id/fork` | Fork di sessione su un messaggio | body: `{ messageID? }`, returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Interrompe una sessione in esecuzione | Returns `boolean` | | `POST` | `/session/:id/share` | Condivide una sessione | Returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Annulla condivisione | Returns [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Diff della sessione | query: `messageID?`, returns [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Riassume la sessione | body: `{ providerID, modelID }`, returns `boolean` | | `POST` | `/session/:id/revert` | Ripristina un messaggio | body: `{ messageID, partID? }`, returns `boolean` | | `POST` | `/session/:id/unrevert` | Ripristina tutti i messaggi revertiti | Returns `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Risponde a una richiesta permessi | body: `{ response, remember? }`, returns `boolean` | * * * ### [Messaggi](https://opencode.ai/docs/it/server#messaggi) | Metodo | Path | Descrizione | Note | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Elenca messaggi in una sessione | query: `limit?`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Invia un messaggio e attende risposta | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Dettagli messaggio | Returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Invia un messaggio in async (senza wait) | body: same as `/session/:id/message`, returns `204 No Content` | | `POST` | `/session/:id/command` | Esegue un comando slash | body: `{ messageID?, agent?, model?, command, arguments }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Esegue un comando shell | body: `{ agent, model?, command }`, returns `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Comandi](https://opencode.ai/docs/it/server#comandi) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/command` | Elenca i comandi | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [File](https://opencode.ai/docs/it/server#file) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Cerca testo nei file | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Trova file e directory per nome | `string[]` (paths) | | `GET` | `/find/symbol?query=` | Trova simboli workspace | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Elenca file e directory | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Legge un file | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Stato dei file tracciati | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` query parameters](https://opencode.ai/docs/it/server#findfile-query-parameters) * `query` (required) — stringa di ricerca (fuzzy match) * `type` (optional) — limita i risultati a `"file"` o `"directory"` * `directory` (optional) — sovrascrive la root del progetto per la ricerca * `limit` (optional) — massimo risultati (1–200) * `dirs` (optional) — flag legacy (`"false"` restituisce solo file) * * * ### [Strumenti (sperimentale)](https://opencode.ai/docs/it/server#strumenti-sperimentale) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Elenca tutti i tool ID | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Elenca tool con JSON schema per un modello | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, formatter e MCP](https://opencode.ai/docs/it/server#lsp-formatter-e-mcp) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/lsp` | Stato server LSP | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Stato formatter | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Stato server MCP | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Aggiunge server MCP runtime | body: `{ name, config }`, returns MCP status object | * * * ### [Agenti](https://opencode.ai/docs/it/server#agenti) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/agent` | Elenca tutti gli agenti | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Log](https://opencode.ai/docs/it/server#log) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `POST` | `/log` | Scrive una voce di log. Body: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/it/server#tui) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Aggiunge testo al prompt | `boolean` | | `POST` | `/tui/open-help` | Apre il dialog help | `boolean` | | `POST` | `/tui/open-sessions` | Apre il selettore sessioni | `boolean` | | `POST` | `/tui/open-themes` | Apre il selettore temi | `boolean` | | `POST` | `/tui/open-models` | Apre il selettore modelli | `boolean` | | `POST` | `/tui/submit-prompt` | Invia il prompt corrente | `boolean` | | `POST` | `/tui/clear-prompt` | Pulisce il prompt | `boolean` | | `POST` | `/tui/execute-command` | Esegue un comando (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Mostra toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Attende la prossima richiesta di controllo | Control request object | | `POST` | `/tui/control/response` | Risponde a una richiesta di controllo (`{ body }`) | `boolean` | * * * ### [Autenticazione](https://opencode.ai/docs/it/server#autenticazione-1) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Imposta credenziali auth. Il body deve rispettare lo schema provider | `boolean` | * * * ### [Eventi](https://opencode.ai/docs/it/server#eventi) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/event` | Stream SSE. Primo evento `server.connected`, poi eventi bus | Server-sent events stream | * * * ### [Documentazione](https://opencode.ai/docs/it/server#documentazione) | Metodo | Path | Descrizione | Response | | --- | --- | --- | --- | | `GET` | `/doc` | Specifica OpenAPI 3.1 | Pagina HTML con spec OpenAPI | --- # Formateurs | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/formatters#_top) Formateurs ========== OpenCode utilise des formateurs spécifiques au langage. OpenCode formate automatiquement les fichiers après leur écriture ou leur modification à l’aide de formateurs spécifiques au langage. Cela garantit que le code généré suit les styles de code de votre projet. * * * [Formateurs intégrés](https://opencode.ai/docs/fr/formatters#formateurs-int%C3%A9gr%C3%A9s) -------------------------------------------------------------------------------------------- OpenCode est livré avec plusieurs formateurs intégrés pour les langages et frameworks populaires. Vous trouverez ci-dessous une liste des formateurs, des extensions de fichiers prises en charge et des commandes ou options de configuration dont il a besoin. | Formateur | Extensions | Prérequis | | --- | --- | --- | | gofmt | .go | Commande `gofmt` disponible | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Commande `mix` disponible | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml et [plus](https://prettier.io/docs/en/index.html) | Dépendance `prettier` dans `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml et [plus](https://biomejs.dev/) | Fichier de configuration `biome.json(c)` | | zig | .zig, .zon | Commande `zig` disponible | | clang-format | .c, .cpp, .h, .hpp, .ino et [plus](https://clang.llvm.org/docs/ClangFormat.html) | Fichier de configuration `.clang-format` | | ktlint | .kt, .kts | Commande `ktlint` disponible | | ruff | .py, .pyi | Commande `ruff` disponible avec config | | rustfmt | .rs | Commande `rustfmt` disponible | | cargofmt | .rs | Commande `cargo fmt` disponible | | uv | .py, .pyi | Commande `uv` disponible | | rubocop | .rb, .rake, .gemspec, .ru | Commande `rubocop` disponible | | standardrb | .rb, .rake, .gemspec, .ru | Commande `standardrb` disponible | | htmlbeautifier | .erb, .html.erb | Commande `htmlbeautifier` disponible | | air | .R | Commande `air` disponible | | dart | .dart | Commande `dart` disponible | | dfmt | .d | Commande `dfmt` disponible | | ocamlformat | .ml, .mli | Commande `ocamlformat` disponible et fichier de configuration `.ocamlformat` | | terraform | .tf, .tfvars | Commande `terraform` disponible | | gleam | .gleam | Commande `gleam` disponible | | nixfmt | .nix | Commande `nixfmt` disponible | | shfmt | .sh, .bash | Commande `shfmt` disponible | | pint | .php | Dépendance `laravel/pint` dans `composer.json` | | oxfmt (expérimental) | .js, .jsx, .ts, .tsx | Dépendance `oxfmt` dans `package.json` et un [flag de variable d’environnement expérimental](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | Commande `ormolu` disponible | Ainsi, si votre projet a `prettier` dans votre `package.json`, OpenCode l’utilisera automatiquement. * * * [Comment ça marche](https://opencode.ai/docs/fr/formatters#comment-%C3%A7a-marche) ----------------------------------------------------------------------------------- Lorsque OpenCode écrit ou modifie un fichier, il : 1. Vérifie l’extension du fichier par rapport à tous les formateurs activés. 2. Exécute la commande de formatage appropriée sur le fichier. 3. Applique automatiquement les modifications de formatage. Ce processus se déroule en arrière-plan, garantissant que vos styles de code sont conservés sans aucune étape manuelle. * * * [Configuration](https://opencode.ai/docs/fr/formatters#configuration) ---------------------------------------------------------------------- Vous pouvez personnaliser les formateurs via la section `formatter` de votre configuration OpenCode. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Chaque configuration du formateur prend en charge les éléments suivants : | Propriété | Type | Description | | --- | --- | --- | | `disabled` | booléen | Définissez ceci sur `true` pour désactiver le formateur | | `command` | chaîne\[\] | La commande à exécuter pour le formatage | | `environment` | objet | Variables d’environnement à définir lors de l’exécution du formateur | | `extensions` | chaîne\[\] | Extensions de fichiers que ce formateur doit gérer | Regardons quelques exemples. * * * ### [Désactivation des formateurs](https://opencode.ai/docs/fr/formatters#d%C3%A9sactivation-des-formateurs) Pour désactiver **tous** les formateurs globalement, définissez `formatter` sur `false` : { "$schema": "https://opencode.ai/config.json", "formatter": false} Pour désactiver un formateur **spécifique**, définissez `disabled` sur `true` : { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Formateurs personnalisés](https://opencode.ai/docs/fr/formatters#formateurs-personnalis%C3%A9s) Vous pouvez remplacer les formateurs intégrés ou en ajouter de nouveaux en spécifiant la commande, les variables d’environnement et les extensions de fichier : { "$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"] } }} L’espace réservé **`$FILE`** dans la commande sera remplacé par le chemin d’accès au fichier en cours de formatage. --- # Formatery | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/formatters#_top) Formatery ========= OpenCode używa formaterów specyficznych dla języka. OpenCode automatycznie formatuje pliki po ich zapisaniu lub edycji przy użyciu formaterów specyficznych dla języka. Zapewnia to, że wygenerowany kod jest zgodny ze stylem kodu Twojego projektu. * * * [Wbudowane](https://opencode.ai/docs/pl/formatters#wbudowane) -------------------------------------------------------------- OpenCode zawiera kilka wbudowanych formaterów dla popularnych języków i frameworków. Poniższa tabela zawiera listę formaterów, obsługiwanych plików oraz wymagań konfiguracyjnych. | Formater | Rozszerzenia | Wymagania | | --- | --- | --- | | gofmt | .go | Dostępne polecenie `gofmt` | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Dostępne polecenie `mix` | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml i [więcej](https://prettier.io/docs/en/index.html) | Zależność `prettier` w `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml i [więcej](https://biomejs.dev/) | Plik konfiguracyjny `biome.json(c)` | | zig | .zig, .zon | Dostępne polecenie `zig` | | clang-format | .c, .cpp, .h, .hpp, .ino i [więcej](https://clang.llvm.org/docs/ClangFormat.html) | Plik konfiguracyjny `.clang-format` | | ktlint | .kt, .kts | Dostępne polecenie `ktlint` | | ruff | .py, .pyi | Dostępne polecenie `ruff` | | rustfmt | .rs | Dostępne polecenie `rustfmt` | | cargo | .rs | Dostępne polecenie `cargo fmt` | | uv | .py, .pyi | Dostępne polecenie `uv` | | rubocop | .rb, .rake, .gemspec, .ru | Dostępne polecenie `rubocop` | | standardrb | .rb, .rake, .gemspec, .ru | Dostępne polecenie `standardrb` | | htmlbeautifier | .erb, .html.erb | Dostępne polecenie `htmlbeautifier` | | air | .R | Dostępne polecenie `air` | | dart | .dart | Dostępne polecenie `dart` | | dfmt | .d | Dostępne polecenie `dfmt` | | ocamlformat | .ml, .mli | Dostępne polecenie `ocamlformat` i plik konfiguracyjny `.ocamlformat` | | terraform | .tf, .tfvars | Dostępne polecenie `terraform` | | gleam | .gleam | Dostępne polecenie `gleam` | | nixfmt | .nix | Dostępne polecenie `nixfmt` | | shfmt | .sh, .bash | Dostępne polecenie `shfmt` | | pint | .php | Zależność `laravel/pint` w `composer.json` | | oxfmt (experimental) | .js, .jsx, .ts, .tsx | Zależność `oxfmt` w `package.json` i [eksperymentalna flaga](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | Dostępne polecenie `ormolu` | Jeśli więc Twój projekt zawiera `prettier` w `package.json`, OpenCode automatycznie go użyje. * * * [Jak to działa](https://opencode.ai/docs/pl/formatters#jak-to-dzia%C5%82a) --------------------------------------------------------------------------- Kiedy OpenCode zapisuje lub edytuje plik: 1. Sprawdza plik pod kątem wszystkich dostępnych formaterów. 2. Uruchamia odpowiedni formater na pliku. 3. Automatycznie stosuje zmiany formatowania. Ten proces odbywa się w tle, zapewniając spójność stylu kodu bez konieczności ręcznej interwencji. * * * [Konfiguracja](https://opencode.ai/docs/pl/formatters#konfiguracja) -------------------------------------------------------------------- Możesz dostosować formatery za pomocą sekcji `formatter` w konfiguracji OpenCode. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Każdy formater obsługuje następujące właściwości: | Właściwość | Typ | Opis | | --- | --- | --- | | `disabled` | boolean | Ustaw na `true`, aby wyłączyć ten formater | | `command` | string\[\] | Polecenie uruchomienia formatera | | `environment` | object | Zmienne środowiskowe ustawiane podczas uruchamiania | | `extensions` | string\[\] | Rozszerzenia plików, które powinny używać tego formatera | Spójrzmy na kilka przykładów. * * * ### [Wyłączanie formaterów](https://opencode.ai/docs/pl/formatters#wy%C5%82%C4%85czanie-formater%C3%B3w) Aby globalnie wyłączyć **wszystkie** formatery, ustaw `formatter` na `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} Aby wyłączyć **określony** formater, ustaw `disabled` na `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Niestandardowe formatery](https://opencode.ai/docs/pl/formatters#niestandardowe-formatery) Możesz dodać niestandardowe formatery, podając polecenie, zmienne środowiskowe i rozszerzenia plików: { "$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"] } }} Symbol zastępczy **`$FILE`** w poleceniu jest zastępowany ścieżką do formatowanego pliku. --- # Server | OpenCode [Gå til indhold](https://opencode.ai/docs/da/server#_top) Server ====== Interager med opencode-serveren over HTTP. Kommandoen `opencode serve` kører en hovedløs HTTP-server, som afslører et OpenAPI-endpoint, som en opencode-klient kan bruge. * * * ### [Brug](https://opencode.ai/docs/da/server#brug) opencode serve [--port ] [--hostname ] [--cors ] #### [Indstillinger](https://opencode.ai/docs/da/server#indstillinger) | Flag | Beskrivelse | Standard | | --- | --- | --- | | `--port` | Port at lytte på | `4096` | | `--hostname` | Værtsnavn at lytte på | `127.0.0.1` | | `--mdns` | Aktiver mDNS-opdagelse | `false` | | `--mdns-domain` | Brugerdefineret domænenavn for mDNS-tjeneste | `opencode.local` | | `--cors` | Yderligere browseroprindelse for at tillade | `[]` | `--cors` kan angives flere gange: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Godkendelse](https://opencode.ai/docs/da/server#godkendelse) Indstil `OPENCODE_SERVER_PASSWORD` for at beskytte serveren med HTTP grundlæggende godkendelse. Brugernavnet er som standard `opencode`, eller indstil `OPENCODE_SERVER_USERNAME` for at tilsidesætte det. Dette gælder både `opencode serve` og `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Sådan fungerer det](https://opencode.ai/docs/da/server#s%C3%A5dan-fungerer-det) Når du kører `opencode` starter den en TUI og en server. Hvor TUI er klient som taler med serveren. Serveren viser en OpenAPI 3.1-specifikation endpoint. Dette endpoint bruges også til at generere en [SDK](https://opencode.ai/docs/sdk) . Denne arkitektur lader opencode understøtte flere klienter og lader dig interagere med opencode programmatisk. Du kan køre `opencode serve` for at starte en selvstændig server. Hvis du har opencode TUI kørende, vil `opencode serve` starte en ny server. * * * #### [Opret forbindelse til en eksisterende server](https://opencode.ai/docs/da/server#opret-forbindelse-til-en-eksisterende-server) Når du starter TUI, tildeler den tilfældigt en port og et værtsnavn. Du kan i stedet sende `--hostname` og `--port` [flagene](https://opencode.ai/docs/cli) . Brug derefter disse til at forbinde til serveren. [`/tui`](https://opencode.ai/docs/da/server#tui) endpointet kan bruges til at køre TUI gennem serveren. Du kan for eksempel forududfylde eller køre en forespørgsel. Denne opsætning bruges af OpenCode [IDE](https://opencode.ai/docs/ide) plugins. * * * [Specifikation](https://opencode.ai/docs/da/server#specifikation) ------------------------------------------------------------------ Serveren publicerer en OpenAPI 3.1-specifikation som kan vises på: http://:/doc For eksempel `http://localhost:4096/doc`. Brug specifikationen til at generere klienter eller inspicere forespørgsels- og svartyper. Eller se den i en Swagger-utforsker. * * * [API’er](https://opencode.ai/docs/da/server#apier) --------------------------------------------------- OpenCode-serveren viser følgende API’er. * * * ### [Globalt](https://opencode.ai/docs/da/server#globalt) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/global/health` | Få serverhelbred og version | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Få globale hændelser (SSE strøm) | Eventstrøm | * * * ### [Projekt](https://opencode.ai/docs/da/server#projekt) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/project` | Liste over alle projekter | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Få det nuværende projekt | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Sti og VCS](https://opencode.ai/docs/da/server#sti-og-vcs) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/path` | Få nuværende sti | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Få VCS info for nuværende projekt | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Instans](https://opencode.ai/docs/da/server#instans) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Kassér nuværende instans | `boolean` | * * * ### [Konfiguration](https://opencode.ai/docs/da/server#konfiguration) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/config` | Få konfigurationsinformation | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Opdater konfiguration | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Liste udbydere og standardmodeller | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Udbyder](https://opencode.ai/docs/da/server#udbyder) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/provider` | Liste alle udbydere | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Få udbydergodkendelsesmetoder | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autoriser en udbyder ved at bruge OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Håndter OAuth-callback for en udbyder | `boolean` | * * * ### [Sessioner](https://opencode.ai/docs/da/server#sessioner) | Metode | Sti | Beskrivelse | Noter | | --- | --- | --- | --- | | `GET` | `/session` | Liste alle sessioner | Returnerer [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Opret en ny session | body: `{ parentID?, title? }`, returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Få sessionstatus for alle sessioner | Returnerer `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Få sessiondetaljer | Returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Slet en session og alle dens data | Returnerer `boolean` | | `PATCH` | `/session/:id` | Opdater sessionegenskaber | body: `{ title? }`, returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Få en sessions undersessioner | Returnerer [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Få to-do-listen for en session | Returnerer [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Analyser appen og lav `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returnerer `boolean` | | `POST` | `/session/:id/fork` | Fork en eksisterende session ved en besked | body: `{ messageID? }`, returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Afbryd en kørende session | Returnerer `boolean` | | `POST` | `/session/:id/share` | Del en session | Returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Stop med at dele en session | Returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Få diff for denne session | query: `messageID?`, returnerer [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Opsummér sessionen | body: `{ providerID, modelID }`, returnerer `boolean` | | `POST` | `/session/:id/revert` | Tilbagestil en besked | body: `{ messageID, partID? }`, returnerer `boolean` | | `POST` | `/session/:id/unrevert` | Gendan alle nulstillede beskeder | Returnerer `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Svar på en tilladelsesforespørgsel | body: `{ response, remember? }`, returnerer `boolean` | * * * ### [Beskeder](https://opencode.ai/docs/da/server#beskeder) | Metode | Sti | Beskrivelse | Noter | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Liste beskeder i en session | query: `limit?`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Send en besked og vent på svar | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Få beskeddetaljer | Returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Send en besked asynkront (ingen vent) | body: samme som `/session/:id/message`, returnerer `204 No Content` | | `POST` | `/session/:id/command` | Udfør en skråstregskommando | body: `{ messageID?, agent?, model?, command, arguments }`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Kør en shell-kommando | body: `{ agent, model?, command }`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Kommandoer](https://opencode.ai/docs/da/server#kommandoer) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/command` | Liste alle kommandoer | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Filer](https://opencode.ai/docs/da/server#filer) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Søg efter tekst i filer | En række matchobjekter med `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Find filer og mapper efter navn | `string[]` (stier) | | `GET` | `/find/symbol?query=` | Find arbejdsområdesymboler | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Liste filer og mapper | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Læs en fil | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Få status for sporede filer | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [/find/file forespørgselsparametre](https://opencode.ai/docs/da/server#findfile-foresp%C3%B8rgselsparametre) * `query` (obligatorisk) - søgestreng (fuzzy match) * `type` (valgfrit) - begræns resultaterne til `"file"` eller `"directory"` * `directory` (valgfrit) — overstyr projektroden for søget * `limit` (valgfrit) - maks. resultater (1–200) * `dirs` (valgfrit) - ældre flag (`"false"` returnerer kun filer) * * * ### [Værktøjer (eksperimentelt)](https://opencode.ai/docs/da/server#v%C3%A6rkt%C3%B8jer-eksperimentelt) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Vis alle værktøjs-ID’er | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Liste værktøjer med JSON-skemaer for en model | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, formattere og MCP](https://opencode.ai/docs/da/server#lsp-formattere-og-mcp) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/lsp` | Få LSP serverstatus | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Få formateringsstatus | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Få MCP serverstatus | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Tilføj MCP server dynamisk | body: `{ name, config }`, returnerer MCP statusobjekt | * * * ### [Agenter](https://opencode.ai/docs/da/server#agenter) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/agent` | Liste alle tilgængelige agenter | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Logning](https://opencode.ai/docs/da/server#logning) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `POST` | `/log` | Skriv logpost. Body: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/da/server#tui) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Tilføj tekst til prompten | `boolean` | | `POST` | `/tui/open-help` | Åbn hjælp-dialogen | `boolean` | | `POST` | `/tui/open-sessions` | Åbn sessionsvælgeren | `boolean` | | `POST` | `/tui/open-themes` | Åbn temavælgeren | `boolean` | | `POST` | `/tui/open-models` | Åbn modelvælgeren | `boolean` | | `POST` | `/tui/submit-prompt` | Indsend nuværende prompt | `boolean` | | `POST` | `/tui/clear-prompt` | Ryd prompten | `boolean` | | `POST` | `/tui/execute-command` | Udfør en kommando (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Vis toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Vent på næste kontrolforespørgsel | Kontrolforespørgselsobjekt | | `POST` | `/tui/control/response` | Svar på en kontrolforespørgsel (`{ body }`) | `boolean` | * * * ### [Godkendelse](https://opencode.ai/docs/da/server#godkendelse-1) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Angiv godkendelsesoplysninger. Body skal matche udbyderskema | `boolean` | * * * ### [Hændelser](https://opencode.ai/docs/da/server#h%C3%A6ndelser) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/event` | Server-sendt hændelsesstrøm. Første hændelse er `server.connected`, derefter bushændelser | Server-sendt hændelsesstrøm | * * * ### [Dokumentation](https://opencode.ai/docs/da/server#dokumentation) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1-specifikation | HTML side med OpenAPI-specifikation | --- # Tjener | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/server#_top) Tjener ====== Samhandle med OpenCode-tjener over HTTP. Kommandoen `opencode serve` kjører en hodeløs HTTP-server som eksponerer et OpenAPI-endepunkt som en OpenCode-klient kan bruke. * * * ### [Bruk](https://opencode.ai/docs/nb/server#bruk) opencode serve [--port ] [--hostname ] [--cors ] #### [Alternativer](https://opencode.ai/docs/nb/server#alternativer) | Flagg | Beskrivelse | Standard | | --- | --- | --- | | `--port` | Port å lytte på | `4096` | | `--hostname` | Vertsnavn å lytte på | `127.0.0.1` | | `--mdns` | Aktiver mDNS-oppdagelse | `false` | | `--mdns-domain` | Egendefinert domenenavn for mDNS-tjeneste | `opencode.local` | | `--cors` | Ytterligere nettleseropprinnelse som tillates | `[]` | `--cors` kan angis flere ganger: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Autentisering](https://opencode.ai/docs/nb/server#autentisering) Sett `OPENCODE_SERVER_PASSWORD` for å beskytte serveren med HTTP grunnleggende autentisering. Brukernavnet er satt til `opencode` som standard, eller sett `OPENCODE_SERVER_USERNAME` for å overstyre det. Dette gjelder både `opencode serve` og `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Slik fungerer det](https://opencode.ai/docs/nb/server#slik-fungerer-det) Når du kjører `opencode` starter den en TUI og en server. Der TUI er klient som snakker med serveren. Serveren viser en OpenAPI 3.1-spesifikasjon endepunkt. Dette endepunktet brukes også til å generere en [SDK](https://opencode.ai/docs/sdk) . Denne arkitekturen lar OpenCode støtte flere klienter og lar deg samhandle med OpenCode programmatisk. Du kan kjøre `opencode serve` for å starte en frittstående server. Hvis du har OpenCode TUI kjører, vil `opencode serve` starte en ny server. * * * #### [Koble til en eksisterende server](https://opencode.ai/docs/nb/server#koble-til-en-eksisterende-server) Når du starter TUI, tildeler den tilfeldig en port og vertsnavn. Du kan i stedet sende inn `--hostname` og `--port` [flagg](https://opencode.ai/docs/cli) . Bruk deretter denne til å koble til serveren. [`/tui`](https://opencode.ai/docs/nb/server#tui) endepunktet kan brukes til å kjøre TUI gjennom serveren. Du kan for eksempel forhåndsutfylle eller kjøre en forespørsel. Dette oppsettet brukes av OpenCode [IDE](https://opencode.ai/docs/ide) plugins. * * * [Spes](https://opencode.ai/docs/nb/server#spes) ------------------------------------------------ Serveren publiserer en OpenAPI 3.1-spesifikasjon som kan vises på: http://:/doc For eksempel `http://localhost:4096/doc`. Bruk spesifikasjonen til å generere klienter eller inspisere forespørsels- og svartyper. Eller se den i en Swagger-utforsker. * * * [APIer](https://opencode.ai/docs/nb/server#apier) -------------------------------------------------- opencode-serveren viser følgende APIer. * * * ### [Globalt](https://opencode.ai/docs/nb/server#globalt) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/global/health` | Få serverhelse og versjon | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Få globale hendelser (SSE strøm) | Eventstrøm | * * * ### [Prosjekt](https://opencode.ai/docs/nb/server#prosjekt) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/project` | List alle prosjekter | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Hent gjeldende prosjekt | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Bane og VCS](https://opencode.ai/docs/nb/server#bane-og-vcs) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/path` | Hent gjeldende bane | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Hent VCS-info for gjeldende prosjekt | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Forekomst](https://opencode.ai/docs/nb/server#forekomst) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Avslutt gjeldende forekomst | `boolean` | * * * ### [Konfigurasjon](https://opencode.ai/docs/nb/server#konfigurasjon) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/config` | Hent konfigurasjonsinformasjon | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Oppdater konfigurasjon | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | List leverandører og standardmodeller | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Leverandør](https://opencode.ai/docs/nb/server#leverand%C3%B8r) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/provider` | List alle leverandører | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Hent autentiseringsmetoder for leverandør | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autoriser en leverandør ved å bruke OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Håndter OAuth-tilbakeringing for en leverandør | `boolean` | * * * ### [Sesjoner](https://opencode.ai/docs/nb/server#sesjoner) | Metode | Sti | Beskrivelse | Merknader | | --- | --- | --- | --- | | `GET` | `/session` | List alle økter | Returnerer [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Opprett en ny økt | body: `{ parentID?, title? }`, returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Hent øktstatus for alle økter | Returnerer `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Hent øktdetaljer | Returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Slett en økt og alle dens data | Returnerer `boolean` | | `PATCH` | `/session/:id` | Oppdater øktegenskaper | body: `{ title? }`, returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Hent en økts barneøkter | Returnerer [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Hent gjøremålslisten for en økt | Returnerer [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Analyser appen og lag `AGENTS.md` | body: `{ messageID, providerID, modelID }`, returnerer `boolean` | | `POST` | `/session/:id/fork` | Fork en eksisterende økt ved en melding | body: `{ messageID? }`, returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Avbryt en kjørende økt | Returnerer `boolean` | | `POST` | `/session/:id/share` | Del en økt | Returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Slutt å dele en økt | Returnerer [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Hent diff for denne økten | spørring: `messageID?`, returnerer [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Oppsummer økten | body: `{ providerID, modelID }`, returnerer `boolean` | | `POST` | `/session/:id/revert` | Tilbakestill en melding | body: `{ messageID, partID? }`, returnerer `boolean` | | `POST` | `/session/:id/unrevert` | Gjenopprett alle tilbakestilte meldinger | Returnerer `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Svar på en tillatelsesforespørsel | body: `{ response, remember? }`, returnerer `boolean` | * * * ### [Meldinger](https://opencode.ai/docs/nb/server#meldinger) | Metode | Sti | Beskrivelse | Merknader | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | List meldinger i en økt | spørring: `limit?`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Send en melding og vent på svar | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Hent meldingsdetaljer | Returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Send en melding asynkront (ingen vent) | body: samme som `/session/:id/message`, returnerer `204 No Content` | | `POST` | `/session/:id/command` | Utfør en slash-kommando | body: `{ messageID?, agent?, model?, command, arguments }`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Kjør en shell-kommando | body: `{ agent, model?, command }`, returnerer `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Kommandoer](https://opencode.ai/docs/nb/server#kommandoer) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/command` | List alle kommandoer | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Filer](https://opencode.ai/docs/nb/server#filer) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Søk etter tekst i filer | En rekke matchobjekter med `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Finn filer og kataloger etter navn | `string[]` (baner) | | `GET` | `/find/symbol?query=` | Finn symboler i arbeidsområdet | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | List filer og kataloger | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Les en fil | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Hent status for sporede filer | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` spørringsparametere](https://opencode.ai/docs/nb/server#findfile-sp%C3%B8rringsparametere) * `query` (obligatorisk) - søkestreng (uklar samsvar) * `type` (valgfritt) - begrense resultatene til `"file"` eller `"directory"` * `directory` (valgfritt) — overstyr prosjektroten for søket * `limit` (valgfritt) - maks. resultater (1–200) * `dirs` (valgfritt) - eldre flagg (`"false"` returnerer kun filer) * * * ### [Verktøy (eksperimentelt)](https://opencode.ai/docs/nb/server#verkt%C3%B8y-eksperimentelt) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Vis alle verktøy-ID-er | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | List verktøy med JSON-skjemaer for en modell | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, formattere og MCP](https://opencode.ai/docs/nb/server#lsp-formattere-og-mcp) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/lsp` | Hent LSP-serverstatus | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Hent formateringsstatus | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Hent MCP-serverstatus | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Legg til MCP-server dynamisk | body: `{ name, config }`, returnerer MCP statusobjekt | * * * ### [Agenter](https://opencode.ai/docs/nb/server#agenter) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/agent` | List alle tilgjengelige agenter | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Logging](https://opencode.ai/docs/nb/server#logging) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `POST` | `/log` | Skriv loggoppføring. Body: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/nb/server#tui) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Legg til tekst i prompten | `boolean` | | `POST` | `/tui/open-help` | Åpne hjelpedialogen | `boolean` | | `POST` | `/tui/open-sessions` | Åpne øktvelgeren | `boolean` | | `POST` | `/tui/open-themes` | Åpne temavelgeren | `boolean` | | `POST` | `/tui/open-models` | Åpne modellvelgeren | `boolean` | | `POST` | `/tui/submit-prompt` | Send inn gjeldende prompt | `boolean` | | `POST` | `/tui/clear-prompt` | Tøm prompten | `boolean` | | `POST` | `/tui/execute-command` | Utfør en kommando (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Vis toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Vent på neste kontrollforespørsel | Kontrollforespørselsobjekt | | `POST` | `/tui/control/response` | Svar på en kontrollforespørsel (`{ body }`) | `boolean` | * * * ### [Auth](https://opencode.ai/docs/nb/server#auth) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Angi autentiseringsinformasjon. Body må samsvare med leverandørskjema | `boolean` | * * * ### [Hendelser](https://opencode.ai/docs/nb/server#hendelser) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/event` | Strøm av server-sendte hendelser. Første hendelse er `server.connected`, deretter busshendelser | Strøm av server-sendte hendelser | * * * ### [Dokumentasjon](https://opencode.ai/docs/nb/server#dokumentasjon) | Metode | Sti | Beskrivelse | Svar | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1-spesifikasjon | HTML side med OpenAPI-spesifikasjon | --- # Formatere | OpenCode [Gå til indhold](https://opencode.ai/docs/da/formatters#_top) Formatere ========= OpenCode bruger sprogspecifikke formatere. OpenCode formaterer automatisk filer, efter de er skrevet eller redigeret ved hjælp af sprogspecifikke formatere. Dette sikrer, at den kode, der genereres, følger kodestilene for dit projekt. * * * [Indbyggede](https://opencode.ai/docs/da/formatters#indbyggede) ---------------------------------------------------------------- OpenCode leveres med flere indbyggede formatere til populære sprog og rammer. Nedenfor er en liste over de formatere, understøttede filtypenavne og kommandoer eller konfigurationsmuligheder, der har brug for. | Formater | Udvidelser | Krav | | --- | --- | --- | | gofmt | .go | `gofmt` kommando tilgængelig | | blande | .ex,.exs,.eex,.heex,.leex,.neex,.sface | `mix` kommando tilgængelig | | smukkere | .js,.jsx,.ts,.tsx,.html,.css,.md,.json,.yaml og [more](https://prettier.io/docs/en/index.html) | `prettier` afhængighed i `package.json` | | biome | .js,.jsx,.ts,.tsx,.html,.css,.md,.json,.yaml og [more](https://biomejs.dev/) | `biome.json(c)` konfigurationsfil | | zig | .zig,.zon | `zig` kommando tilgængelig | | klang-format | .c,.cpp,.h,.hpp,.ino og [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` konfigurationsfil | | ktlint | .kt,.kts | `ktlint` kommando tilgængelig | | ruff | .py,.pyi | `ruff` kommando tilgængelig med konfiguration | | rustfmt | .rs | `rustfmt` kommando tilgængelig | | cargofmt | .rs | `cargo fmt` kommando tilgængelig | | uv | .py,.pyi | `uv` kommando tilgængelig | | rubocop | .rb,.rake,.gemspec,.ru | `rubocop` kommando tilgængelig | | standardrb | .rb,.rake,.gemspec,.ru | `standardrb` kommando tilgængelig | | htmlbeautifier | .erb,.html.erb | `htmlbeautifier` kommando tilgængelig | | luft | .R | `air` kommando tilgængelig | | dart | .dart | `dart` kommando tilgængelig | | dfmt | .d | `dfmt` kommando tilgængelig | | ocamlformat | .ml,.mli | `ocamlformat` kommando tilgængelig og `.ocamlformat` config fil | | terraform | .tf,.tfvars | `terraform` kommando tilgængelig | | glimt | .glimt | `gleam` kommando tilgængelig | | nixfmt | .nix | `nixfmt` kommando tilgængelig | | shfmt | .sh,.bash | `shfmt` kommando tilgængelig | | pint | .php | `laravel/pint` afhængighed i `composer.json` | | oxfmt (Eksperimentel) | .js,.jsx,.ts,.tsx | `oxfmt` afhængighed i `package.json` og en [experimental env variable flag](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | `ormolu` kommando tilgængelig | Så hvis dit projekt har `prettier` i din `package.json`, vil OpenCode automatisk bruge det. * * * [Sådan fungerer det](https://opencode.ai/docs/da/formatters#s%C3%A5dan-fungerer-det) ------------------------------------------------------------------------------------- Når OpenCode skriver eller redigerer en fil, vil det: 1. Kontrollerer filtypenavnet mod alle aktiverede formatere. 2. Kører den relevante formateringskommando på filen. 3. Anvender formateringsændringerne automatisk. Denne proces sker i baggrunden, hvilket sikrer, at dine kodestile vedligeholdes uden nogen manuelle trin. * * * [Konfiguration](https://opencode.ai/docs/da/formatters#konfiguration) ---------------------------------------------------------------------- Du kan tilpasse formatere gennem afsnittet `formatter` i din OpenCode-konfiguration. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Hver formateringskonfiguration understøtter følgende: | Ejendom | Skriv | Beskrivelse | | --- | --- | --- | | `disabled` | boolean | Indstil dette til `true` for at deaktivere formateringsværktøjet | | `command` | string\[\] | Kommandoen til at køre for formatering | | `environment` | object | Miljøvariabler, der skal indstilles, når formateringsværktøjet køres | | `extensions` | string\[\] | Filtypenavne, som denne formaterer skal håndtere | Lad os se på nogle eksempler. * * * ### [Deaktivering af formatere](https://opencode.ai/docs/da/formatters#deaktivering-af-formatere) For at deaktivere **alle** formatere globalt, skal du indstille `formatter` til `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} For at deaktivere en **specifik** formatter, skal du indstille `disabled` til `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Brugerdefinerede formatere](https://opencode.ai/docs/da/formatters#brugerdefinerede-formatere) Du kan tilsidesætte de indbyggede formattere eller tilføje nye ved at angive kommandoen, miljøvariabler og filtypenavne: { "$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"] } }} **`$FILE` pladsholderen** i kommandoen vil blive erstattet med stien til filen, der formateres. --- # Formattatori | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/formatters#_top) Formattatori ============ OpenCode usa formattatori specifici per linguaggio. OpenCode formatta automaticamente i file dopo che vengono scritti o modificati usando formattatori specifici per linguaggio. Questo assicura che il codice generato segua lo stile del tuo progetto. * * * [Integrati](https://opencode.ai/docs/it/formatters#integrati) -------------------------------------------------------------- OpenCode include diversi formattatori integrati per linguaggi e framework popolari. Qui sotto trovi la lista dei formattatori, delle estensioni supportate e dei comandi o opzioni di config richiesti. | Formattatore | Estensioni | Requisiti | | --- | --- | --- | | air | .R | comando `air` disponibile | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://biomejs.dev/) | file di configurazione `biome.json(c)` | | cargofmt | .rs | comando `cargo fmt` disponibile | | clang-format | .c, .cpp, .h, .hpp, .ino, and [more](https://clang.llvm.org/docs/ClangFormat.html) | file di configurazione `.clang-format` | | cljfmt | .clj, .cljs, .cljc, .edn | comando `cljfmt` disponibile | | dart | .dart | comando `dart` disponibile | | dfmt | .d | comando `dfmt` disponibile | | gleam | .gleam | comando `gleam` disponibile | | gofmt | .go | comando `gofmt` disponibile | | htmlbeautifier | .erb, .html.erb | comando `htmlbeautifier` disponibile | | ktlint | .kt, .kts | comando `ktlint` disponibile | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | comando `mix` disponibile | | nixfmt | .nix | comando `nixfmt` disponibile | | ocamlformat | .ml, .mli | comando `ocamlformat` disponibile e file di configurazione `.ocamlformat` | | ormolu | .hs | comando `ormolu` disponibile | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | dipendenza `oxfmt` in `package.json` e una [flag variabile d’ambiente sperimentale](https://opencode.ai/docs/cli/#experimental) | | pint | .php | dipendenza `laravel/pint` in `composer.json` | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://prettier.io/docs/en/index.html) | dipendenza `prettier` in `package.json` | | rubocop | .rb, .rake, .gemspec, .ru | comando `rubocop` disponibile | | ruff | .py, .pyi | comando `ruff` disponibile con config | | rustfmt | .rs | comando `rustfmt` disponibile | | shfmt | .sh, .bash | comando `shfmt` disponibile | | standardrb | .rb, .rake, .gemspec, .ru | comando `standardrb` disponibile | | terraform | .tf, .tfvars | comando `terraform` disponibile | | uv | .py, .pyi | comando `uv` disponibile | | zig | .zig, .zon | comando `zig` disponibile | Quindi, se il progetto ha `prettier` in `package.json`, OpenCode lo usera automaticamente. * * * [Come funziona](https://opencode.ai/docs/it/formatters#come-funziona) ---------------------------------------------------------------------- Quando OpenCode scrive o modifica un file: 1. Controlla l’estensione del file rispetto a tutti i formattatori abilitati. 2. Esegue il comando del formattatore appropriato sul file. 3. Applica automaticamente le modifiche di formattazione. Questo processo avviene in background, mantenendo lo stile del codice senza passaggi manuali. * * * [Configurazione](https://opencode.ai/docs/it/formatters#configurazione) ------------------------------------------------------------------------ Puoi personalizzare i formattatori nella sezione `formatter` della config di OpenCode. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Ogni configurazione di formattatore supporta: | Proprieta | Tipo | Descrizione | | --- | --- | --- | | `disabled` | boolean | Impostalo a `true` per disabilitare il formattatore | | `command` | string\[\] | Il comando da eseguire per la formattazione | | `environment` | object | Variabili d’ambiente da impostare quando si esegue | | `extensions` | string\[\] | Estensioni file gestite da questo formattatore | Vediamo alcuni esempi. * * * ### [Disabilitare i formattatori](https://opencode.ai/docs/it/formatters#disabilitare-i-formattatori) Per disabilitare **tutti** i formattatori globalmente, imposta `formatter` a `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} Per disabilitare un formattatore **specifico**, imposta `disabled` a `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Formattatori personalizzati](https://opencode.ai/docs/it/formatters#formattatori-personalizzati) Puoi sovrascrivere i formattatori integrati o aggiungerne di nuovi specificando comando, variabili d’ambiente ed estensioni file: { "$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"] } }} Il **placeholder `$FILE`** nel comando viene sostituito con il percorso del file in fase di formattazione. --- # Форматтеры | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/formatters#_top) Форматтеры ========== opencode использует средства форматирования, специфичные для языка. opencode автоматически форматирует файлы после их записи или редактирования с использованием средств форматирования для конкретного языка. Это гарантирует, что создаваемый код будет соответствовать стилям кода вашего проекта. * * * [Встроенные](https://opencode.ai/docs/ru/formatters#%D0%B2%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5) ------------------------------------------------------------------------------------------------------------------ opencode поставляется с несколькими встроенными форматировщиками для популярных языков и платформ. Ниже приведен список форматтеров, поддерживаемых расширений файлов, а также необходимых команд или параметров конфигурации. | Formatter | Расширения | Требования | | --- | --- | --- | | gofmt | .go | Доступна команда `gofmt` | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Доступна команда `mix` | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml и [подробнее](https://prettier.io/docs/en/index.html) | Зависимость `prettier` в `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml и [подробнее](https://biomejs.dev/) | Конфигурационный файл `biome.json(c)` | | zig | .zig, .zon | Доступна команда `zig` | | clang-format | .c, .cpp, .h, .hpp, .ino и [подробнее](https://clang.llvm.org/docs/ClangFormat.html) | Конфигурационный файл `.clang-format` | | ktlint | .kt, .kts | Доступна команда `ktlint` | | ruff | .py, .pyi | Команда `ruff` доступна в конфигурации | | rustfmt | .rs | Доступна команда `rustfmt` | | cargofmt | .rs | Доступна команда `cargo fmt` | | uv | .py, .pyi | Доступна команда `uv` | | rubocop | .rb, .rake, .gemspec, .ru | Доступна команда `rubocop` | | standardrb | .rb, .rake, .gemspec, .ru | Доступна команда `standardrb` | | htmlbeautifier | .erb, .html.erb | Доступна команда `htmlbeautifier` | | air | .R | Доступна команда `air` | | dart | .dart | Доступна команда `dart` | | dfmt | .d | Доступна команда `dfmt` | | ocamlformat | .ml, .mli | Доступна команда `ocamlformat` и файл конфигурации `.ocamlformat`. | | terraform | .tf, .tfvars | Доступна команда `terraform` | | gleam | .gleam | Доступна команда `gleam` | | nixfmt | .nix | Доступна команда `nixfmt` | | shfmt | .sh, .bash | Доступна команда `shfmt` | | pint | .php | Зависимость `laravel/pint` в `composer.json` | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | Зависимость `oxfmt` в `package.json` и [экспериментальный флаг переменной окружения](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | Доступна команда `ormolu` | Поэтому, если ваш проект имеет `prettier` в вашем `package.json`, opencode автоматически будет использовать его. * * * [Настройка](https://opencode.ai/docs/ru/formatters#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0) ----------------------------------------------------------------------------------------------------------- Вы можете настроить форматтеры через раздел `formatter` в конфигурации opencode. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Каждая конфигурация форматтера поддерживает следующее: | Свойство | Тип | Описание | | --- | --- | --- | | `disabled` | boolean | Установите для этого параметра значение `true`, чтобы отключить форматтер. | | `command` | string\[\] | Команда для форматирования | | `environment` | объект | Переменные среды, которые необходимо установить при запуске средства форматирования | | `extensions` | string\[\] | Расширения файлов, которые должен обрабатывать этот форматтер | Давайте посмотрим на несколько примеров. * * * ### [Отключение форматтеров](https://opencode.ai/docs/ru/formatters#%D0%BE%D1%82%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D1%82%D0%B5%D1%80%D0%BE%D0%B2) Чтобы глобально отключить **все** средства форматирования, установите для `formatter` значение `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} Чтобы отключить **конкретный** форматтер, установите для `disabled` значение `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Пользовательские форматтеры](https://opencode.ai/docs/ru/formatters#%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B5-%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D1%82%D0%B5%D1%80%D1%8B) Вы можете переопределить встроенные средства форматирования или добавить новые, указав команду, переменные среды и расширения файлов: { "$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"] } }} Заполнитель **`$FILE`** в команде будет заменен путем к форматируемому файлу. --- # Konfigurasjon | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/config#_top) Konfigurasjon ============= Ved å bruke opencode JSON-konfigurasjonen. Du kan konfigurere OpenCode ved å bruke en JSON konfigurasjonsfil. * * * [Format](https://opencode.ai/docs/nb/config#format) ---------------------------------------------------- OpenCode støtter både **JSON** og **JSONC** (JSON med kommentarer) formater. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [Plasseringer](https://opencode.ai/docs/nb/config#plasseringer) ---------------------------------------------------------------- Du kan plassere konfigurasjonen på et par forskjellige steder, og de har en annen rekkefølge. Konfigurasjonsfiler slås sammen, ikke erstattes. Innstillinger fra følgende konfigurasjonsplasseringer kombineres. Senere konfigurasjoner overstyrer tidligere kun for motstridende nøkler. Ikke-motstridende innstillinger fra alle konfigurasjoner er bevart. For eksempel, hvis din globale konfigurasjon setter `theme: "opencode"` og `autoupdate: true`, og prosjektkonfigurasjonen setter `model: "anthropic/claude-sonnet-4-5"`, vil den endelige konfigurasjonen inkludere alle tre innstillingene. * * * ### [Prioritetsrekkefølge](https://opencode.ai/docs/nb/config#prioritetsrekkef%C3%B8lge) Konfigurasjonskilder lastes inn i denne rekkefølgen (senere kilder overstyrer tidligere): 1. **Ekstern konfigurasjon** (fra `.well-known/opencode`) - organisasjonsstandarder 2. **Global konfigurasjon** (`~/.config/opencode/opencode.json`) - brukerinnstillinger 3. **Egendefinert konfigurasjon** (`OPENCODE_CONFIG` env var) - egendefinerte overstyringer 4. **Prosjektkonfigurasjon** (`opencode.json` i prosjekt) - prosjektspesifikke innstillinger 5. **`.opencode` kataloger** - agenter, kommandoer, plugins 6. **Inline config** (`OPENCODE_CONFIG_CONTENT` env var) - kjøretidsoverstyringer Dette betyr at prosjektkonfigurasjoner kan overstyre globale standardinnstillinger, og globale konfigurasjoner kan overstyre eksterne organisasjonsstandarder. * * * ### [Ekstern konfigurasjon](https://opencode.ai/docs/nb/config#ekstern-konfigurasjon) Organisasjoner kan tilby standardkonfigurasjon via `.well-known/opencode`\-endepunktet. Dette hentes automatisk når du autentiserer med en leverandør som støtter det. Ekstern konfigurasjon lastes først, og fungerer som grunnlaget. Alle andre konfigurasjonskilder (global, prosjekt) kan overstyre disse standardinnstillingene. For eksempel, hvis organisasjonen din tilbyr MCP servere som er deaktivert som standard: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Du kan aktivere spesifikke servere i din lokale konfigurasjon: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global konfigurasjon](https://opencode.ai/docs/nb/config#global-konfigurasjon) Plasser din globale OpenCode-konfigurasjon i `~/.config/opencode/opencode.json`. Bruk global konfigurasjon for brukerspesifikke preferanser som temaer, leverandører eller nøkkelbindinger. Global konfigurasjon overstyrer eksterne organisasjonsstandarder. * * * ### [Per prosjekt](https://opencode.ai/docs/nb/config#per-prosjekt) Legg til `opencode.json` i prosjektroten din. Prosjektkonfigurasjon har den høyeste prioritet blant standard config-filer - den overstyrer både globale og eksterne konfigurasjoner. Når OpenCode starter opp, ser den etter en konfigurasjonsfil i gjeldende katalog eller går opp til nærmeste Git-katalog. Det er også trygt å sjekke inn dette i Git og bruker samme skjema som det globale. * * * ### [Egendefinert bane](https://opencode.ai/docs/nb/config#egendefinert-bane) Spesifiser en tilpasset konfigurasjonsfilbane ved å bruke miljøvariabelen `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Egendefinert konfigurasjon lastes inn mellom globale og prosjektkonfigurasjoner i prioritetsrekkefølge. * * * ### [Egendefinert katalog](https://opencode.ai/docs/nb/config#egendefinert-katalog) Spesifiser en tilpasset konfigurasjonskatalog ved å bruke `OPENCODE_CONFIG_DIR` miljøvariabel. Denne katalogen vil bli søkt etter agenter, kommandoer, moduser og plugins akkurat som standard `.opencode` katalog, og bør følge samme struktur. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" Den egendefinerte katalogen lastes inn etter den globale konfigurasjonen og `.opencode`\-katalogene, slik at den **kan overstyre** innstillingene deres. * * * [Skjema](https://opencode.ai/docs/nb/config#skjema) ---------------------------------------------------- Konfigurasjonsfilen har et skjema som er definert i [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . Redaktøren din skal kunne validere og autofullføre basert på skjemaet. * * * ### [TUI](https://opencode.ai/docs/nb/config#tui) Du kan konfigurere TUI-spesifikke innstillinger gjennom alternativet `tui`. { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} Tilgjengelige alternativer: * `scroll_acceleration.enabled` - Aktiver rulleakselerasjon i macOS-stil. **Tar forrang over `scroll_speed`.** * `scroll_speed` - Egendefinert rullehastighetsmultiplikator (standard: `3`, minimum: `1`). Ignorert hvis `scroll_acceleration.enabled` er `true`. * `diff_style` - Kontroller diff-gjengivelse. `"auto"` tilpasser seg terminalbredden, `"stacked"` viser alltid en kolonne. [Les mer om bruk av TUI her](https://opencode.ai/docs/tui) . * * * ### [Tjener](https://opencode.ai/docs/nb/config#tjener) Du kan konfigurere serverinnstillinger for kommandoene `opencode serve` og `opencode web` gjennom alternativet `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Tilgjengelige alternativer: * `port` - Port å lytte på. * `hostname` - Vertsnavn å lytte på. Når `mdns` er aktivert og ingen vertsnavn er angitt, er standard `0.0.0.0`. * `mdns` - Aktiver mDNS-tjenesteoppdagelse. Dette lar andre enheter på nettverket oppdage OpenCode-serveren din. * `mdnsDomain` - Egendefinert domenenavn for mDNS-tjeneste. Standard er `opencode.local`. Nyttig for å kjøre flere forekomster på samme nettverk. * `cors` - Ytterligere opprinnelser for å tillate CORS når du bruker HTTP-serveren fra en nettleserbasert klient. Verdiene må være fullstendige opprinnelser (skjema + vert + valgfri port), f.eks. `https://app.example.com`. [Les mer om serveren her](https://opencode.ai/docs/server) . * * * ### [Verktøy](https://opencode.ai/docs/nb/config#verkt%C3%B8y) Du kan administrere verktøyene en LLM kan bruke gjennom alternativet `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Les mer om verktøy her](https://opencode.ai/docs/tools) . * * * ### [Modeller](https://opencode.ai/docs/nb/config#modeller) Du kan konfigurere leverandørene og modellene du vil bruke i OpenCode-konfigurasjonen gjennom alternativene `provider`, `model` og `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} Alternativet `small_model` konfigurerer en egen modell for lette oppgaver som tittelgenerering. Som standard prøver OpenCode å bruke en rimeligere modell hvis en er tilgjengelig fra leverandøren din, ellers faller den tilbake til hovedmodellen din. Leverandøralternativer kan inkludere `timeout` og `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Tidsavbrudd for forespørsler i millisekunder (standard: 300 000). Sett til `false` for å deaktivere. * `setCacheKey` - Sørg for at en hurtigbuffernøkkel alltid settes for valgt leverandør. Du kan også konfigurere [lokale modeller](https://opencode.ai/docs/models#local) . [Finn ut mer](https://opencode.ai/docs/models) . * * * #### [Leverandørspesifikke alternativer](https://opencode.ai/docs/nb/config#leverand%C3%B8rspesifikke-alternativer) Noen leverandører støtter flere konfigurasjonsalternativer utover de generiske innstillingene `timeout` og `apiKey`. ##### [Amazon Bedrock](https://opencode.ai/docs/nb/config#amazon-bedrock) Amazon Bedrock støtter AWS-spesifikk konfigurasjon: { "$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 (standard er `AWS_REGION` env var eller `us-east-1`) * `profile` - AWS navngitt profil fra `~/.aws/credentials` (standard til `AWS_PROFILE` env var) * `endpoint` - Egendefinert endepunkt URL for VPC endepunkter. Dette er et alias for det generiske `baseURL`\-alternativet som bruker AWS-spesifikk terminologi. Hvis begge er spesifisert, har `endpoint` forrang. [Les mer om konfigurasjon av Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Temaer](https://opencode.ai/docs/nb/config#temaer) Angi UI-temaet ditt i `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [Les mer her](https://opencode.ai/docs/themes) . * * * ### [Agenter](https://opencode.ai/docs/nb/config#agenter) Du kan konfigurere spesialiserte agenter for spesifikke oppgaver gjennom alternativet `agent`. { "$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, }, }, },} Du kan også definere agenter ved å bruke markdown-filer i `~/.config/opencode/agents/` eller `.opencode/agents/`. [Les mer her](https://opencode.ai/docs/agents) . * * * ### [Standardagent](https://opencode.ai/docs/nb/config#standardagent) Du kan angi standard agent ved å bruke alternativet `default_agent`. Dette bestemmer hvilken agent som brukes når ingen er eksplisitt spesifisert. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} Standardagenten må være en primæragent (ikke en underagent). Dette kan være en innebygd agent som `"build"` eller `"plan"`, eller en [egendefinert agent](https://opencode.ai/docs/agents) du har definert. Hvis den angitte agenten ikke eksisterer eller er en subagent, vil OpenCode falle tilbake til `"build"` med en advarsel. Denne innstillingen gjelder for alle grensesnitt: TUI, CLI (`opencode run`), skrivebordsapp og GitHub Action. * * * ### [Deling](https://opencode.ai/docs/nb/config#deling) Du kan konfigurere [share](https://opencode.ai/docs/share) \-funksjonen gjennom alternativet `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Dette krever: * `"manual"` - Tillat manuell deling via kommandoer (standard) * `"auto"` - Del nye samtaler automatisk * `"disabled"` - Deaktiver deling helt Som standard er deling satt til manuell modus der du eksplisitt må dele samtaler ved å bruke kommandoen `/share`. * * * ### [Kommandoer](https://opencode.ai/docs/nb/config#kommandoer) Du kan konfigurere egendefinerte kommandoer for repeterende oppgaver gjennom alternativet `command`. { "$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", }, },} Du kan også definere kommandoer ved å bruke markdown-filer i `~/.config/opencode/commands/` eller `.opencode/commands/`. [Les mer her](https://opencode.ai/docs/commands) . * * * ### [Tastebindinger](https://opencode.ai/docs/nb/config#tastebindinger) Tilpass tastebindinger i `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [Les mer her](https://opencode.ai/docs/keybinds) . * * * ### [Autooppdatering](https://opencode.ai/docs/nb/config#autooppdatering) OpenCode vil automatisk laste ned eventuelle nye oppdateringer når den starter opp. Du kan deaktivere dette med alternativet `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Hvis du ikke vil ha oppdateringer, men ønsker å bli varslet når en ny versjon er tilgjengelig, sett `autoupdate` til `"notify"`. Legg merke til at dette bare fungerer hvis det ikke ble installert med en pakkebehandling som Homebrew. * * * ### [Formatere](https://opencode.ai/docs/nb/config#formatere) Du kan konfigurere kodeformatere gjennom alternativet `formatter`. { "$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"] } }} [Les mer om formattere her](https://opencode.ai/docs/formatters) . * * * ### [Tillatelser](https://opencode.ai/docs/nb/config#tillatelser) Som standard **tillater OpenCode alle operasjoner** uten å kreve eksplisitt godkjenning. Du kan endre dette ved å bruke alternativet `permission`. Slik sikrer du at verktøyene `edit` og `bash` krever brukergodkjenning: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Les mer om tillatelser her](https://opencode.ai/docs/permissions) . * * * ### [Komprimering](https://opencode.ai/docs/nb/config#komprimering) Du kan styre kontekstkomprimering gjennom alternativet `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - Komprimer økten automatisk når konteksten er full (standard: `true`). * `prune` - Fjern gamle verktøyutdata for å spare tokens (standard: `true`). * `reserved` - Token-buffer for komprimering. Etterlater nok vindu til å unngå overflyt under komprimering * * * ### [Filovervåker](https://opencode.ai/docs/nb/config#filoverv%C3%A5ker) Du kan konfigurere ignoreringsmønstre for filovervåking gjennom alternativet `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Mønstre følger glob-syntaks. Bruk dette for å ekskludere støyende kataloger fra filovervåking. * * * ### [MCP servere](https://opencode.ai/docs/nb/config#mcp-servere) Du kan konfigurere MCP-servere du vil bruke gjennom alternativet `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Les mer her](https://opencode.ai/docs/mcp-servers) . * * * ### [Utvidelser](https://opencode.ai/docs/nb/config#utvidelser) [Plugins](https://opencode.ai/docs/plugins) utvider OpenCode med tilpassede verktøy, kroker og integrasjoner. Plasser plugin-filer i `.opencode/plugins/` eller `~/.config/opencode/plugins/`. Du kan også laste inn plugins fra npm gjennom alternativet `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Les mer her](https://opencode.ai/docs/plugins) . * * * ### [Instruksjoner](https://opencode.ai/docs/nb/config#instruksjoner) Du kan konfigurere instruksjoner for modellen du bruker gjennom alternativet `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Dette krever en liste med baner og globmønstre til instruksjonsfiler. [Les mer om regler her](https://opencode.ai/docs/rules) . * * * ### [Deaktiverte leverandører](https://opencode.ai/docs/nb/config#deaktiverte-leverand%C3%B8rer) Du kan deaktivere leverandører som lastes automatisk gjennom alternativet `disabled_providers`. Dette er nyttig når du vil forhindre at enkelte leverandører lastes inn selv om deres legitimasjon er tilgjengelig. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} Alternativet `disabled_providers` godtar en rekke leverandør-ID-er. Når en leverandør er deaktivert: * Den blir ikke lastet selv om miljøvariabler er angitt. * Den vil ikke bli lastet inn selv om API-nøkler er konfigurert gjennom `/connect`\-kommandoen. * Leverandørens modeller vises ikke i modellvalglisten. * * * ### [Aktiverte leverandører](https://opencode.ai/docs/nb/config#aktiverte-leverand%C3%B8rer) Du kan spesifisere en godkjenningsliste over leverandører gjennom alternativet `enabled_providers`. Når angitt, vil bare de angitte leverandørene være aktivert og alle andre vil bli ignorert. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Dette er nyttig når du vil begrense OpenCode til kun å bruke spesifikke leverandører i stedet for å deaktivere dem én etter én. Hvis en leverandør vises i både `enabled_providers` og `disabled_providers`, har `disabled_providers` prioritet for bakoverkompatibilitet. * * * ### [Eksperimentelt](https://opencode.ai/docs/nb/config#eksperimentelt) `experimental`\-nøkkelen inneholder alternativer som er under aktiv utvikling. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variabler](https://opencode.ai/docs/nb/config#variabler) ---------------------------------------------------------- Du kan bruke variabelerstatning i konfigurasjonsfilene dine for å referere til miljøvariabler og filinnhold. * * * ### [Miljøvariabler](https://opencode.ai/docs/nb/config#milj%C3%B8variabler) Bruk `{env:VARIABLE_NAME}` for å erstatte miljøvariabler: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Hvis miljøvariabelen ikke er angitt, vil den bli erstattet med en tom streng. * * * ### [Filer](https://opencode.ai/docs/nb/config#filer) Bruk `{file:path/to/file}` for å erstatte innholdet i en fil: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Filbaner kan være: * I forhold til konfigurasjonsfilkatalogen * Eller absolutte baner som begynner med `/` eller `~` Disse er nyttige for: * Oppbevaring av sensitive data som API-nøkler i separate filer. * Inkludert store instruksjonsfiler uten å rote konfigurasjonen din. * Deling av vanlige konfigurasjonsbiter på tvers av flere konfigurasjonsfiler. --- # Сервер | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/server#_top) Сервер ====== Взаимодействуйте с сервером opencode через HTTP. Команда `opencode serve` запускает автономный HTTP-сервер, который предоставляет конечную точку OpenAPI, которую может использовать клиент с открытым кодом. * * * ### [Использование](https://opencode.ai/docs/ru/server#%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) opencode serve [--port ] [--hostname ] [--cors ] #### [Параметры](https://opencode.ai/docs/ru/server#%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B) | Флаг | Описание | По умолчанию | | --- | --- | --- | | `--port` | Порт для прослушивания | `4096` | | `--hostname` | Имя хоста для прослушивания | `127.0.0.1` | | `--mdns` | Включить обнаружение mDNS | `false` | | `--mdns-domain` | Пользовательское доменное имя для mDNS | `opencode.local` | | `--cors` | Разрешенные дополнительные источники (CORS) | `[]` | `--cors` можно передать несколько раз: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Аутентификация](https://opencode.ai/docs/ru/server#%D0%B0%D1%83%D1%82%D0%B5%D0%BD%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F) Установите `OPENCODE_SERVER_PASSWORD`, чтобы защитить сервер с помощью базовой аутентификации HTTP. Имя пользователя по умолчанию — `opencode` или установите `OPENCODE_SERVER_USERNAME`, чтобы переопределить его. Это относится как к `opencode serve`, так и к `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Как это работает](https://opencode.ai/docs/ru/server#%D0%BA%D0%B0%D0%BA-%D1%8D%D1%82%D0%BE-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82) Когда вы запускаете `opencode`, он запускает TUI и сервер. Где находится TUI клиент, который общается с сервером. Сервер предоставляет спецификацию OpenAPI 3.1. конечная точка. Эта конечная точка также используется для создания файла [SDK](https://opencode.ai/docs/sdk) . Эта архитектура позволяет открытому коду поддерживать несколько клиентов и позволяет программно взаимодействовать с открытым кодом. Вы можете запустить `opencode serve`, чтобы запустить автономный сервер. Если у вас есть TUI с открытым кодом запущен, `opencode serve` запустит новый сервер. * * * #### [Подключиться к существующему серверу](https://opencode.ai/docs/ru/server#%D0%BF%D0%BE%D0%B4%D0%BA%D0%BB%D1%8E%D1%87%D0%B8%D1%82%D1%8C%D1%81%D1%8F-%D0%BA-%D1%81%D1%83%D1%89%D0%B5%D1%81%D1%82%D0%B2%D1%83%D1%8E%D1%89%D0%B5%D0%BC%D1%83-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D1%83) Когда вы запускаете TUI, он случайным образом назначает порт и имя хоста. Вместо этого вы можете передать `--hostname` и `--port` [flags](https://opencode.ai/docs/cli) . Затем используйте это для подключения к его серверу. Конечную точку [`/tui`](https://opencode.ai/docs/ru/server#tui) можно использовать для управления TUI через сервер. Например, вы можете предварительно заполнить или запустить подсказку. Эта настройка используется плагинами opencode [IDE](https://opencode.ai/docs/ide) . * * * [Спецификация](https://opencode.ai/docs/ru/server#%D1%81%D0%BF%D0%B5%D1%86%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F) ---------------------------------------------------------------------------------------------------------------------------- Сервер публикует спецификацию OpenAPI 3.1, которую можно просмотреть по адресу: http://:/doc For example, `http://localhost:4096/doc`. Use the spec to generate clients or inspect request and response types. Or view it in a Swagger explorer. * * * [API](https://opencode.ai/docs/ru/server#api) ---------------------------------------------- Сервер opencode предоставляет следующие API. * * * ### [Глобальный](https://opencode.ai/docs/ru/server#%D0%B3%D0%BB%D0%BE%D0%B1%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/global/health` | Получить состояние и версию сервера | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Получить глобальные события (поток SSE) | Поток событий | * * * ### [Проект](https://opencode.ai/docs/ru/server#%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/project` | Список всех проектов | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Получить текущий проект | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Путь и система контроля версий](https://opencode.ai/docs/ru/server#%D0%BF%D1%83%D1%82%D1%8C-%D0%B8-%D1%81%D0%B8%D1%81%D1%82%D0%B5%D0%BC%D0%B0-%D0%BA%D0%BE%D0%BD%D1%82%D1%80%D0%BE%D0%BB%D1%8F-%D0%B2%D0%B5%D1%80%D1%81%D0%B8%D0%B9) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/path` | Получить текущий путь | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Получить информацию о VCS для текущего проекта | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Экземпляр](https://opencode.ai/docs/ru/server#%D1%8D%D0%BA%D0%B7%D0%B5%D0%BC%D0%BF%D0%BB%D1%8F%D1%80) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Удалить текущий экземпляр | `boolean` | * * * ### [Конфигурация](https://opencode.ai/docs/ru/server#%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B3%D1%83%D1%80%D0%B0%D1%86%D0%B8%D1%8F) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/config` | Получить информацию о конфигурации | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Обновить конфигурацию | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Список провайдеров и моделей по умолчанию | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Поставщик](https://opencode.ai/docs/ru/server#%D0%BF%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D1%89%D0%B8%D0%BA) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/provider` | Список всех провайдеров | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Получить методы аутентификации провайдера | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Авторизация провайдера через OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Обработка callback OAuth для провайдера | `boolean` | * * * ### [Сессии](https://opencode.ai/docs/ru/server#%D1%81%D0%B5%D1%81%D1%81%D0%B8%D0%B8) | Метод | Путь | Описание | Примечания | | --- | --- | --- | --- | | `GET` | `/session` | Список всех сессий | Возвращает [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Создать новую сессию | body: `{ parentID?, title? }`, возвращает [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Получить статус всех сессий | Возвращает `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Получить детали сессии | Возвращает [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Удалить сессию и все её данные | Возвращает `boolean` | | `PATCH` | `/session/:id` | Обновить свойства сессии | body: `{ title? }`, возвращает [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Получить дочерние сессии | Возвращает [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Получить список задач для сессии | Возвращает [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Анализ приложения и создание `AGENTS.md` | body: `{ messageID, providerID, modelID }`, возвращает `boolean` | | `POST` | `/session/:id/fork` | Ответвление сессии от сообщения | body: `{ messageID? }`, возвращает [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Прервать запущенную сессию | Возвращает `boolean` | | `POST` | `/session/:id/share` | Поделиться сессией | Возвращает [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Отменить общий доступ к сессии | Возвращает [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Получить diff для этой сессии | query: `messageID?`, возвращает [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Суммировать сессию | body: `{ providerID, modelID }`, возвращает `boolean` | | `POST` | `/session/:id/revert` | Отменить сообщение | body: `{ messageID, partID? }`, возвращает `boolean` | | `POST` | `/session/:id/unrevert` | Восстановить все отмененные сообщения | Возвращает `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Ответить на запрос разрешения | body: `{ response, remember? }`, возвращает `boolean` | * * * ### [Сообщения](https://opencode.ai/docs/ru/server#%D1%81%D0%BE%D0%BE%D0%B1%D1%89%D0%B5%D0%BD%D0%B8%D1%8F) | Метод | Путь | Описание | Примечания | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Список сообщений в сессии | query: `limit?`, возвращает `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Отправить сообщение и ждать ответа | body: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, возвращает `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Получить детали сообщения | Возвращает `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Отправить сообщение асинхронно (без ожидания) | body: как в `/session/:id/message`, возвращает `204 No Content` | | `POST` | `/session/:id/command` | Выполнить слэш-команду | body: `{ messageID?, agent?, model?, command, arguments }`, возвращает `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Запустить команду оболочки | body: `{ agent, model?, command }`, возвращает `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Команды](https://opencode.ai/docs/ru/server#%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D1%8B) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/command` | Список всех команд | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Файлы](https://opencode.ai/docs/ru/server#%D1%84%D0%B0%D0%B9%D0%BB%D1%8B) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Поиск текста в файлах | Массив объектов совпадения с `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Поиск файлов и директорий по имени | `string[]` (пути) | | `GET` | `/find/symbol?query=` | Поиск символов рабочего пространства | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Список файлов и директорий | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Прочитать файл | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Получить статус отслеживаемых файлов | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` параметры запроса](https://opencode.ai/docs/ru/server#findfile-%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B-%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%D0%B0) * `query` (обязательно) — строка поиска (нечеткое совпадение) * `type` (необязательно) — ограничить результаты `"file"` или `"directory"`. * `directory` (необязательно) — переопределить корень проекта для поиска. * `limit` (необязательно) — максимальное количество результатов (1–200) * `dirs` (необязательно) — устаревший флаг (`"false"` возвращает только файлы) * * * ### [Инструменты (Экспериментальные)](https://opencode.ai/docs/ru/server#%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%8D%D0%BA%D1%81%D0%BF%D0%B5%D1%80%D0%B8%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Список всех идентификаторов инструментов | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Список инструментов со схемами JSON для модели | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, форматтеры и MCP](https://opencode.ai/docs/ru/server#lsp-%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D1%82%D0%B5%D1%80%D1%8B-%D0%B8-mcp) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/lsp` | Получить статус сервера LSP | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Получить статус форматера | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Получить статус сервера MCP | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Добавить сервер MCP динамически | body: `{ name, config }`, возвращает статус объекта MCP | * * * ### [Агенты](https://opencode.ai/docs/ru/server#%D0%B0%D0%B3%D0%B5%D0%BD%D1%82%D1%8B) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/agent` | Список всех доступных агентов | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Ведение журнала](https://opencode.ai/docs/ru/server#%D0%B2%D0%B5%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B6%D1%83%D1%80%D0%BD%D0%B0%D0%BB%D0%B0) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `POST` | `/log` | Записать запись в журнал. Body: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/ru/server#tui) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Добавить текст в подсказку | `boolean` | | `POST` | `/tui/open-help` | Открыть диалог помощи | `boolean` | | `POST` | `/tui/open-sessions` | Открыть селектор сессий | `boolean` | | `POST` | `/tui/open-themes` | Открыть селектор тем | `boolean` | | `POST` | `/tui/open-models` | Открыть селектор моделей | `boolean` | | `POST` | `/tui/submit-prompt` | Отправить текущую подсказку | `boolean` | | `POST` | `/tui/clear-prompt` | Очистить подсказку | `boolean` | | `POST` | `/tui/execute-command` | Выполнить команду (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Показать уведомление (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Ожидание следующего запроса управления | Объект запроса управления | | `POST` | `/tui/control/response` | Ответить на запрос управления (`{ body }`) | `boolean` | * * * ### [Авторизация](https://opencode.ai/docs/ru/server#%D0%B0%D0%B2%D1%82%D0%BE%D1%80%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Установить учетные данные аутентификации. Body должен соответствовать схеме провайдера | `boolean` | * * * ### [События](https://opencode.ai/docs/ru/server#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/event` | Поток событий, отправляемых сервером. Первое событие — `server.connected`, затем события шины | Поток событий, отправляемых сервером | * * * ### [Документы](https://opencode.ai/docs/ru/server#%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B) | Метод | Путь | Описание | Ответ | | --- | --- | --- | --- | | `GET` | `/doc` | Спецификация OpenAPI 3.1 | HTML-страница со спецификацией OpenAPI | --- # Biçimlendiriciler | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/formatters#_top) Biçimlendiriciler ================= opencode dile özgü biçimlendiriciler kullanır. opencode, dosyaları dile özgü formatlayıcılar kullanılarak yazıldıktan veya düzenlendikten sonra otomatik olarak formatlar. Bu, oluşturulan kodun projenizin kod stillerine uymasını sağlar. * * * [Yerleşik](https://opencode.ai/docs/tr/formatters#yerle%C5%9Fik) ----------------------------------------------------------------- opencode, popüler diller ve çerçeveler için çeşitli yerleşik biçimlendiricilerle birlikte gelir. Aşağıda ihtiyaç duyduğu biçimlendiricilerin, desteklenen dosya uzantılarının ve komutların veya yapılandırma seçeneklerinin bir listesi bulunmaktadır. | Biçimlendirici | Uzantılar | Gereksinimler | | --- | --- | --- | | gofmt | .go | `gofmt` komutu mevcut | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` komutu mevcut | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml ve [daha fazla](https://prettier.io/docs/en/index.html) | `package.json` içinde `prettier` bağımlılığı | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml ve [daha fazla](https://biomejs.dev/) | `biome.json(c)` yapılandırma dosyası | | zig | .zig, .zon | `zig` komutu mevcut | | clang-format | .c, .cpp, .h, .hpp, .ino ve [daha fazla](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` yapılandırma dosyası | | ktlint | .kt, .kts | `ktlint` komutu mevcut | | ruff | .py, .pyi | `ruff` komutu yapılandırmayla kullanılabilir | | rustfmt | .rs | `rustfmt` komutu mevcut | | cargofmt | .rs | `cargo fmt` komutu mevcut | | uv | .py, .pyi | `uv` komutu mevcut | | rubocop | .rb, .rake, .gemspec, .ru | `rubocop` komutu mevcut | | standardrb | .rb, .rake, .gemspec, .ru | `standardrb` komutu mevcut | | htmlbeautifier | .erb, .html.erb | `htmlbeautifier` komutu mevcut | | air | .R | `air` komutu mevcut | | dart | .dart | `dart` komutu mevcut | | dfmt | .d | `dfmt` komutu mevcut | | ocamlformat | .ml, .mli | `ocamlformat` komutu mevcut ve `.ocamlformat` yapılandırma dosyası | | terraform | .tf, .tfvars | `terraform` komutu mevcut | | gleam | .gleam | `gleam` komutu mevcut | | nixfmt | .nix | `nixfmt` komutu mevcut | | shfmt | .sh, .bash | `shfmt` komutu mevcut | | pint | .php | `composer.json` içinde `laravel/pint` bağımlılığı | | oxfmt (Deneysel) | .js, .jsx, .ts, .tsx | `package.json` içinde `oxfmt` bağımlılığı ve [experimental env variable flag](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | `ormolu` komutu mevcut | Yani eğer projenizin `package.json` dosyasında `prettier` varsa, opencode bunu otomatik olarak kullanacaktır. * * * [Nasıl çalışır?](https://opencode.ai/docs/tr/formatters#nas%C4%B1l-%C3%A7al%C4%B1%C5%9F%C4%B1r) ------------------------------------------------------------------------------------------------ opencode bir dosyayı yazdığında veya düzenlediğinde: 1. Dosya uzantısını tüm etkin formatlayıcılara göre kontrol eder. 2. Dosyada uygun biçimlendirici komutunu çalıştırır. 3. Biçimlendirme değişikliklerini otomatik olarak uygular. Bu işlem arka planda gerçekleşir ve kod stillerinizin herhangi bir manuel adım olmadan korunmasını sağlar. * * * [Yapılandırma](https://opencode.ai/docs/tr/formatters#yap%C4%B1land%C4%B1rma) ------------------------------------------------------------------------------ Biçimlendiricileri opencode yapılandırmanızdaki `formatter` bölümü aracılığıyla özelleştirebilirsiniz. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Her formatlayıcı yapılandırması aşağıdakileri destekler: | Özellik | Tip | Açıklama | | --- | --- | --- | | `disabled` | boolean | Biçimlendiriciyi devre dışı bırakmak için bunu `true` olarak ayarlayın | | `command` | string\[\] | Biçimlendirme için çalıştırılacak komut | | `environment` | object | Biçimlendiriciyi çalıştırırken ayarlanacak ortam değişkenleri | | `extensions` | string\[\] | Bu formatlayıcının işlemesi gereken dosya uzantıları | Bazı örneklere bakalım. * * * ### [Biçimlendiricileri devre dışı bırakma](https://opencode.ai/docs/tr/formatters#bi%C3%A7imlendiricileri-devre-d%C4%B1%C5%9F%C4%B1-b%C4%B1rakma) **tüm** biçimlendiricileri genel olarak devre dışı bırakmak için `formatter` değerini `false` olarak ayarlayın: { "$schema": "https://opencode.ai/config.json", "formatter": false} **Belirli** bir biçimlendiriciyi devre dışı bırakmak için `disabled` değerini `true` olarak ayarlayın: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Özel biçimlendiriciler](https://opencode.ai/docs/tr/formatters#%C3%B6zel-bi%C3%A7imlendiriciler) Komutu, ortam değişkenlerini ve dosya uzantılarını belirterek yerleşik biçimlendiricileri geçersiz kılabilir veya yenilerini ekleyebilirsiniz: { "$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"] } }} Komuttaki **`$FILE` yer tutucusu**, biçimlendirilen dosyanın yolu ile değiştirilecektir. --- # Formattere | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/formatters#_top) Formattere ========== OpenCode bruker språkspesifikke formattere. OpenCode formaterer automatisk filer etter at de er skrevet eller redigert ved hjelp av språkspesifikke formattere. Dette sikrer at koden som genereres følger kodestilene til prosjektet ditt. * * * [Innebygde formattere](https://opencode.ai/docs/nb/formatters#innebygde-formattere) ------------------------------------------------------------------------------------ OpenCode kommer med flere innebygde formattere for populære språk og rammeverk. Nedenfor er en liste over formattere, støttede filendelser og kommandoer eller konfigurasjonsalternativer den krever. | Formatter | Filendelser | Krav | | --- | --- | --- | | gofmt | .go | `gofmt` kommando tilgjengelig | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` kommando tilgjengelig | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml og [flere](https://prettier.io/docs/en/index.html) | `prettier` avhengighet i `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml og [flere](https://biomejs.dev/) | `biome.json(c)` konfigurasjonsfil | | zig | .zig, .zon | `zig` kommando tilgjengelig | | clang-format | .c, .cpp, .h, .hpp, .ino og [flere](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` konfigurasjonsfil | | ktlint | .kt, .kts | `ktlint` kommando tilgjengelig | | ruff | .py, .pyi | `ruff` kommando tilgjengelig med config | | rustfmt | .rs | `rustfmt` kommando tilgjengelig | | cargofmt | .rs | `cargo fmt` kommando tilgjengelig | | uv | .py, .pyi | `uv` kommando tilgjengelig | | rubocop | .rb, .rake, .gemspec, .ru | `rubocop` kommando tilgjengelig | | standardrb | .rb, .rake, .gemspec, .ru | `standardrb` kommando tilgjengelig | | htmlbeautifier | .erb, .html.erb | `htmlbeautifier` kommando tilgjengelig | | air | .R | `air` kommando tilgjengelig | | dart | .dart | `dart` kommando tilgjengelig | | dfmt | .d | `dfmt` kommando tilgjengelig | | ocamlformat | .ml, .mli | `ocamlformat` kommando tilgjengelig og `.ocamlformat` konfigurasjonsfil | | terraform | .tf, .tfvars | `terraform` kommando tilgjengelig | | gleam | .gleam | `gleam` kommando tilgjengelig | | nixfmt | .nix | `nixfmt` kommando tilgjengelig | | shfmt | .sh, .bash | `shfmt` kommando tilgjengelig | | pint | .php | `laravel/pint` avhengighet i `composer.json` | | oxfmt (Eksperimentell) | .js, .jsx, .ts, .tsx | `oxfmt` avhengighet i `package.json` og et [eksperimentelt env variabel flagg](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | `ormolu` kommando tilgjengelig | Så hvis prosjektet ditt har `prettier` i `package.json`, vil OpenCode automatisk bruke det. * * * [Slik fungerer det](https://opencode.ai/docs/nb/formatters#slik-fungerer-det) ------------------------------------------------------------------------------ Når OpenCode skriver eller redigerer en fil, gjør den: 1. Kontrollerer filtypen mot alle aktiverte formattere. 2. Kjører riktig formateringskommando på filen. 3. Bruker formateringsendringene automatisk. Denne prosessen skjer i bakgrunnen, og sikrer at kodestilene dine opprettholdes uten noen manuelle trinn. * * * [Konfigurasjon](https://opencode.ai/docs/nb/formatters#konfigurasjon) ---------------------------------------------------------------------- Du kan tilpasse formattere gjennom `formatter`\-delen i OpenCode-konfigurasjonen. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Hver formateringskonfigurasjon støtter følgende: | Egenskap | Type | Beskrivelse | | --- | --- | --- | | `disabled` | boolean | Sett dette til `true` for å deaktivere formatteren | | `command` | string\[\] | Kommandoen som skal kjøres for formatering | | `environment` | object | Miljøvariabler som skal settes når formateringsverktøyet kjøres | | `extensions` | string\[\] | Filendelser denne formatteren skal håndtere | La oss se på noen eksempler. * * * ### [Deaktivering av formattere](https://opencode.ai/docs/nb/formatters#deaktivering-av-formattere) For å deaktivere **alle** formattere globalt, sett `formatter` til `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} For å deaktivere en **spesifikk** formatter, sett `disabled` til `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Egendefinerte formattere](https://opencode.ai/docs/nb/formatters#egendefinerte-formattere) Du kan overstyre de innebygde formatterne eller legge til nye ved å spesifisere kommandoen, miljøvariablene og filtypene: { "$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"] } }} **Plassholderen $FILE** i kommandoen vil bli erstattet med banen til filen som formateres. --- # サーバー | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/server#_top) サーバー ==== HTTP 経由で OpenCode サーバーと通信します。 `opencode serve` コマンドは、OpenCode クライアントが使用できる OpenAPI エンドポイントを公開するヘッドレス HTTP サーバーを実行します。 * * * ### [使用法](https://opencode.ai/docs/ja/server#%E4%BD%BF%E7%94%A8%E6%B3%95) opencode serve [--port ] [--hostname ] [--cors ] #### [オプション](https://opencode.ai/docs/ja/server#%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%B3) | フラグ | 説明 | デフォルト | | --- | --- | --- | | `--port` | リッスンするポート | `4096` | | `--hostname` | リッスンするホスト名 | `127.0.0.1` | | `--mdns` | mDNS 検出を有効にする | `false` | | `--mdns-domain` | mDNS サービスのカスタムドメイン名 | `opencode.local` | | `--cors` | 許可する追加のブラウザーオリジン | `[]` | `--cors` は複数回渡すことができます。 opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [認証](https://opencode.ai/docs/ja/server#%E8%AA%8D%E8%A8%BC) HTTP 基本認証でサーバーを保護するには、`OPENCODE_SERVER_PASSWORD` を設定します。ユーザー名はデフォルトで `opencode` になるか、`OPENCODE_SERVER_USERNAME` を設定してオーバーライドします。これは、`opencode serve` と `opencode web` の両方に当てはまります。 OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [仕組み](https://opencode.ai/docs/ja/server#%E4%BB%95%E7%B5%84%E3%81%BF) `opencode` を実行すると、TUI とサーバーが起動します。 TUI はサーバーと通信するクライアントです。サーバーは OpenAPI 3.1 仕様のエンドポイントを公開します。このエンドポイントは、[SDK](https://opencode.ai/docs/sdk) を使用してアクセスできます。 `opencode serve` を実行してスタンドアロンサーバーを起動できます。すでに OpenCode TUI を実行している場合でも、`opencode serve` は新しいサーバーを起動します。 * * * #### [既存のサーバーに接続する](https://opencode.ai/docs/ja/server#%E6%97%A2%E5%AD%98%E3%81%AE%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E3%81%AB%E6%8E%A5%E7%B6%9A%E3%81%99%E3%82%8B) TUI を起動すると、ポートとホスト名がランダムに割り当てられます。代わりに、`--hostname` と `--port` [フラグ](https://opencode.ai/docs/cli) を使用して固定できます。次に、これを使用してサーバーに接続します。 [`/tui`](https://opencode.ai/docs/ja/server#tui) エンドポイントは、サーバー経由で TUI を駆動するために使用できます。たとえば、プロンプトを事前入力したり、実行したりできます。この設定は、OpenCode [IDE](https://opencode.ai/docs/ide) プラグインによって使用されます。 * * * [仕様](https://opencode.ai/docs/ja/server#%E4%BB%95%E6%A7%98) ------------------------------------------------------------ サーバーは、次の場所で閲覧できる OpenAPI 3.1 仕様を公開しています。 http://:/doc たとえば、`http://localhost:4096/doc`。この仕様を使用して、クライアントを生成したり、要求と応答のタイプを検査したりできます。または、Swagger エクスプローラーで表示します。 * * * [API](https://opencode.ai/docs/ja/server#api) ---------------------------------------------- OpenCode サーバーは次の API を公開します。 * * * ### [Global](https://opencode.ai/docs/ja/server#global) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/global/health` | サーバーの健全性とバージョンを取得する | `{ healthy: true, version: string }` | | `GET` | `/global/event` | グローバルイベントの取得 (SSE ストリーム) | イベントストリーム | * * * ### [Project](https://opencode.ai/docs/ja/server#project) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/project` | すべてのプロジェクトをリストする | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | 現在のプロジェクトを取得 | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Path and VCS](https://opencode.ai/docs/ja/server#path-and-vcs) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/path` | 現在のパスを取得する | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | 現在のプロジェクトの VCS 情報を取得する | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Instance](https://opencode.ai/docs/ja/server#instance) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | 現在のインスタンスを破棄する | void | * * * ### [Config](https://opencode.ai/docs/ja/server#config) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/config` | 設定情報を取得する | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | 設定を更新する | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | プロバイダーとデフォルトのモデルをリストする | `{ providers:` [`Provider[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [プロバイダー](https://opencode.ai/docs/ja/server#%E3%83%97%E3%83%AD%E3%83%90%E3%82%A4%E3%83%80%E3%83%BC) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/provider` | すべてのプロバイダーをリストする | `{ all:` [`Provider[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | プロバイダーの認証方法を取得する | `{ [providerID: string]:` [`ProviderAuthMethod[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | OAuth を使用してプロバイダーを認証する | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | プロバイダーの OAuth コールバックを処理する | void | * * * ### [Session](https://opencode.ai/docs/ja/server#session) | メソッド | パス | 説明 | 詳細 | | --- | --- | --- | --- | | `GET` | `/session` | すべてのセッションをリストする | 戻り値 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | 新しいセッションを作成する | 本文: `{ parentID?, title? }`、[`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
を返します。 | | `GET` | `/session/status` | すべてのセッションのセッションステータスを取得する | 戻り値 `{ [sessionID: string]:` [`SessionStatus`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | セッションの詳細を取得する | 戻り値 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | セッションとそのすべてのデータを削除する | 戻り値 `boolean` | | `PATCH` | `/session/:id` | セッションのプロパティを更新する | 本文: `{ title? }`、[`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
を返します。 | | `GET` | `/session/:id/children` | セッションの子セッションを取得する | 戻り値 [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | セッションの ToDo リストを取得する | 戻り値 [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | アプリを分析して `AGENTS.md` を作成する | 本文: `{ messageID, providerID, modelID }`、`boolean` を返します。 | | `POST` | `/session/:id/fork` | メッセージで既存のセッションをフォークする | 本文: `{ messageID? }`、[`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
を返します。 | | `POST` | `/session/:id/abort` | 実行中のセッションを中止する | 戻り値 `boolean` | | `POST` | `/session/:id/share` | セッションを共有する | 戻り値 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | セッションの共有を解除する | 戻り値 [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | このセッションの差分を取得する | クエリ: `messageID?`、[`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
を返します。 | | `POST` | `/session/:id/summarize` | セッションを要約する | 本文: `{ providerID, modelID }`、`boolean` を返します。 | | `POST` | `/session/:id/revert` | メッセージを元に戻す | 本文: `{ messageID, partID? }`、`boolean` を返します。 | | `POST` | `/session/:id/unrevert` | 元に戻したすべてのメッセージを復元する | 戻り値 `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | 許可リクエストに応答する | 本文: `{ response, remember? }`、`boolean` を返します。 | * * * ### [Message](https://opencode.ai/docs/ja/server#message) | メソッド | パス | 説明 | 詳細 | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | セッション内のメッセージをリストする | クエリ: `limit?`、`{ info:` [`Message`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [`Part[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` を返します。 | | `POST` | `/session/:id/message` | メッセージを送信して応答を待ちます | 本文: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`、`{ info:` [`Message`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [`Part[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` を返します | | `GET` | `/session/:id/message/:messageID` | メッセージの詳細を取得する | 戻り値 `{ info:` [`Message`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [`Part[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | メッセージを非同期に送信する (待機なし) | body: `/session/:id/message` と同じ、`204 No Content` を返します。 | | `POST` | `/session/:id/command` | スラッシュコマンドを実行します | 本文: `{ messageID?, agent?, model?, command, arguments }`、`{ info:` [`Message`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [`Part[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` を返します | | `POST` | `/session/:id/shell` | シェルコマンドを実行する | 本文: `{ agent, model?, command }`、`{ info:` [`Message`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [`Part[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` を返します | * * * ### [Command](https://opencode.ai/docs/ja/server#command) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/command` | すべてのコマンドをリストする | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [File](https://opencode.ai/docs/ja/server#file) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | ファイル内のテキストを検索 | `path`、`lines`、`line_number`、`absolute_offset`、`submatches` と一致するオブジェクトの配列 | | `GET` | `/find/file?query=` | ファイルとディレクトリを名前で検索する | `string[]` (パス) | | `GET` | `/find/symbol?query=` | ワークスペースのシンボルを検索する | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | ファイルとディレクトリをリストする | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | ファイルを読む | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | 追跡されたファイルのステータスを取得する | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` クエリパラメータ](https://opencode.ai/docs/ja/server#findfile-%E3%82%AF%E3%82%A8%E3%83%AA%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF) * `query` (必須) — 検索文字列 (あいまい一致) * `type` (オプション) — 結果を `"file"` または `"directory"` に制限します * `directory` (オプション) — 検索用のプロジェクトルートをオーバーライドします。 * `limit` (オプション) — 最大結果 (1 ~ 200) * `dirs` (オプション) — 従来のフラグ (`"false"` はファイルのみを返します) * * * ### [Tool (Experimental)](https://opencode.ai/docs/ja/server#tool-experimental) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | すべてのツール ID をリストする | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | モデルの JSON スキーマを含むツールをリストする | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, Formatter, MCP](https://opencode.ai/docs/ja/server#lsp-formatter-mcp) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/lsp` | LSP サーバーのステータスを取得 | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | フォーマッタのステータスを取得する | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | MCP サーバーのステータスを取得する | `{ [name: string]:` [`MCPStatus`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | MCP サーバーを動的に追加する | 本文: `{ name, config }`、MCP ステータスオブジェクトを返します。 | * * * ### [Agent](https://opencode.ai/docs/ja/server#agent) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/agent` | 利用可能なすべてのエージェントをリストする | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Logging](https://opencode.ai/docs/ja/server#logging) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `POST` | `/log` | ログエントリを書き込みます。本体:`{ service, level, message, extra? }` | void | * * * ### [TUI](https://opencode.ai/docs/ja/server#tui) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | プロンプトにテキストを追加します | void | | `POST` | `/tui/open-help` | ヘルプダイアログを開く | void | | `POST` | `/tui/open-sessions` | セッションセレクターを開く | void | | `POST` | `/tui/open-themes` | テーマセレクターを開く | void | | `POST` | `/tui/open-models` | モデルセレクターを開く | void | | `POST` | `/tui/submit-prompt` | 現在のプロンプトを送信します | void | | `POST` | `/tui/clear-prompt` | プロンプトをクリア | void | | `POST` | `/tui/execute-command` | コマンドを実行する (`{ command }`) | void | | `POST` | `/tui/show-toast` | トーストを表示 (`{ title?, message, variant }`) | void | | `GET` | `/tui/control/next` | 次の制御リクエストを待ちます | 制御リクエストオブジェクト | | `POST` | `/tui/control/response` | 制御リクエストに応答する (`{ body }`) | void | * * * ### [Auth](https://opencode.ai/docs/ja/server#auth) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | 認証資格情報を設定します。本文はプロバイダーのスキーマと一致する必要があります | void | * * * ### [Event](https://opencode.ai/docs/ja/server#event) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/event` | サーバー送信イベントストリーム。最初のイベントは `server.connected`、次にバスイベント | サーバー送信イベントストリーム | * * * ### [Documentation](https://opencode.ai/docs/ja/server#documentation) | メソッド | パス | 説明 | レスポンス | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1 仕様 | OpenAPI 仕様を備えた HTML ページ | --- # Configuração | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/config#_top) Configuração ============ Usando a configuração JSON do opencode. Você pode configurar o opencode usando um arquivo de configuração JSON. * * * [Formato](https://opencode.ai/docs/pt-br/config#formato) --------------------------------------------------------- O opencode suporta os formatos **JSON** e **JSONC** (JSON com Comentários). { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [Locais](https://opencode.ai/docs/pt-br/config#locais) ------------------------------------------------------- Você pode colocar sua configuração em alguns locais diferentes e eles têm uma ordem de precedência diferente. Os arquivos de configuração são mesclados, não substituídos. As configurações das seguintes localizações de configuração são combinadas. Configurações posteriores substituem as anteriores apenas para chaves conflitantes. Configurações não conflitantes de todas as configurações são preservadas. Por exemplo, se sua configuração global define `autoupdate: true` e sua configuração de projeto define `model: "anthropic/claude-sonnet-4-5"`, a configuração final incluirá as duas configurações. * * * ### [Ordem de precedência](https://opencode.ai/docs/pt-br/config#ordem-de-preced%C3%AAncia) As fontes de configuração são carregadas nesta ordem (fontes posteriores substituem as anteriores): 1. **Configuração remota** (de `.well-known/opencode`) - padrões organizacionais 2. **Configuração global** (`~/.config/opencode/opencode.json`) - preferências do usuário 3. **Configuração personalizada** (`OPENCODE_CONFIG` var de ambiente) - substituições personalizadas 4. **Configuração do projeto** (`opencode.json` no projeto) - configurações específicas do projeto 5. **Diretórios `.opencode`** - agentes, comandos, plugins 6. **Configuração inline** (`OPENCODE_CONFIG_CONTENT` var de ambiente) - substituições em tempo de execução Isso significa que as configurações do projeto podem substituir os padrões globais, e as configurações globais podem substituir os padrões organizacionais remotos. * * * ### [Remoto](https://opencode.ai/docs/pt-br/config#remoto) As organizações podem fornecer configuração padrão através do endpoint `.well-known/opencode`. Isso é buscado automaticamente quando você se autentica com um provedor que o suporta. A configuração remota é carregada primeiro, servindo como a camada base. Todas as outras fontes de configuração (global, projeto) podem substituir esses padrões. Por exemplo, se sua organização fornece servidores MCP que estão desativados por padrão: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Você pode habilitar servidores específicos em sua configuração local: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global](https://opencode.ai/docs/pt-br/config#global) Coloque sua configuração global do opencode em `~/.config/opencode/opencode.json`. Use a configuração global para preferências de todo o usuário, como provedores, modelos e permissões. Para configurações específicas do TUI, use `~/.config/opencode/tui.json`. A configuração global substitui os padrões organizacionais remotos. * * * ### [Por projeto](https://opencode.ai/docs/pt-br/config#por-projeto) Adicione `opencode.json` na raiz do seu projeto. A configuração do projeto tem a maior precedência entre os arquivos de configuração padrão - ela substitui tanto as configurações globais quanto as remotas. Para configurações específicas do TUI do projeto, adicione `tui.json` junto a ele. Quando o opencode é iniciado, ele procura um arquivo de configuração no diretório atual ou sobe até o diretório Git mais próximo. Isso também é seguro para ser verificado no Git e usa o mesmo esquema que o global. * * * ### [Caminho personalizado](https://opencode.ai/docs/pt-br/config#caminho-personalizado) Especifique um caminho de arquivo de configuração personalizado usando a variável de ambiente `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" A configuração personalizada é carregada entre as configurações globais e do projeto na ordem de precedência. * * * ### [Diretório personalizado](https://opencode.ai/docs/pt-br/config#diret%C3%B3rio-personalizado) Especifique um diretório de configuração personalizado usando a variável de ambiente `OPENCODE_CONFIG_DIR`. Este diretório será pesquisado por agentes, comandos, modos e plugins, assim como o diretório padrão `.opencode`, e deve seguir a mesma estrutura. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" O diretório personalizado é carregado após a configuração global e os diretórios `.opencode`, então ele **pode substituir** suas configurações. * * * [Esquema](https://opencode.ai/docs/pt-br/config#esquema) --------------------------------------------------------- O esquema de configuração do servidor/tempo de execução é definido em [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . A configuração do TUI usa [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) . Seu editor deve ser capaz de validar e autocompletar com base no esquema. * * * ### [TUI](https://opencode.ai/docs/pt-br/config#tui) Use um arquivo `tui.json` (ou `tui.jsonc`) dedicado para configurações específicas do TUI. { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Use `OPENCODE_TUI_CONFIG` para apontar para um arquivo de configuração TUI personalizado. Chaves legadas `theme`, `keybinds` e `tui` em `opencode.json` estão obsoletas e são migradas automaticamente quando possível. [Saiba mais sobre a configuração do TUI aqui](https://opencode.ai/docs/tui#configure) . * * * ### [Servidor](https://opencode.ai/docs/pt-br/config#servidor) Você pode configurar as configurações do servidor para os comandos `opencode serve` e `opencode web` através da opção `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Opções disponíveis: * `port` - Porta para escutar. * `hostname` - Nome do host para escutar. Quando `mdns` está habilitado e nenhum nome de host está definido, o padrão é `0.0.0.0`. * `mdns` - Habilitar descoberta de serviço mDNS. Isso permite que outros dispositivos na rede descubram seu servidor opencode. * `mdnsDomain` - Nome de domínio personalizado para o serviço mDNS. O padrão é `opencode.local`. Útil para executar várias instâncias na mesma rede. * `cors` - Origens adicionais a serem permitidas para CORS ao usar o servidor HTTP de um cliente baseado em navegador. Os valores devem ser origens completas (esquema + host + porta opcional), por exemplo, `https://app.example.com`. [Saiba mais sobre o servidor aqui](https://opencode.ai/docs/server) . * * * ### [Ferramentas](https://opencode.ai/docs/pt-br/config#ferramentas) Você pode gerenciar as ferramentas que um LLM pode usar através da opção `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Saiba mais sobre ferramentas aqui](https://opencode.ai/docs/tools) . * * * ### [Modelos](https://opencode.ai/docs/pt-br/config#modelos) Você pode configurar os provedores e modelos que deseja usar em sua configuração do opencode através das opções `provider`, `model` e `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} A opção `small_model` configura um modelo separado para tarefas leves, como geração de títulos. Por padrão, o opencode tenta usar um modelo mais barato se um estiver disponível do seu provedor, caso contrário, ele recua para seu modelo principal. As opções do provedor podem incluir `timeout` e `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Tempo limite da solicitação em milissegundos (padrão: 300000). Defina como `false` para desabilitar. * `setCacheKey` - Garantir que uma chave de cache seja sempre definida para o provedor designado. Você também pode configurar [modelos locais](https://opencode.ai/docs/models#local) . [Saiba mais](https://opencode.ai/docs/models) . * * * #### [Opções Específicas do Provedor](https://opencode.ai/docs/pt-br/config#op%C3%A7%C3%B5es-espec%C3%ADficas-do-provedor) Alguns provedores suportam opções de configuração adicionais além das configurações genéricas `timeout` e `apiKey`. ##### [Amazon Bedrock](https://opencode.ai/docs/pt-br/config#amazon-bedrock) Amazon Bedrock suporta configuração específica da AWS: { "$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` - Região AWS para Bedrock (padrão para `AWS_REGION` var de ambiente ou `us-east-1`) * `profile` - Perfil nomeado da AWS em `~/.aws/credentials` (padrão para `AWS_PROFILE` var de ambiente) * `endpoint` - URL de endpoint personalizada para endpoints VPC. Este é um alias para a opção genérica `baseURL` usando terminologia específica da AWS. Se ambos forem especificados, `endpoint` tem precedência. [Saiba mais sobre a configuração do Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Temas](https://opencode.ai/docs/pt-br/config#temas) Defina seu tema de interface em `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [Saiba mais aqui](https://opencode.ai/docs/themes) . * * * ### [Agentes](https://opencode.ai/docs/pt-br/config#agentes) Você pode configurar agentes especializados para tarefas específicas através da opção `agent`. { "$schema": "https://opencode.ai/config.json", "agent": { "code-reviewer": { "description": "Revisa código para melhores práticas e potenciais problemas", "model": "anthropic/claude-sonnet-4-5", "prompt": "Você é um revisor de código. Foque em segurança, performance e manutenibilidade.", "tools": { // Desabilitar ferramentas de modificação de arquivo para agente de apenas revisão "write": false, "edit": false, }, }, },} Você também pode definir agentes usando arquivos markdown em `~/.config/opencode/agents/` ou `.opencode/agents/`. [Saiba mais aqui](https://opencode.ai/docs/agents) . * * * ### [Agente padrão](https://opencode.ai/docs/pt-br/config#agente-padr%C3%A3o) Você pode definir o agente padrão usando a opção `default_agent`. Isso determina qual agente é usado quando nenhum é explicitamente especificado. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} O agente padrão deve ser um agente primário (não um subagente). Isso pode ser um agente embutido como `"build"` ou `"plan"`, ou um [agente personalizado](https://opencode.ai/docs/agents) que você definiu. Se o agente especificado não existir ou for um subagente, o opencode recuará para `"build"` com um aviso. Essa configuração se aplica a todas as interfaces: TUI, CLI (`opencode run`), aplicativo desktop e GitHub Action. * * * ### [Compartilhamento](https://opencode.ai/docs/pt-br/config#compartilhamento) Você pode configurar o recurso [share](https://opencode.ai/docs/share) através da opção `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Isso aceita: * `"manual"` - Permitir compartilhamento manual via comandos (padrão) * `"auto"` - Compartilhar novas conversas automaticamente * `"disabled"` - Desabilitar compartilhamento completamente Por padrão, o compartilhamento é definido para o modo manual, onde você precisa compartilhar explicitamente as conversas usando o comando `/share`. * * * ### [Comandos](https://opencode.ai/docs/pt-br/config#comandos) Você pode configurar comandos personalizados para tarefas repetitivas através da opção `command`. { "$schema": "https://opencode.ai/config.json", "command": { "test": { "template": "Execute a suíte de testes completa com relatório de cobertura e mostre quaisquer falhas.\nConcentre-se nos testes com falha e sugira correções.", "description": "Execute testes com cobertura", "agent": "build", "model": "anthropic/claude-haiku-4-5", }, "component": { "template": "Crie um novo componente React chamado $ARGUMENTS com suporte a TypeScript.\nInclua tipagem adequada e estrutura básica.", "description": "Crie um novo componente", }, },} Você também pode definir comandos usando arquivos markdown em `~/.config/opencode/commands/` ou `.opencode/commands/`. [Saiba mais aqui](https://opencode.ai/docs/commands) . * * * ### [Atalhos de teclado](https://opencode.ai/docs/pt-br/config#atalhos-de-teclado) Personalize atalhos de teclado em `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [Saiba mais aqui](https://opencode.ai/docs/keybinds) . * * * ### [Atualização automática](https://opencode.ai/docs/pt-br/config#atualiza%C3%A7%C3%A3o-autom%C3%A1tica) O opencode fará o download automaticamente de quaisquer novas atualizações quando for iniciado. Você pode desabilitar isso com a opção `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Se você não quiser atualizações, mas deseja ser notificado quando uma nova versão estiver disponível, defina `autoupdate` como `"notify"`. Observe que isso só funciona se não foi instalado usando um gerenciador de pacotes como o Homebrew. * * * ### [Formatadores](https://opencode.ai/docs/pt-br/config#formatadores) Você pode configurar formatadores de código através da opção `formatter`. { "$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"] } }} [Saiba mais sobre formatadores aqui](https://opencode.ai/docs/formatters) . * * * ### [Permissões](https://opencode.ai/docs/pt-br/config#permiss%C3%B5es) Por padrão, o opencode **permite todas as operações** sem exigir aprovação explícita. Você pode mudar isso usando a opção `permission`. Por exemplo, para garantir que as ferramentas `edit` e `bash` exijam aprovação do usuário: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Saiba mais sobre permissões aqui](https://opencode.ai/docs/permissions) . * * * ### [Compactação](https://opencode.ai/docs/pt-br/config#compacta%C3%A7%C3%A3o) Você pode controlar o comportamento de compactação de contexto através da opção `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - Compactar automaticamente a sessão quando o contexto estiver cheio (padrão: `true`). * `prune` - Remover saídas antigas de ferramentas para economizar tokens (padrão: `true`). * `reserved` - Buffer de tokens para compactação. Deixa janela suficiente para evitar estouro durante a compactação * * * ### [Observador](https://opencode.ai/docs/pt-br/config#observador) Você pode configurar padrões de ignorar do observador de arquivos através da opção `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Os padrões seguem a sintaxe glob. Use isso para excluir diretórios barulhentos da observação de arquivos. * * * ### [Servidores MCP](https://opencode.ai/docs/pt-br/config#servidores-mcp) Você pode configurar servidores MCP que deseja usar através da opção `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Saiba mais aqui](https://opencode.ai/docs/mcp-servers) . * * * ### [Plugins](https://opencode.ai/docs/pt-br/config#plugins) [Plugins](https://opencode.ai/docs/plugins) estendem o opencode com ferramentas, hooks e integrações personalizadas. Coloque arquivos de plugin em `.opencode/plugins/` ou `~/.config/opencode/plugins/`. Você também pode carregar plugins do npm através da opção `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Saiba mais aqui](https://opencode.ai/docs/plugins) . * * * ### [Instruções](https://opencode.ai/docs/pt-br/config#instru%C3%A7%C3%B5es) Você pode configurar as instruções para o modelo que está usando através da opção `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Isso aceita um array de caminhos e padrões glob para arquivos de instrução. [Saiba mais sobre regras aqui](https://opencode.ai/docs/rules) . * * * ### [Provedores desabilitados](https://opencode.ai/docs/pt-br/config#provedores-desabilitados) Você pode desabilitar provedores que são carregados automaticamente através da opção `disabled_providers`. Isso é útil quando você deseja impedir que certos provedores sejam carregados, mesmo que suas credenciais estejam disponíveis. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} A opção `disabled_providers` aceita um array de IDs de provedores. Quando um provedor é desabilitado: * Ele não será carregado, mesmo que variáveis de ambiente estejam definidas. * Ele não será carregado, mesmo que chaves de API estejam configuradas através do comando `/connect`. * Os modelos do provedor não aparecerão na lista de seleção de modelos. * * * ### [Provedores habilitados](https://opencode.ai/docs/pt-br/config#provedores-habilitados) Você pode especificar uma lista de permissão de provedores através da opção `enabled_providers`. Quando definida, apenas os provedores especificados serão habilitados e todos os outros serão ignorados. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Isso é útil quando você deseja restringir o opencode para usar apenas provedores específicos, em vez de desabilitá-los um a um. Se um provedor aparecer em `enabled_providers` e `disabled_providers`, a `disabled_providers` tem prioridade para compatibilidade retroativa. * * * ### [Experimental](https://opencode.ai/docs/pt-br/config#experimental) A chave `experimental` contém opções que estão em desenvolvimento ativo. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variáveis](https://opencode.ai/docs/pt-br/config#vari%C3%A1veis) ------------------------------------------------------------------ Você pode usar substituição de variáveis em seus arquivos de configuração para referenciar variáveis de ambiente e conteúdos de arquivos. * * * ### [Variáveis de ambiente](https://opencode.ai/docs/pt-br/config#vari%C3%A1veis-de-ambiente) Use `{env:VARIABLE_NAME}` para substituir variáveis de ambiente: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Se a variável de ambiente não estiver definida, ela será substituída por uma string vazia. * * * ### [Arquivos](https://opencode.ai/docs/pt-br/config#arquivos) Use `{file:path/to/file}` para substituir o conteúdo de um arquivo: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Os caminhos dos arquivos podem ser: * Relativos ao diretório do arquivo de configuração * Ou caminhos absolutos começando com `/` ou `~` Esses são úteis para: * Manter dados sensíveis, como chaves de API, em arquivos separados. * Incluir grandes arquivos de instrução sem sobrecarregar sua configuração. * Compartilhar trechos de configuração comuns entre vários arquivos de configuração. --- # الخادم | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/server#_top) الخادم ====== تفاعل مع خادم opencode عبر HTTP. يشغّل الأمر `opencode serve` خادما HTTP دون واجهة ويعرض نقطة نهاية OpenAPI يمكن لعميل opencode استخدامها. * * * ### [الاستخدام](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85) opencode serve [--port ] [--hostname ] [--cors ] #### [الخيارات](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%AE%D9%8A%D8%A7%D8%B1%D8%A7%D8%AA) | الخيار | الوصف | الافتراضي | | --- | --- | --- | | `--port` | المنفذ الذي يستمع عليه | `4096` | | `--hostname` | اسم المضيف الذي يستمع عليه | `127.0.0.1` | | `--mdns` | تفعيل اكتشاف mDNS | `false` | | `--mdns-domain` | اسم نطاق مخصص لخدمة mDNS | `opencode.local` | | `--cors` | أصول (Origins) متصفح إضافية مسموح بها | `[]` | يمكن تمرير `--cors` عدة مرات: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [المصادقة](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D8%B5%D8%A7%D8%AF%D9%82%D8%A9) عيّن `OPENCODE_SERVER_PASSWORD` لحماية الخادم باستخدام مصادقة HTTP الأساسية. اسم المستخدم افتراضيا هو `opencode`، أو عيّن `OPENCODE_SERVER_USERNAME` لتغييره. ينطبق ذلك على كل من `opencode serve` و `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [كيف يعمل](https://opencode.ai/docs/ar/server#%D9%83%D9%8A%D9%81-%D9%8A%D8%B9%D9%85%D9%84) عند تشغيل `opencode` يبدأ تشغيل واجهة terminal تفاعلية (TUI) وخادما. تكون الـ TUI هي العميل الذي يتحدث إلى الخادم. يوفّر الخادم نقطة نهاية لمواصفة OpenAPI 3.1. وتُستخدم هذه النقطة أيضا لتوليد [SDK](https://opencode.ai/docs/sdk) . تتيح هذه البنية لـ opencode دعم عدة عملاء وتمكّنك من التفاعل مع opencode برمجيا. يمكنك تشغيل `opencode serve` لبدء خادم مستقل. إذا كانت واجهة opencode في terminal (TUI) قيد التشغيل، فسيبدأ `opencode serve` خادما جديدا. * * * #### [الاتصال بخادم موجود](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%A7%D8%AA%D8%B5%D8%A7%D9%84-%D8%A8%D8%AE%D8%A7%D8%AF%D9%85-%D9%85%D9%88%D8%AC%D9%88%D8%AF) عند بدء الـ TUI تقوم بتعيين منفذ واسم مضيف عشوائيا. يمكنك بدلا من ذلك تمرير [الخيارات](https://opencode.ai/docs/cli) `--hostname` و `--port`، ثم استخدامهما للاتصال بخادمها. يمكن استخدام نقطة النهاية [`/tui`](https://opencode.ai/docs/ar/server#tui) للتحكم في الـ TUI عبر الخادم. على سبيل المثال، يمكنك تعبئة الموجّه مسبقا أو تشغيله. يُستخدم هذا الإعداد بواسطة ملحقات OpenCode لـ [IDE](https://opencode.ai/docs/ide) . * * * [المواصفات](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D9%88%D8%A7%D8%B5%D9%81%D8%A7%D8%AA) ------------------------------------------------------------------------------------------------------- ينشر الخادم مواصفة OpenAPI 3.1 ويمكن عرضها على: http://:/doc على سبيل المثال: `http://localhost:4096/doc`. استخدم المواصفة لتوليد عملاء أو لفحص أنواع الطلبات والاستجابات. أو اعرضها في مستكشف Swagger. * * * [واجهات API](https://opencode.ai/docs/ar/server#%D9%88%D8%A7%D8%AC%D9%87%D8%A7%D8%AA-api) ------------------------------------------------------------------------------------------ يعرض خادم opencode واجهات API التالية. * * * ### [عام](https://opencode.ai/docs/ar/server#%D8%B9%D8%A7%D9%85) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/global/health` | الحصول على صحة الخادم وإصداره | `{ healthy: true, version: string }` | | `GET` | `/global/event` | الحصول على الأحداث العامة (تدفق SSE) | تدفق أحداث | * * * ### [المشروع](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D8%B4%D8%B1%D9%88%D8%B9) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/project` | سرد جميع المشاريع | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | الحصول على المشروع الحالي | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [المسار و VCS](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D8%B3%D8%A7%D8%B1-%D9%88-vcs) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/path` | الحصول على المسار الحالي | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | الحصول على معلومات VCS للمشروع الحالي | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [المثيل](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D8%AB%D9%8A%D9%84) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | التخلص من المثيل الحالي | `boolean` | * * * ### [الإعدادات](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF%D8%A7%D8%AA) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/config` | الحصول على معلومات الإعدادات | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | تحديث الإعدادات | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | سرد المزوّدين والنماذج الافتراضية | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [المزوّد](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D8%B2%D9%88%D9%91%D8%AF) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/provider` | سرد جميع المزوّدين | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | الحصول على طرق مصادقة المزوّد | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | تفويض مزوّد باستخدام OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | معالجة رد نداء OAuth لمزوّد | `boolean` | * * * ### [الجلسات](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%AC%D9%84%D8%B3%D8%A7%D8%AA) | الطريقة | المسار | الوصف | الملاحظات | | --- | --- | --- | --- | | `GET` | `/session` | سرد جميع الجلسات | يعيد [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | إنشاء جلسة جديدة | المتن: `{ parentID?, title? }`، يعيد [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | الحصول على حالة الجلسات جميعها | يعيد `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | الحصول على تفاصيل الجلسة | يعيد [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | حذف جلسة وجميع بياناتها | يعيد `boolean` | | `PATCH` | `/session/:id` | تحديث خصائص الجلسة | المتن: `{ title? }`، يعيد [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | الحصول على الجلسات الفرعية لجلسة | يعيد [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | الحصول على قائمة المهام (todo) للجلسة | يعيد [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | تحليل التطبيق وإنشاء `AGENTS.md` | المتن: `{ messageID, providerID, modelID }`، يعيد `boolean` | | `POST` | `/session/:id/fork` | تفريع جلسة موجودة عند رسالة | المتن: `{ messageID? }`، يعيد [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | إلغاء جلسة قيد التشغيل | يعيد `boolean` | | `POST` | `/session/:id/share` | مشاركة جلسة | يعيد [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | إلغاء مشاركة جلسة | يعيد [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | الحصول على diff لهذه الجلسة | الاستعلام: `messageID?`، يعيد [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | تلخيص الجلسة | المتن: `{ providerID, modelID }`، يعيد `boolean` | | `POST` | `/session/:id/revert` | التراجع عن رسالة | المتن: `{ messageID, partID? }`، يعيد `boolean` | | `POST` | `/session/:id/unrevert` | استعادة جميع الرسائل المتراجع عنها | يعيد `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | الرد على طلب إذن | المتن: `{ response, remember? }`، يعيد `boolean` | * * * ### [الرسائل](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%B1%D8%B3%D8%A7%D8%A6%D9%84) | الطريقة | المسار | الوصف | الملاحظات | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | سرد رسائل جلسة | الاستعلام: `limit?`، يعيد `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | إرسال رسالة والانتظار للحصول على رد | المتن: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`، يعيد `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | الحصول على تفاصيل الرسالة | يعيد `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | إرسال رسالة بشكل غير متزامن (بدون انتظار) | المتن: مثل `/session/:id/message`، يعيد `204 No Content` | | `POST` | `/session/:id/command` | تنفيذ أمر شرطة مائلة (slash) | المتن: `{ messageID?, agent?, model?, command, arguments }`، يعيد `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | تشغيل أمر في shell | المتن: `{ agent, model?, command }`، يعيد `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [الأوامر](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%A3%D9%88%D8%A7%D9%85%D8%B1) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/command` | سرد جميع الأوامر | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [الملفات](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D9%84%D9%81%D8%A7%D8%AA) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | البحث عن نص داخل الملفات | مصفوفة من كائنات المطابقة تحتوي على `path` و`lines` و`line_number` و`absolute_offset` و`submatches` | | `GET` | `/find/file?query=` | العثور على الملفات والمجلدات بالاسم | `string[]` (مسارات) | | `GET` | `/find/symbol?query=` | العثور على رموز مساحة العمل | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | سرد الملفات والمجلدات | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | قراءة ملف | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | الحصول على حالة الملفات المتعقّبة | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [معلمات الاستعلام لـ `/find/file`](https://opencode.ai/docs/ar/server#%D9%85%D8%B9%D9%84%D9%85%D8%A7%D8%AA-%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%B9%D9%84%D8%A7%D9%85-%D9%84%D9%80-findfile) * `query` (مطلوب) — سلسلة البحث (مطابقة ضبابية) * `type` (اختياري) — حصر النتائج في `"file"` أو `"directory"` * `directory` (اختياري) — تجاوز جذر المشروع لأجل البحث * `limit` (اختياري) — الحد الأقصى للنتائج (1–200) * `dirs` (اختياري) — خيار قديم (إرجاع `"false"` يعيد الملفات فقط) * * * ### [الأدوات (تجريبية)](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%A3%D8%AF%D9%88%D8%A7%D8%AA-%D8%AA%D8%AC%D8%B1%D9%8A%D8%A8%D9%8A%D8%A9) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | سرد جميع معرّفات الأدوات | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | سرد الأدوات مع مخططات JSON لنموذج | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP والمنسّقات و MCP](https://opencode.ai/docs/ar/server#lsp-%D9%88%D8%A7%D9%84%D9%85%D9%86%D8%B3%D9%91%D9%82%D8%A7%D8%AA-%D9%88-mcp) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/lsp` | الحصول على حالة خادم LSP | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | الحصول على حالة المنسّقات | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | الحصول على حالة خادم MCP | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | إضافة خادم MCP ديناميكيا | المتن: `{ name, config }`، يعيد كائن حالة MCP | * * * ### [الوكلاء](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%88%D9%83%D9%84%D8%A7%D8%A1) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/agent` | سرد جميع الوكلاء المتاحين | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [التسجيل](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%AA%D8%B3%D8%AC%D9%8A%D9%84) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `POST` | `/log` | كتابة إدخال سجل. المتن: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/ar/server#tui) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | إلحاق نص بالموجّه | `boolean` | | `POST` | `/tui/open-help` | فتح مربع حوار المساعدة | `boolean` | | `POST` | `/tui/open-sessions` | فتح محدد الجلسات | `boolean` | | `POST` | `/tui/open-themes` | فتح محدد السمات | `boolean` | | `POST` | `/tui/open-models` | فتح محدد النماذج | `boolean` | | `POST` | `/tui/submit-prompt` | إرسال الموجّه الحالي | `boolean` | | `POST` | `/tui/clear-prompt` | مسح الموجّه | `boolean` | | `POST` | `/tui/execute-command` | تنفيذ أمر (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | عرض toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | الانتظار لطلب التحكم التالي | كائن طلب تحكم | | `POST` | `/tui/control/response` | الاستجابة لطلب تحكم (`{ body }`) | `boolean` | * * * ### [المصادقة](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D9%85%D8%B5%D8%A7%D8%AF%D9%82%D8%A9-1) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | تعيين بيانات اعتماد المصادقة. يجب أن يطابق المتن مخطط المزوّد | `boolean` | * * * ### [الأحداث](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/event` | تدفق أحداث مرسلة من الخادم (SSE). أول حدث هو `server.connected` ثم أحداث الحافلة | تدفق أحداث مرسلة من الخادم | * * * ### [التوثيق](https://opencode.ai/docs/ar/server#%D8%A7%D9%84%D8%AA%D9%88%D8%AB%D9%8A%D9%82) | الطريقة | المسار | الوصف | الاستجابة | | --- | --- | --- | --- | | `GET` | `/doc` | مواصفة OpenAPI 3.1 | صفحة HTML تتضمن مواصفة OpenAPI | --- # Sunucu | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/server#_top) Sunucu ====== opencode sunucusuyla HTTP uzerinden etkilesin. `opencode serve` komutu, opencode istemcisinin kullanabileceği bir OpenAPI endpoint’i açan headless bir HTTP sunucusu çalıştırır. * * * ### [Kullanım](https://opencode.ai/docs/tr/server#kullan%C4%B1m) opencode serve [--port ] [--hostname ] [--cors ] #### [Seçenekler](https://opencode.ai/docs/tr/server#se%C3%A7enekler) | Bayrak | Açıklama | Varsayılan | | --- | --- | --- | | `--port` | Dinlenecek bağlantı noktası | `4096` | | `--hostname` | Dinlenecek ana bilgisayar adı | `127.0.0.1` | | `--mdns` | mDNS keşfini etkinleştir | `false` | | `--mdns-domain` | mDNS hizmeti için özel alan adı | `opencode.local` | | `--cors` | İzin verilecek ek tarayıcı kaynakları (origin) | `[]` | `--cors` birden fazla kez geçilebilir: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Kimlik Doğrulama](https://opencode.ai/docs/tr/server#kimlik-do%C4%9Frulama) Sunucuyu HTTP temel kimlik doğrulama (basic auth) ile korumak için `OPENCODE_SERVER_PASSWORD` ayarlayın. Kullanıcı adı varsayılan olarak `opencode` değeridir; değiştirmek isterseniz `OPENCODE_SERVER_USERNAME` ayarlayabilirsiniz. Bu ayar hem `opencode serve` hem de `opencode web` için geçerlidir. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Nasıl çalışır](https://opencode.ai/docs/tr/server#nas%C4%B1l-%C3%A7al%C4%B1%C5%9F%C4%B1r) `opencode` çalıştırdığınızda hem TUI hem de sunucu başlar. TUI, sunucuyla konuşan istemci tarafıdır. Sunucu bir OpenAPI 3.1 spesifikasyon uç noktası açar. Bu uç nokta [SDK](https://opencode.ai/docs/sdk) üretiminde de kullanılır. Bu mimari, opencode’un birden fazla istemciyi desteklemesini ve programatik kullanımları mümkün kılmasını sağlar. `opencode serve` ile bağımsız bir sunucu başlatabilirsiniz. opencode TUI açıksa, `opencode serve` yeni bir sunucu başlatır. * * * #### [Mevcut sunucuya bağlanın](https://opencode.ai/docs/tr/server#mevcut-sunucuya-ba%C4%9Flan%C4%B1n) TUI başlarken rastgele bir port ve hostname atanır. Bunun yerine `--hostname` ve `--port` [bayraklarını](https://opencode.ai/docs/cli) verebilirsiniz. [`/tui`](https://opencode.ai/docs/tr/server#tui) uç noktası sunucu üzerinden TUI’yi sürmek için kullanılabilir. Örneğin bir istemi önceden doldurabilir veya çalıştırabilirsiniz. Bu kurulum opencode [IDE](https://opencode.ai/docs/ide) eklentileri tarafından kullanılır. * * * [Spesifikasyon](https://opencode.ai/docs/tr/server#spesifikasyon) ------------------------------------------------------------------ Sunucu, şu adreste görülebilen bir OpenAPI 3.1 spesifikasyonu yayınlar: http://:/doc Örneğin `http://localhost:4096/doc`. İstemci oluşturmak, istek/yanit tiplerini incelemek veya Swagger gezgininde açmak için bu spec’i kullanın. * * * [API’ler](https://opencode.ai/docs/tr/server#apiler) ----------------------------------------------------- opencode sunucusu aşağıdaki API’leri sunar. * * * ### [Global](https://opencode.ai/docs/tr/server#global) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/global/health` | Sunucu sağlığını ve sürümünü al | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Küresel olayları al (SSE akışı) | Olay akışı | * * * ### [Proje](https://opencode.ai/docs/tr/server#proje) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/project` | Tüm projeleri listele | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Mevcut projeyi al | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Yol & VCS](https://opencode.ai/docs/tr/server#yol--vcs) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/path` | Mevcut yolu al | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Mevcut proje için VCS bilgisini al | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Örnek (Instance)](https://opencode.ai/docs/tr/server#%C3%B6rnek-instance) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Mevcut örneği (instance) kapat | `boolean` | * * * ### [Config](https://opencode.ai/docs/tr/server#config) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/config` | Yapılandırma bilgisini al | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Yapılandırmayı güncelle | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Sağlayıcıları ve varsayılan modelleri listele | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Sağlayıcı (Provider)](https://opencode.ai/docs/tr/server#sa%C4%9Flay%C4%B1c%C4%B1-provider) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/provider` | Tüm sağlayıcıları listele | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Sağlayıcı kimlik doğrulama yöntemlerini al | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | OAuth kullanarak bir sağlayıcıyı yetkilendir | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Bir sağlayıcı için OAuth geri çağrısını işle | `boolean` | * * * ### [Oturumlar (Sessions)](https://opencode.ai/docs/tr/server#oturumlar-sessions) | Yöntem | Yol | Açıklama | Notlar | | --- | --- | --- | --- | | `GET` | `/session` | Tüm oturumları listele | [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `POST` | `/session` | Yeni bir oturum oluştur | gövde: `{ parentID?, title? }`, [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `GET` | `/session/status` | Tüm oturumlar için durumu al | `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` döndürür | | `GET` | `/session/:id` | Oturum ayrıntılarını al | [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `DELETE` | `/session/:id` | Bir oturumu ve tüm verilerini sil | `boolean` döndürür | | `PATCH` | `/session/:id` | Oturum özelliklerini güncelle | gövde: `{ title? }`, [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `GET` | `/session/:id/children` | Bir oturumun alt oturumlarını al | [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `GET` | `/session/:id/todo` | Bir oturum için yapılacaklar listesini al | [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `POST` | `/session/:id/init` | Uygulamayı analiz et ve `AGENTS.md` oluştur | gövde: `{ messageID, providerID, modelID }`, `boolean` döndürür | | `POST` | `/session/:id/fork` | Mevcut bir oturumu bir mesajda çatalla | gövde: `{ messageID? }`, [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `POST` | `/session/:id/abort` | Çalışan bir oturumu iptal et | `boolean` döndürür | | `POST` | `/session/:id/share` | Bir oturumu paylaş | [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `DELETE` | `/session/:id/share` | Bir oturumun paylaşımını kaldır | [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `GET` | `/session/:id/diff` | Bu oturum için farkı (diff) al | sorgu: `messageID?`, [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
döndürür | | `POST` | `/session/:id/summarize` | Oturumu özetle | gövde: `{ providerID, modelID }`, `boolean` döndürür | | `POST` | `/session/:id/revert` | Bir mesajı geri al | gövde: `{ messageID, partID? }`, `boolean` döndürür | | `POST` | `/session/:id/unrevert` | Geri alınan tüm mesajları geri yükle | `boolean` döndürür | | `POST` | `/session/:id/permissions/:permissionID` | Bir izin isteğine yanıt ver | gövde: `{ response, remember? }`, `boolean` döndürür | * * * ### [Mesajlar](https://opencode.ai/docs/tr/server#mesajlar) | Yöntem | Yol | Açıklama | Notlar | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Bir oturumdaki mesajları listele | sorgu: `limit?`, `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` döndürür | | `POST` | `/session/:id/message` | Bir mesaj gönder ve yanıt bekle | gövde: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` döndürür | | `GET` | `/session/:id/message/:messageID` | Mesaj ayrıntılarını al | `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` döndürür | | `POST` | `/session/:id/prompt_async` | Eşzamansız bir mesaj gönder (bekleme yok) | gövde: `/session/:id/message` ile aynı, `204 No Content` döndürür | | `POST` | `/session/:id/command` | Bir eğik çizgi (slash) komutu çalıştır | gövde: `{ messageID?, agent?, model?, command, arguments }`, `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` döndürür | | `POST` | `/session/:id/shell` | Bir kabuk komutu çalıştır | gövde: `{ agent, model?, command }`, `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` döndürür | * * * ### [Komutlar](https://opencode.ai/docs/tr/server#komutlar) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/command` | Tüm komutları listele | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Dosyalar](https://opencode.ai/docs/tr/server#dosyalar) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Dosyalarda metin ara | `path`, `lines`, `line_number`, `absolute_offset`, `submatches` içeren eşleşme nesneleri dizisi | | `GET` | `/find/file?query=` | Dosya ve dizinleri isme göre bul | `string[]` (yollar) | | `GET` | `/find/symbol?query=` | Çalışma alanı sembollerini bul | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Dosya ve dizinleri listele | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Bir dosyayı oku | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | İzlenen dosyalar için durumu al | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` sorgu parametreleri](https://opencode.ai/docs/tr/server#findfile-sorgu-parametreleri) * `query` (gerekli) - arama metni (bulanık eşleşme) * `type` (isteğe bağlı) - sonuçları `"file"` veya `"directory"` ile sınırlama * `directory` (isteğe bağlı) - arama için proje kökünü geçersiz kılma * `limit` (isteğe bağlı) - en fazla sonuç (1-200) * `dirs` (isteğe bağlı) - eski bayrak (`"false"` sadece dosyaları döndürür) * * * ### [Araçlar (Deneysel)](https://opencode.ai/docs/tr/server#ara%C3%A7lar-deneysel) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Tüm araç kimliklerini listele | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Bir model için araçları JSON şemalarıyla listele | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, Biçimlendiriciler & MCP](https://opencode.ai/docs/tr/server#lsp-bi%C3%A7imlendiriciler--mcp) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/lsp` | LSP sunucu durumunu al | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Biçimlendirici durumunu al | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | MCP sunucu durumunu al | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Dinamik olarak MCP sunucusu ekle | gövde: `{ name, config }`, MCP durum nesnesi döndürür | * * * ### [Agent’lar](https://opencode.ai/docs/tr/server#agentlar) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/agent` | Tüm mevcut agent’ları listele | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Günlük (Logging)](https://opencode.ai/docs/tr/server#g%C3%BCnl%C3%BCk-logging) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `POST` | `/log` | Günlük girdisi yaz. Gövde: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/tr/server#tui) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | İsteme metin ekle | `boolean` | | `POST` | `/tui/open-help` | Yardım iletişim kutusunu aç | `boolean` | | `POST` | `/tui/open-sessions` | Oturum seçiciyi aç | `boolean` | | `POST` | `/tui/open-themes` | Tema seçiciyi aç | `boolean` | | `POST` | `/tui/open-models` | Model seçiciyi aç | `boolean` | | `POST` | `/tui/submit-prompt` | Mevcut istemi gönder | `boolean` | | `POST` | `/tui/clear-prompt` | İstemi temizle | `boolean` | | `POST` | `/tui/execute-command` | Bir komut çalıştır (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Toast bildirimi göster (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Bir sonraki kontrol isteğini bekle | Kontrol isteği nesnesi | | `POST` | `/tui/control/response` | Bir kontrol isteğine yanıt ver (`{ body }`) | `boolean` | * * * ### [Kimlik Doğrulama (Auth)](https://opencode.ai/docs/tr/server#kimlik-do%C4%9Frulama-auth) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Kimlik bilgilerini ayarla. Gövde sağlayıcı şemasıyla eşleşmelidir | `boolean` | * * * ### [Olaylar (Events)](https://opencode.ai/docs/tr/server#olaylar-events) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/event` | Sunucu tarafından gönderilen olay akışı (SSE). İlk olay `server.connected`, ardından veriyolu olayları | Sunucu tarafından gönderilen olay akışı | * * * ### [Dokümanlar (Docs)](https://opencode.ai/docs/tr/server#dok%C3%BCmanlar-docs) | Yöntem | Yol | Açıklama | Yanıt | | --- | --- | --- | --- | | `GET` | `/doc` | OpenAPI 3.1 spesifikasyonu | OpenAPI spec içeren HTML sayfası | --- # Servidor | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/server#_top) Servidor ======== Interaja com o servidor opencode via HTTP. O comando `opencode serve` executa um servidor HTTP sem cabeça que expõe um endpoint OpenAPI que um cliente opencode pode usar. * * * ### [Uso](https://opencode.ai/docs/pt-br/server#uso) opencode serve [--port ] [--hostname ] [--cors ] #### [Opções](https://opencode.ai/docs/pt-br/server#op%C3%A7%C3%B5es) | Flag | Descrição | Padrão | | --- | --- | --- | | `--port` | Porta para escutar | `4096` | | `--hostname` | Nome do host para escutar | `127.0.0.1` | | `--mdns` | Habilitar descoberta mDNS | `false` | | `--mdns-domain` | Nome de domínio personalizado para o serviço mDNS | `opencode.local` | | `--cors` | Origens adicionais de navegador a permitir | `[]` | `--cors` pode ser passado várias vezes: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Autenticação](https://opencode.ai/docs/pt-br/server#autentica%C3%A7%C3%A3o) Defina `OPENCODE_SERVER_PASSWORD` para proteger o servidor com autenticação básica HTTP. O nome de usuário padrão é `opencode`, ou defina `OPENCODE_SERVER_USERNAME` para substituí-lo. Isso se aplica tanto ao `opencode serve` quanto ao `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Como funciona](https://opencode.ai/docs/pt-br/server#como-funciona) Quando você executa `opencode`, ele inicia um TUI e um servidor. Onde o TUI é o cliente que se comunica com o servidor. O servidor expõe um endpoint de especificação OpenAPI 3.1. Este endpoint também é usado para gerar um [SDK](https://opencode.ai/docs/sdk) . Essa arquitetura permite que o opencode suporte múltiplos clientes e permite que você interaja com o opencode programaticamente. Você pode executar `opencode serve` para iniciar um servidor autônomo. Se você tiver o TUI do opencode em execução, `opencode serve` iniciará um novo servidor. * * * #### [Conectar a um servidor existente](https://opencode.ai/docs/pt-br/server#conectar-a-um-servidor-existente) Quando você inicia o TUI, ele atribui aleatoriamente uma porta e um nome de host. Você pode passar os [flags](https://opencode.ai/docs/cli) `--hostname` e `--port`. Em seguida, use isso para se conectar ao seu servidor. O endpoint [`/tui`](https://opencode.ai/docs/pt-br/server#tui) pode ser usado para controlar o TUI através do servidor. Por exemplo, você pode preencher ou executar um prompt. Essa configuração é usada pelos plugins do opencode [IDE](https://opencode.ai/docs/ide) . * * * [Especificação](https://opencode.ai/docs/pt-br/server#especifica%C3%A7%C3%A3o) ------------------------------------------------------------------------------- O servidor publica uma especificação OpenAPI 3.1 que pode ser visualizada em: http://:/doc Por exemplo, `http://localhost:4096/doc`. Use a especificação para gerar clientes ou inspecionar tipos de requisição e resposta. Ou visualize em um explorador Swagger. * * * [APIs](https://opencode.ai/docs/pt-br/server#apis) --------------------------------------------------- O servidor opencode expõe as seguintes APIs. * * * ### [Global](https://opencode.ai/docs/pt-br/server#global) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/global/health` | Obter saúde e versão do servidor | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Obter eventos globais (fluxo SSE) | Fluxo de eventos | * * * ### [Projeto](https://opencode.ai/docs/pt-br/server#projeto) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/project` | Listar todos os projetos | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Obter o projeto atual | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Caminho & VCS](https://opencode.ai/docs/pt-br/server#caminho--vcs) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/path` | Obter o caminho atual | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Obter informações do VCS para o projeto atual | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Instância](https://opencode.ai/docs/pt-br/server#inst%C3%A2ncia) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Descartar a instância atual | `boolean` | * * * ### [Configuração](https://opencode.ai/docs/pt-br/server#configura%C3%A7%C3%A3o) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/config` | Obter informações de configuração | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Atualizar configuração | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Listar provedores e modelos padrão | `{ providers:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Provedor](https://opencode.ai/docs/pt-br/server#provedor) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/provider` | Listar todos os provedores | `{ all:` [Provider\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Obter métodos de autenticação do provedor | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autorizar um provedor usando OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Lidar com o callback OAuth para um provedor | `boolean` | * * * ### [Sessões](https://opencode.ai/docs/pt-br/server#sess%C3%B5es) | Método | Caminho | Descrição | Notas | | --- | --- | --- | --- | | `GET` | `/session` | Listar todas as sessões | Retorna [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Criar uma nova sessão | corpo: `{ parentID?, title? }`, retorna [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Obter status da sessão para todas as sessões | Retorna `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Obter detalhes da sessão | Retorna [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Deletar uma sessão e todos os seus dados | Retorna `boolean` | | `PATCH` | `/session/:id` | Atualizar propriedades da sessão | corpo: `{ title? }`, retorna [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Obter as sessões filhas de uma sessão | Retorna [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Obter a lista de tarefas para uma sessão | Retorna [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Analisar o app e criar `AGENTS.md` | corpo: `{ messageID, providerID, modelID }`, retorna `boolean` | | `POST` | `/session/:id/fork` | Fazer um fork de uma sessão existente em uma mensagem | corpo: `{ messageID? }`, retorna [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Abortar uma sessão em execução | Retorna `boolean` | | `POST` | `/session/:id/share` | Compartilhar uma sessão | Retorna [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Descompartilhar uma sessão | Retorna [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Obter a diferença para esta sessão | query: `messageID?`, retorna [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Resumir a sessão | corpo: `{ providerID, modelID }`, retorna `boolean` | | `POST` | `/session/:id/revert` | Reverter uma mensagem | corpo: `{ messageID, partID? }`, retorna `boolean` | | `POST` | `/session/:id/unrevert` | Restaurar todas as mensagens revertidas | Retorna `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Responder a um pedido de permissão | corpo: `{ response, remember? }`, retorna `boolean` | * * * ### [Mensagens](https://opencode.ai/docs/pt-br/server#mensagens) | Método | Caminho | Descrição | Notas | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Listar mensagens em uma sessão | query: `limit?`, retorna `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Enviar uma mensagem e aguardar resposta | corpo: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, retorna `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Obter detalhes da mensagem | Retorna `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Enviar uma mensagem assíncrona (sem espera) | corpo: igual a `/session/:id/message`, retorna `204 No Content` | | `POST` | `/session/:id/command` | Executar um comando de barra | corpo: `{ messageID?, agent?, model?, command, arguments }`, retorna `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Executar um comando shell | corpo: `{ agent, model?, command }`, retorna `{ info:` [Message](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Part\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Comandos](https://opencode.ai/docs/pt-br/server#comandos) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/command` | Listar todos os comandos | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Arquivos](https://opencode.ai/docs/pt-br/server#arquivos) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Pesquisar texto em arquivos | Array de objetos de correspondência com `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Encontrar arquivos e diretórios por nome | `string[]` (caminhos) | | `GET` | `/find/symbol?query=` | Encontrar símbolos do workspace | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Listar arquivos e diretórios | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Ler um arquivo | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Obter status para arquivos rastreados | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [Parâmetros de consulta `/find/file`](https://opencode.ai/docs/pt-br/server#par%C3%A2metros-de-consulta-findfile) * `query` (obrigatório) — string de pesquisa (correspondência difusa) * `type` (opcional) — limitar resultados a `"file"` ou `"directory"` * `directory` (opcional) — substituir a raiz do projeto para a pesquisa * `limit` (opcional) — resultados máximos (1–200) * `dirs` (opcional) — flag legada (`"false"` retorna apenas arquivos) * * * ### [Ferramentas (Experimental)](https://opencode.ai/docs/pt-br/server#ferramentas-experimental) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Listar todos os IDs de ferramentas | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Listar ferramentas com esquemas JSON para um modelo | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, Formatadores & MCP](https://opencode.ai/docs/pt-br/server#lsp-formatadores--mcp) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/lsp` | Obter status do servidor LSP | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Obter status do formatador | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Obter status do servidor MCP | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Adicionar servidor MCP dinamicamente | corpo: `{ name, config }`, retorna objeto de status MCP | * * * ### [Agentes](https://opencode.ai/docs/pt-br/server#agentes) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/agent` | Listar todos os agentes disponíveis | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Registro](https://opencode.ai/docs/pt-br/server#registro) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `POST` | `/log` | Escrever entrada de log. Corpo: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/pt-br/server#tui) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Anexar texto ao prompt | `boolean` | | `POST` | `/tui/open-help` | Abrir o diálogo de ajuda | `boolean` | | `POST` | `/tui/open-sessions` | Abrir o seletor de sessões | `boolean` | | `POST` | `/tui/open-themes` | Abrir o seletor de temas | `boolean` | | `POST` | `/tui/open-models` | Abrir o seletor de modelos | `boolean` | | `POST` | `/tui/submit-prompt` | Enviar o prompt atual | `boolean` | | `POST` | `/tui/clear-prompt` | Limpar o prompt | `boolean` | | `POST` | `/tui/execute-command` | Executar um comando (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Mostrar toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Aguardar o próximo pedido de controle | Objeto de pedido de controle | | `POST` | `/tui/control/response` | Responder a um pedido de controle (`{ body }`) | `boolean` | * * * ### [Auth](https://opencode.ai/docs/pt-br/server#auth) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Definir credenciais de autenticação. O corpo deve corresponder ao esquema do provedor | `boolean` | * * * ### [Eventos](https://opencode.ai/docs/pt-br/server#eventos) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/event` | Fluxo de eventos enviados pelo servidor. O primeiro evento é `server.connected`, depois eventos de bus | Fluxo de eventos enviados pelo servidor | * * * ### [Docs](https://opencode.ai/docs/pt-br/server#docs) | Método | Caminho | Descrição | Resposta | | --- | --- | --- | --- | | `GET` | `/doc` | Especificação OpenAPI 3.1 | Página HTML com a especificação OpenAPI | --- # Serwer | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/server#_top) Serwer ====== Interakcja z serwerem opencode za pośrednictwem protokołu HTTP. Komenda `opencode serve` uruchamia bezgłowy serwer HTTP, który udostępnia punkt końcowy OpenAPI, z którego może korzystać klient opencode. * * * ### [Użycie](https://opencode.ai/docs/pl/server#u%C5%BCycie) opencode serve [--port ] [--hostname ] [--cors ] #### [Opcje](https://opencode.ai/docs/pl/server#opcje) | Flaga | Opis | Domyślne | | --- | --- | --- | | `--port` | Port nasłuchiwania | `4096` | | `--hostname` | Nazwa hosta do nasłuchiwania | `127.0.0.1` | | `--mdns` | Włącz wykrywanie mDNS | `false` | | `--mdns-domain` | Niestandardowa nazwa domeny dla usługi mDNS | `opencode.local` | | `--cors` | Dodatkowe originy przeglądarki do dozwolenia | `[]` | `--cors` można przekazać wiele razy: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [Uwierzytelnianie](https://opencode.ai/docs/pl/server#uwierzytelnianie) Ustaw `OPENCODE_SERVER_PASSWORD`, aby chronić serwer za pomocą podstawowego uwierzytelniania HTTP. Domyślną nazwą użytkownika jest `opencode` lub ustaw `OPENCODE_SERVER_USERNAME`, aby ją zastąpić. Dotyczy to zarówno `opencode serve`, jak i `opencode web`. OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [Jak to działa](https://opencode.ai/docs/pl/server#jak-to-dzia%C5%82a) Kiedy uruchomisz `opencode`, uruchomi się TUI i serwer. Gdzie jest TUI klient komunikujący się z serwerem. Serwer udostępnia specyfikację OpenAPI 3.1 punkt końcowy. Ten punkt końcowy jest również używany do generowania [SDK](https://opencode.ai/docs/sdk) . Ta architektura umożliwia obsługę wielu klientów przez opencode i programową interakcję z kodem otwartym. Możesz uruchomić `opencode serve`, aby uruchomić samodzielny serwer. Jeśli masz opencode TUI działa, `opencode serve` uruchomi nowy serwer. * * * #### [Połączenie z istniejącym serwerem](https://opencode.ai/docs/pl/server#po%C5%82%C4%85czenie-z-istniej%C4%85cym-serwerem) Po uruchomieniu TUI losowo przypisuje port i nazwę hosta. Zamiast tego możesz przekazać `--hostname` i `--port` [flagi](https://opencode.ai/docs/cli) . Następnie użyj tego, aby połączyć się z serwerem. Punktu końcowego [`/tui`](https://opencode.ai/docs/pl/server#TUI) można użyć do sterowania TUI przez serwer. Można na przykład wstępnie wypełnić lub uruchomić monit. Ta konfiguracja jest używana przez wtyczki opencode [IDE](https://opencode.ai/docs/ide) . * * * [Specyfikacja](https://opencode.ai/docs/pl/server#specyfikacja) ---------------------------------------------------------------- Serwer publikuje specyfikację OpenAPI 3.1, którą można obejrzeć pod adresem: http://:/doc Na przykład `http://localhost:4096/doc`. Użyj specyfikacji, aby wygenerować klientów lub sprawdzić typy żądań i odpowiedzi. Możesz też wyświetlić go w eksploratorze Swagger. * * * [API](https://opencode.ai/docs/pl/server#api) ---------------------------------------------- Serwer opencode udostępnia następujące interfejsy API. * * * ### [Globalne](https://opencode.ai/docs/pl/server#globalne) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/global/health` | Uzyskaj stan i wersję serwera | `{ healthy: true, version: string }` | | `GET` | `/global/event` | Get global events (SSE stream) | Event stream | * * * ### [Projekt](https://opencode.ai/docs/pl/server#projekt) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/project` | Lista wszystkich projektów | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | Pobierz bieżący projekt | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Ścieżka i VCS](https://opencode.ai/docs/pl/server#%C5%9Bcie%C5%BCka-i-vcs) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/path` | Pobierz bieżącą ścieżkę | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | Uzyskaj informacje VCS dla bieżącego projektu | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Instancja](https://opencode.ai/docs/pl/server#instancja) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | Usuń bieżącą instancję | `boolean` | * * * ### [Konfiguracja](https://opencode.ai/docs/pl/server#konfiguracja) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/config` | Get config info | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | Update config | [`Config`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | Lista dostawców i modeli domyślnych | `{ providers:` [Dostawca\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [Dostawca](https://opencode.ai/docs/pl/server#dostawca) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/provider` | Lista wszystkich dostawców | `{ all:` [Dostawca\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | Uzyskaj metody uwierzytelniania dostawcy | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | Autoryzuj dostawcę za pomocą protokołu OAuth | [`ProviderAuthAuthorization`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | Obsługa wywołania zwrotnego OAuth dla dostawcy | `boolean` | * * * ### [Sesje](https://opencode.ai/docs/pl/server#sesje) | Method | Path | Description | Notes | | --- | --- | --- | --- | | `GET` | `/session` | Lista wszystkich sesji | Zwraca [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | Utwórz nową sesję | treść: `{ parentID?, title? }`, zwraca [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | Uzyskaj status sesji dla wszystkich sesji | Zwraca `{ [sessionID: string]:` [Status sesji](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | Uzyskaj szczegóły sesji | Zwraca [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | Usuń sesję i wszystkie jej dane | Zwraca `boolean` | | `PATCH` | `/session/:id` | Aktualizuj właściwości sesji | treść: `{ title? }`, zwraca [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | Pobierz sesje podrzędne sesji | Zwraca [`Session[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | Pobierz listę rzeczy do zrobienia dla sesji | Zwraca [`Todo[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | Przeanalizuj aplikację i utwórz `AGENTS.md` | treść: `{ messageID, providerID, modelID }`, zwraca `boolean` | | `POST` | `/session/:id/fork` | Rozwiń istniejącą sesję w wiadomości | treść: `{ messageID? }`, zwraca [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | Przerwij trwającą sesję | Zwraca `boolean` | | `POST` | `/session/:id/share` | Udostępnij sesję | Zwraca [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | Anuluj udostępnianie sesji | Zwraca [`Session`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | Pobierz różnicę dla tej sesji | zapytanie: `messageID?`, zwraca [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | Podsumuj sesję | treść: `{ providerID, modelID }`, zwraca `boolean` | | `POST` | `/session/:id/revert` | Przywróć wiadomość | treść: `{ messageID, partID? }`, zwraca `boolean` | | `POST` | `/session/:id/unrevert` | Przywróć wszystkie przywrócone wiadomości | Zwraca `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | Odpowiedz na prośbę o pozwolenie | treść: `{ response, remember? }`, zwraca `boolean` | * * * ### [Wiadomości](https://opencode.ai/docs/pl/server#wiadomo%C5%9Bci) | Method | Path | Description | Notes | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | Lista wiadomości w sesji | zapytanie: `limit?`, zwraca `{ info:` [Wiadomość](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Część\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | Wyślij wiadomość i poczekaj na odpowiedź | treść: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }`, zwraca `{ info:` [Wiadomość](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Część\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | Uzyskaj szczegóły wiadomości | Zwraca `{ info:` [Wiadomość](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Część\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | Wyślij wiadomość asynchronicznie (bez czekania) | treść: taka sama jak `/session/:id/message`, zwraca `204 No Content` | | `POST` | `/session/:id/command` | Wykonaj slash command | treść: `{ messageID?, agent?, model?, command, arguments }`, zwraca `{ info:` [Wiadomość](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Część\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | Uruchom polecenie shell | treść: `{ agent, model?, command }`, zwraca `{ info:` [Wiadomość](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [Część\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [Polecenia](https://opencode.ai/docs/pl/server#polecenia) | Metoda | Ścieżka | Opis | Odpowiedź | | --- | --- | --- | --- | | `GET` | `/command` | Lista wszystkich poleceń | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Pliki](https://opencode.ai/docs/pl/server#pliki) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | Szukaj tekstu w plikach | Tablica obiektów dopasowania z `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | Znajdź pliki i katalogi według nazwy | `string[]` (ścieżki) | | `GET` | `/find/symbol?query=` | Find workspace symbols | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | Lista plików i katalogów | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | Read a file | [`FileContent`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | Uzyskaj status śledzonych plików | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` query parameters](https://opencode.ai/docs/pl/server#findfile-query-parameters) * `query` (required) — search string (fuzzy match) * `type` (optional) — limit results to `"file"` or `"directory"` * `directory` (opcjonalnie) — zastąp katalog główny projektu dla wyszukiwania * `limit` (optional) — max results (1–200) * `dirs` (optional) — legacy flag (`"false"` returns only files) * * * ### [Narzędzia (Eksperymentalne)](https://opencode.ai/docs/pl/server#narz%C4%99dzia-eksperymentalne) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | Lista wszystkich identyfikatorów narzędzi | [`ToolIDs`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | Lista narzędzi ze schematami JSON dla modelu | [`ToolList`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, Formatery i MCP](https://opencode.ai/docs/pl/server#lsp-formatery-i-mcp) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/lsp` | Uzyskaj status serwera LSP | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | Get formatter status | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | Uzyskaj status serwera MCP | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | Dodaj dynamicznie serwer MCP | treść: `{ name, config }`, zwraca obiekt stanu MCP | * * * ### [Agenci](https://opencode.ai/docs/pl/server#agenci) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/agent` | Lista wszystkich dostępnych agentów | [`Agent[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [Logowanie](https://opencode.ai/docs/pl/server#logowanie) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/pl/server#tui) | Method | Path | Description | Response | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | Dołącz tekst do promptu | `boolean` | | `POST` | `/tui/open-help` | Otwórz okno pomocy | `boolean` | | `POST` | `/tui/open-sessions` | Otwórz selektor sesji | `boolean` | | `POST` | `/tui/open-themes` | Otwórz selektor motywów | `boolean` | | `POST` | `/tui/open-models` | Otwórz selektor modelu | `boolean` | | `POST` | `/tui/submit-prompt` | Prześlij bieżący prompt | `boolean` | | `POST` | `/tui/clear-prompt` | Wyczyść prompt | `boolean` | | `POST` | `/tui/execute-command` | Wykonaj polecenie (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | Pokaż toast (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | Poczekaj na następne żądanie kontroli | Obiekt żądania kontroli | | `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | * * * ### [Uwierzytelnianie](https://opencode.ai/docs/pl/server#uwierzytelnianie-1) | Method | Path | Description | Response | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | Ustaw dane uwierzytelniające. Treść musi pasować do schematu dostawcy | `boolean` | * * * ### [Zdarzenia](https://opencode.ai/docs/pl/server#zdarzenia) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/event` | Strumień zdarzeń wysyłanych przez serwer. Pierwsze wydarzenie to `server.connected`, następnie wydarzenia autobusowe | Strumień zdarzeń wysłanych przez serwer | * * * ### [Dokumentacja](https://opencode.ai/docs/pl/server#dokumentacja) | Method | Path | Description | Response | | --- | --- | --- | --- | | `GET` | `/doc` | Specyfikacja OpenAPI 3.1 | Strona HTML ze specyfikacją OpenAPI | --- # フォーマッタ | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/formatters#_top) フォーマッタ ====== OpenCode は言語固有のフォーマッタを使用します。 OpenCode は、言語固有のフォーマッタを使用してファイルを作成または編集した後、ファイルを自動的にフォーマットします。これにより、生成されるコードがプロジェクトのコードスタイルに従っていることが保証されます。 * * * [組み込み](https://opencode.ai/docs/ja/formatters#%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF) ------------------------------------------------------------------------------------ OpenCode には、一般的な言語およびフレームワーク用のいくつかの組み込みフォーマッタが付属しています。以下は、フォーマッタ、サポートされているファイル拡張子、および必要なコマンドまたは構成オプションのリストです。 | Formatter | Extensions | Requirements | | --- | --- | --- | | air | .R | `air` command available | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://biomejs.dev/) | `biome.json(c)` config file | | cargofmt | .rs | `cargo fmt` command available | | clang-format | .c, .cpp, .h, .hpp, .ino, and [more](https://clang.llvm.org/docs/ClangFormat.html) | `.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](https://opencode.ai/docs/cli/#experimental) | | pint | .php | `laravel/pint` dependency in `composer.json` | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://prettier.io/docs/en/index.html) | `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 | したがって、プロジェクトの `prettier` に `package.json` が含まれている場合、OpenCode は自動的にそれを使用します。 * * * [仕組み](https://opencode.ai/docs/ja/formatters#%E4%BB%95%E7%B5%84%E3%81%BF) -------------------------------------------------------------------------- OpenCode がファイルを書き込んだり編集したりすると、次のことが行われます。 1. 有効なすべてのフォーマッタに対してファイル拡張子をチェックします。 2. ファイルに対して適切なフォーマッタコマンドを実行します。 3. 書式の変更を自動的に適用します。 このプロセスはバックグラウンドで実行されるため、手動の手順を行わなくてもコードスタイルが維持されます。 * * * [設定](https://opencode.ai/docs/ja/formatters#%E8%A8%AD%E5%AE%9A) ---------------------------------------------------------------- OpenCode 設定の `formatter` セクションを通じてフォーマッタをカスタマイズできます。 { "$schema": "https://opencode.ai/config.json", "formatter": {}} 各フォーマッタ設定は以下をサポートします。 | プロパティ | タイプ | 説明 | | --- | --- | --- | | `disabled` | ブール値 | フォーマッタを無効にするには、これを `true` に設定します。 | | `command` | 文字列\[\] | フォーマットのために実行するコマンド | | `environment` | オブジェクト | フォーマッタの実行時に設定する環境変数 | | `extensions` | 文字列\[\] | このフォーマッタが処理するファイル拡張子 | いくつかの例を見てみましょう。 * * * ### [フォーマッタの無効化](https://opencode.ai/docs/ja/formatters#%E3%83%95%E3%82%A9%E3%83%BC%E3%83%9E%E3%83%83%E3%82%BF%E3%81%AE%E7%84%A1%E5%8A%B9%E5%8C%96) **すべて**のフォーマッタをグローバルに無効にするには、`formatter` を `false` に設定します。 { "$schema": "https://opencode.ai/config.json", "formatter": false} **特定**のフォーマッタを無効にするには、`disabled` を `true` に設定します。 { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [カスタムフォーマッタ](https://opencode.ai/docs/ja/formatters#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%95%E3%82%A9%E3%83%BC%E3%83%9E%E3%83%83%E3%82%BF) コマンド、環境変数、ファイル拡張子を指定することで、組み込みフォーマッタをオーバーライドしたり、新しいフォーマッタを追加したりできます。 { "$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"] } }} コマンド内の **`$FILE` プレースホルダー** は、フォーマットされるファイルへのパスに置き換えられます。 --- # المُنسِّقات | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/formatters#_top) المُنسِّقات =========== يستخدم OpenCode مُنسِّقات خاصة بكل لغة. يُنسِّق OpenCode الملفات تلقائيا بعد كتابتها أو تعديلها باستخدام مُنسِّقات خاصة بكل لغة. يضمن ذلك أن الشيفرة التي يتم توليدها تتبع أساليب التنسيق المعتمدة في مشروعك. * * * [مُضمَّنة](https://opencode.ai/docs/ar/formatters#%D9%85%D9%8F%D8%B6%D9%85%D9%91%D9%8E%D9%86%D8%A9) ---------------------------------------------------------------------------------------------------- يأتي OpenCode مع عدة مُنسِّقات مُضمَّنة للغات وأطر العمل الشائعة. فيما يلي قائمة بالمُنسِّقات وامتدادات الملفات المدعومة والأوامر أو خيارات الإعداد التي تحتاجها. | المُنسِّق | الامتدادات | المتطلبات | | --- | --- | --- | | gofmt | .go | يتوفر أمر `gofmt` | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | يتوفر أمر `mix` | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml، و[غير ذلك](https://prettier.io/docs/en/index.html) | وجود اعتماد `prettier` في `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml، و[غير ذلك](https://biomejs.dev/) | ملف إعداد `biome.json(c)` | | zig | .zig, .zon | يتوفر أمر `zig` | | clang-format | .c, .cpp, .h, .hpp, .ino، و[غير ذلك](https://clang.llvm.org/docs/ClangFormat.html) | ملف إعداد `.clang-format` | | ktlint | .kt, .kts | يتوفر أمر `ktlint` | | ruff | .py, .pyi | يتوفر أمر `ruff` مع إعداد | | rustfmt | .rs | يتوفر أمر `rustfmt` | | cargofmt | .rs | يتوفر أمر `cargo fmt` | | uv | .py, .pyi | يتوفر أمر `uv` | | rubocop | .rb, .rake, .gemspec, .ru | يتوفر أمر `rubocop` | | standardrb | .rb, .rake, .gemspec, .ru | يتوفر أمر `standardrb` | | htmlbeautifier | .erb, .html.erb | يتوفر أمر `htmlbeautifier` | | air | .R | يتوفر أمر `air` | | dart | .dart | يتوفر أمر `dart` | | dfmt | .d | يتوفر أمر `dfmt` | | ocamlformat | .ml, .mli | يتوفر أمر `ocamlformat` وملف إعداد `.ocamlformat` | | terraform | .tf, .tfvars | يتوفر أمر `terraform` | | gleam | .gleam | يتوفر أمر `gleam` | | nixfmt | .nix | يتوفر أمر `nixfmt` | | shfmt | .sh, .bash | يتوفر أمر `shfmt` | | pint | .php | وجود اعتماد `laravel/pint` في `composer.json` | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | وجود اعتماد `oxfmt` في `package.json` و[علم متغير بيئة تجريبي](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | يتوفر أمر `ormolu` | لذا إذا كان مشروعك يتضمن `prettier` ضمن `package.json`، فسيستخدمه OpenCode تلقائيا. * * * [كيف يعمل](https://opencode.ai/docs/ar/formatters#%D9%83%D9%8A%D9%81-%D9%8A%D8%B9%D9%85%D9%84) ----------------------------------------------------------------------------------------------- عندما يكتب OpenCode ملفا أو يحرره، فإنه: 1. يتحقق من امتداد الملف مقابل جميع المُنسِّقات المفعّلة. 2. يشغّل أمر المُنسِّق المناسب على الملف. 3. يطبق تغييرات التنسيق تلقائيا. تتم هذه العملية في الخلفية لضمان الحفاظ على أساليب تنسيق الشيفرة دون أي خطوات يدوية. * * * [الإعداد](https://opencode.ai/docs/ar/formatters#%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF) --------------------------------------------------------------------------------------------- يمكنك تخصيص المُنسِّقات عبر قسم `formatter` في إعدادات OpenCode. { "$schema": "https://opencode.ai/config.json", "formatter": {}} يدعم إعداد كل مُنسِّق ما يلي: | الخاصية | النوع | الوصف | | --- | --- | --- | | `disabled` | boolean | اضبطها على `true` لتعطيل المُنسِّق | | `command` | string\[\] | الأمر الذي سيتم تشغيله للتنسيق | | `environment` | object | متغيرات البيئة التي يتم ضبطها عند تشغيل المُنسِّق | | `extensions` | string\[\] | امتدادات الملفات التي يجب أن يتعامل معها هذا المُنسِّق | لنلقِ نظرة على بعض الأمثلة. * * * ### [تعطيل المُنسِّقات](https://opencode.ai/docs/ar/formatters#%D8%AA%D8%B9%D8%B7%D9%8A%D9%84-%D8%A7%D9%84%D9%85%D9%8F%D9%86%D8%B3%D9%91%D9%90%D9%82%D8%A7%D8%AA) لتعطيل **جميع** المُنسِّقات على مستوى عام، اضبط `formatter` على `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} لتعطيل مُنسِّق **محدد**، اضبط `disabled` على `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [مُنسِّقات مخصّصة](https://opencode.ai/docs/ar/formatters#%D9%85%D9%8F%D9%86%D8%B3%D9%91%D9%90%D9%82%D8%A7%D8%AA-%D9%85%D8%AE%D8%B5%D9%91%D8%B5%D8%A9) يمكنك تجاوز المُنسِّقات المُضمَّنة أو إضافة مُنسِّقات جديدة عبر تحديد الأمر ومتغيرات البيئة وامتدادات الملفات: { "$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"] } }} سيتم استبدال **العنصر النائب `$FILE`** في الأمر بمسار الملف الذي يجري تنسيقه. --- # Konfiguracja | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/config#_top) Konfiguracja ============ Ustawienia OpenCode w pliku JSON. Możesz dostosować OpenCode za pomocą pliku konfiguracyjnego JSON. * * * [Format](https://opencode.ai/docs/pl/config#format) ---------------------------------------------------- OpenCode obsługuje formaty **JSON** i **JSONC** (JSON z komentarzami). { "$schema": "https://opencode.ai/config.json", // Theme configuration "theme": "opencode", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true,} * * * [Lokalizacje](https://opencode.ai/docs/pl/config#lokalizacje) -------------------------------------------------------------- Możesz umieścić swoją konfigurację w kilku różnych lokalizacjach, które mają ustaloną kolejność pierwszeństwa. Pliki konfiguracyjne są łączone ze sobą. Ustawienia z lokalizacji o wyższym priorytecie nadpisują ustawienia z lokalizacji o niższym priorytecie tylko w przypadku konfliktów kluczy. Ustawienia niekolidujące ze wszystkich źródeł są zachowywane. Na przykład, jeśli konfiguracja globalna ustawi `theme: "opencode"` i `autoupdate: true`, a konfiguracja projektu ustawi `model: "anthropic/claude-sonnet-4-5"`, ostateczna konfiguracja będzie zawierać wszystkie trzy ustawienia. * * * ### [Kolejność pierwszeństwa](https://opencode.ai/docs/pl/config#kolejno%C5%9B%C4%87-pierwsze%C5%84stwa) Źródła konfiguracji są ładowane w następującej kolejności (źródła występujące później mają pierwszeństwo): 1. **Konfiguracja zdalna** (z `.well-known/opencode`) – ustawienia wymuszane przez organizację 2. **Konfiguracja globalna** (`~/.config/opencode/opencode.json`) – preferencje użytkownika 3. **Konfiguracja niestandardowa** (zmienna `OPENCODE_CONFIG`) — jawne nadpisanie 4. **Konfiguracja projektu** (`opencode.json` w projekcie) - ustawienia specyficzne dla projektu 5. **Katalogi `.opencode`** - agenci, polecenia, umiejętności 6. **Konfiguracja wbudowana** (zmienna `OPENCODE_CONFIG_CONTENT`) — nadpisanie środowiska uruchomieniowego Oznacza to, że konfiguracje projektu mogą nadpisywać konfiguracje globalne, a konfiguracje globalne mogą nadpisywać konfiguracje zdalne. * * * ### [Zdalna](https://opencode.ai/docs/pl/config#zdalna) Organizacje mogą publikować konfigurację pod adresem `.well-known/opencode`. Jest ona pobierana automatycznie po uwierzytelnieniu u dostawcy, który ją obsługuje. Konfiguracja zdalna jest ładowana jako pierwsza i stanowi bazę. Wszystkie inne źródła konfiguracji (globalne, projektowe) mogą ją nadpisywać. Na przykład, jeśli Twoja organizacja udostępnia serwery MCP, które są domyślnie wyłączone: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Możesz włączyć serwer w konfiguracji projektu: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Globalna](https://opencode.ai/docs/pl/config#globalna) Umieść swoją globalną konfigurację OpenCode w `~/.config/opencode/opencode.json`. Użyj jej do ustawień ogólnych dla użytkownika, takich jak dostawcy, modele i uprawnienia. Dla ustawień specyficznych dla TUI, użyj `~/.config/opencode/tui.json`. Konfiguracja globalna ma pierwszeństwo przed konfiguracją zdalną. * * * ### [Projekt](https://opencode.ai/docs/pl/config#projekt) Dodaj `opencode.json` w katalogu głównym projektu. Konfiguracja projektu ma najwyższy priorytet wśród plików konfiguracyjnych — nadpisuje konfiguracje globalne i zdalne. Dla ustawień TUI specyficznych dla projektu, dodaj plik `tui.json` obok niego. Kiedy OpenCode się uruchamia, szuka pliku konfiguracyjnego w katalogu głównym repozytorium Git. Może on być przechowywany w Git i mieć ten sam schemat, co konfiguracja globalna. * * * ### [Niestandardowa ścieżka](https://opencode.ai/docs/pl/config#niestandardowa-%C5%9Bcie%C5%BCka) Możesz załadować niestandardowy plik konfiguracyjny, ustawiając zmienną środowiskową `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Konfiguracja niestandardowa jest ładowana po konfiguracji globalnej i przed konfiguracją projektu w kolejności priorytetów. * * * ### [Niestandardowy katalog](https://opencode.ai/docs/pl/config#niestandardowy-katalog) Możesz ustawić niestandardowy katalog konfiguracyjny za pomocą zmiennej środowiskowej `OPENCODE_CONFIG_DIR`. Katalog ten będzie przeszukiwany pod kątem agentów, poleceń, trybów i wtyczek, tak jak standardowy katalog `.opencode` i powinien zachować tę samą strukturę. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" Katalog niestandardowy jest ładowany po globalnej konfiguracji i katalogach `.opencode`, więc **może być łączony** z ich zawartością. * * * [Schemat](https://opencode.ai/docs/pl/config#schemat) ------------------------------------------------------ Plik konfiguracyjny ma schemat JSON dostępny pod adresem [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . Twój edytor powinien zapewniać walidację i autouzupełnianie na podstawie tego schematu. * * * ### [TUI](https://opencode.ai/docs/pl/config#tui) Użyj dedykowanego pliku `tui.json` (lub `tui.jsonc`) dla ustawień specyficznych dla TUI. { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Użyj `OPENCODE_TUI_CONFIG`, aby wskazać niestandardowy plik konfiguracyjny TUI. Przestarzałe klucze `theme`, `keybinds` i `tui` w `opencode.json` są wycofywane i automatycznie migrowane, gdy to możliwe. [Dowiedz się więcej o konfiguracji TUI tutaj](https://opencode.ai/docs/tui#configure) . * * * ### [Server (Serwer)](https://opencode.ai/docs/pl/config#server-serwer) Możesz skonfigurować serwer dla `opencode serve` i `opencode web` za pomocą opcji `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Dostępne opcje: * `port` - Port do nasłuchiwania. * `hostname` — Nazwa hosta, z którą należy się powiązać. Gdy `mdns` jest włączone i nie ustawiono innej nazwy hosta, domyślnie jest to `0.0.0.0`. * `mdns` - Włącz wykrywanie usług mDNS. Dzięki temu inne urządzenia w sieci mogą łatwo znaleźć Twój serwer OpenCode. * `mdnsDomain` - Niestandardowa nazwa domeny dla usług mDNS. Domyślnie `opencode.local`. Przydatne do uruchamiania wielu instancji w tej samej sieci. * `cors` - Dozwolone źródła CORS podczas korzystania z serwera HTTP z przeglądarki. Wartość musi być listą źródeł (schemat + host + opcjonalny port), np. `https://app.example.com`. [Dowiedz się więcej o serwerze](https://opencode.ai/docs/server) . * * * ### [Tools (Narzędzia)](https://opencode.ai/docs/pl/config#tools-narz%C4%99dzia) Kontroluj, które narzędzia są dostępne dla LLM, za pomocą opcji `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Dowiedz się więcej o narzędziach](https://opencode.ai/docs/tools) . * * * ### [Models (Modele)](https://opencode.ai/docs/pl/config#models-modele) Możesz skonfigurować dostawców i modele, których chcesz używać, za pomocą opcji `provider`, `model` i `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} Opcja `small_model` konfiguruje oddzielny model do lżejszych zadań, takich jak generowanie tytułów. Domyślnie OpenCode wybiera tańszy model od tego samego dostawcy, jeśli jest dostępny, w przeciwnym razie powraca do modelu głównego. Opcje dostawcy mogą zawierać `timeout` i `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Limit czasu żądania w milisekundach (domyślnie: 300000). Ustaw na `false`, aby wyłączyć. * `setCacheKey` — Wymuś ustawienie klucza pamięci podręcznej dla dostawcy. Możesz także skonfigurować [modele lokalne](https://opencode.ai/docs/models#local) . [Dowiedz się więcej o modelach](https://opencode.ai/docs/models) . * * * #### [Opcje specyficzne dla dostawców](https://opencode.ai/docs/pl/config#opcje-specyficzne-dla-dostawc%C3%B3w) Niektórzy dostawcy obsługują dodatkowe opcje konfiguracji poza `timeout` i `apiKey`. ##### [Amazon Bedrock](https://opencode.ai/docs/pl/config#amazon-bedrock) Amazon Bedrock umożliwia konfigurację połączenia z AWS: { "$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` — Region AWS dla Bedrock (domyślnie `AWS_REGION` env var lub `us-east-1`) * `profile` - Nazwa profilu AWS z `~/.aws/credentials` (domyślnie `AWS_PROFILE` env var) * `endpoint` — Niestandardowy adres URL punktu końcowego (np. dla punktów końcowych VPC). Jest to alias dla opcji ogólnej `baseURL` przy użyciu terminologii AWS. Jeśli podano oba, pierwszeństwo ma `endpoint`. [Dowiedz się więcej o Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Theme (Motyw)](https://opencode.ai/docs/pl/config#theme-motyw) Ustaw motyw interfejsu użytkownika w `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [Dowiedz się więcej tutaj](https://opencode.ai/docs/themes) . * * * ### [Agents (Agenci)](https://opencode.ai/docs/pl/config#agents-agenci) Możesz zdefiniować i skonfigurować agentów za pomocą opcji `agent`. { "$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, }, }, },} Możesz także definiować agentów przy użyciu plików markdown w `~/.config/opencode/agents/` lub `.opencode/agents/`. [Dowiedz się więcej o agentach](https://opencode.ai/docs/agents) . * * * ### [Default Agent (Domyślny agent)](https://opencode.ai/docs/pl/config#default-agent-domy%C5%9Blny-agent) Domyślnego agenta można ustawić za pomocą opcji `default_agent`. Określa to agenta, który jest używany, jeśli nie wybrano żadnego innego. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} Agent domyślny musi być agentem typu `primary` (nie `subagent`). Może to być agent wbudowany, taki jak `"build"` lub `"plan"`, albo zdefiniowany przez Ciebie [agent niestandardowy](https://opencode.ai/docs/agents) . Jeśli agent nie istnieje lub jest subagentem, OpenCode powróci do `"build"` z ostrzeżeniem. Dotyczy to wszystkich interfejsów: TUI, CLI (`opencode run`), aplikacji desktopowej i GitHub Actions. * * * ### [Share (Udostępnianie)](https://opencode.ai/docs/pl/config#share-udost%C4%99pnianie) Możesz skonfigurować [udostępnianie](https://opencode.ai/docs/share) za pomocą opcji `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Opcje: * `"manual"` – Zezwalaj na ręczne udostępnianie (domyślnie) * `"auto"` - Automatycznie udostępniaj nowe rozmowy * `"disabled"` - Całkowicie wyłącz udostępnianie Domyślnie ustawiony jest tryb ręczny, w którym należy jawnie udostępniać rozmowy za pomocą polecenia `/share`. * * * ### [Commands (Polecenia)](https://opencode.ai/docs/pl/config#commands-polecenia) Możesz zdefiniować niestandardowe polecenia dla powtarzalnych zadań za pomocą opcji `command`. { "$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", }, },} Możesz także definiować polecenia przy użyciu plików Markdown w `~/.config/opencode/commands/` lub `.opencode/commands/`. [Dowiedz się więcej o poleceniach](https://opencode.ai/docs/commands) . * * * ### [Keybinds (Skróty klawiszowe)](https://opencode.ai/docs/pl/config#keybinds-skr%C3%B3ty-klawiszowe) Dostosuj skróty klawiszowe w `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [Dowiedz się więcej tutaj](https://opencode.ai/docs/keybinds) . * * * ### [Autoupdate (Automatyczna aktualizacja)](https://opencode.ai/docs/pl/config#autoupdate-automatyczna-aktualizacja) OpenCode może automatycznie pobierać nowe wersje. Możesz to kontrolować za pomocą opcji `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Jeśli nie chcesz automatycznych aktualizacji, ale chcesz być powiadamiany o nowych wersjach, ustaw `autoupdate` na `"notify"`. Działa to tylko wtedy, gdy OpenCode nie został zainstalowany przez menedżera pakietów, takiego jak Homebrew. * * * ### [Formatters (Formatery)](https://opencode.ai/docs/pl/config#formatters-formatery) Możesz skonfigurować formatery kodu za pomocą opcji `formatter`. { "$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"] } }} [Dowiedz się więcej o formaterach](https://opencode.ai/docs/formatters) . * * * ### [Permissions (Uprawnienia)](https://opencode.ai/docs/pl/config#permissions-uprawnienia) Domyślnie OpenCode **zezwala na wszystkie działania** bez konieczności zatwierdzania. Możesz to zmienić za pomocą opcji `permission`. Na przykład, aby wymagać zatwierdzenia dla narzędzi `edit` i `bash`: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Dowiedz się więcej o uprawnieniach](https://opencode.ai/docs/permissions) . * * * ### [Compaction (Kompaktowanie)](https://opencode.ai/docs/pl/config#compaction-kompaktowanie) Możesz kontrolować zachowanie kompaktowania kontekstu za pomocą opcji `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true }} * `auto` - Automatycznie kompaktuj, gdy kontekst jest pełny (domyślnie: `true`). * `prune` - Usuń stare wyniki narzędzi, aby zaoszczędzić tokeny (domyślnie: `true`). * * * ### [Watcher (Obserwator)](https://opencode.ai/docs/pl/config#watcher-obserwator) Skonfiguruj ignorowane wzorce plików dla obserwatora plików za pomocą `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Wzorce są zgodne ze składnią glob. Użyj tej opcji, aby wykluczyć często zmieniające się lub duże katalogi z monitorowania. * * * ### [MCP Servers (Serwery MCP)](https://opencode.ai/docs/pl/config#mcp-servers-serwery-mcp) Skonfiguruj serwery MCP, których chcesz używać, za pomocą opcji `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Dowiedz się więcej o serwerach MCP](https://opencode.ai/docs/mcp-servers) . * * * ### [Plugins (Wtyczki)](https://opencode.ai/docs/pl/config#plugins-wtyczki) [Wtyczki](https://opencode.ai/docs/plugins) rozszerzają OpenCode o niestandardowe narzędzia, hooki i integracje. Umieść pliki wtyczek w `.opencode/plugins/` lub `~/.config/opencode/plugins/`. Możesz także załadować wtyczkę z npm za pomocą opcji `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Dowiedz się więcej o wtyczkach](https://opencode.ai/docs/plugins) . * * * ### [Instructions (Instrukcje)](https://opencode.ai/docs/pl/config#instructions-instrukcje) Określ pliki instrukcji dla modelu, używając opcji `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Załadowane pliki są dołączane do promptu systemowego. Obsługuje wzorce glob. [Dowiedz się więcej o zasadach](https://opencode.ai/docs/rules) . * * * ### [Disabled Providers (Wyłączeni dostawcy)](https://opencode.ai/docs/pl/config#disabled-providers-wy%C5%82%C4%85czeni-dostawcy) Zapobiegaj automatycznemu ładowaniu dostawców za pomocą opcji `disabled_providers`. Jest to przydatne, gdy chcesz wyłączyć niektórych dostawców, nawet jeśli masz dla nich dane uwierzytelniające. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} Opcja `disabled_providers` przyjmuje tablicę identyfikatorów dostawców. Gdy dostawca jest wyłączony: * Nie zostanie załadowany podczas startu. * Nie zostanie załadowany, nawet jeśli podasz klucz API za pomocą `/connect`. * Modele tego dostawcy nie pojawią się na liście wyboru modeli. * * * ### [Enabled Providers (Włączeni dostawcy)](https://opencode.ai/docs/pl/config#enabled-providers-w%C5%82%C4%85czeni-dostawcy) Możesz określić listę dozwolonych dostawców za pomocą `enabled_providers`. Po ustawieniu, tylko wymienieni dostawcy będą ładowani. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Jest to przydatne, gdy chcesz ograniczyć użycie OpenCode tylko do określonych dostawców. Jeśli dostawca jest wymieniony zarówno w `enabled_providers`, jak i `disabled_providers`, `disabled_providers` wygrywa. * * * ### [Experimental (Eksperymentalne)](https://opencode.ai/docs/pl/config#experimental-eksperymentalne) Klucz `experimental` zawiera opcje, które są we wczesnej fazie rozwoju. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Zmienne](https://opencode.ai/docs/pl/config#zmienne) ------------------------------------------------------ Możesz używać specjalnej składni w plikach konfiguracyjnych, aby odwoływać się do zmiennych środowiskowych i zawartości plików. * * * ### [Env vars (Zmienne środowiskowe)](https://opencode.ai/docs/pl/config#env-vars-zmienne-%C5%9Brodowiskowe) Użyj `{env:VARIABLE_NAME}`, aby wstawić wartość zmiennej środowiskowej: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Jeśli zmienna środowiskowa nie jest ustawiona, zostanie zastąpiona pustym ciągiem. * * * ### [Files (Pliki)](https://opencode.ai/docs/pl/config#files-pliki) Użyj `{file:path/to/file}`, aby wstawić zawartość pliku: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Ścieżki plików mogą być: * Względne do pliku konfiguracyjnego * Lub absolutne, zaczynające się od `/` lub `~` Zalecamy używanie tego do: * Przechowywania wrażliwych danych, takich jak klucze API, w oddzielnych plikach. * Ładowania dużych promptów bez zaśmiecania konfiguracji. * Dzielenia fragmentów konfiguracji między wieloma plikami. --- # Formatadores | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/formatters#_top) Formatadores ============ O opencode usa formatadores específicos de linguagem. O opencode formata automaticamente arquivos após serem escritos ou editados usando formatadores específicos de linguagem. Isso garante que o código gerado siga os estilos de código do seu projeto. * * * [Integrados](https://opencode.ai/docs/pt-br/formatters#integrados) ------------------------------------------------------------------- O opencode vem com vários formatadores integrados para linguagens e frameworks populares. Abaixo está uma lista dos formatadores, extensões de arquivo suportadas e comandos ou opções de configuração necessárias. | Formatador | Extensões | Requisitos | | --- | --- | --- | | gofmt | .go | Comando `gofmt` disponível | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | Comando `mix` disponível | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, e [mais](https://prettier.io/docs/en/index.html) | Dependência `prettier` em `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, e [mais](https://biomejs.dev/) | Arquivo de configuração `biome.json(c)` | | zig | .zig, .zon | Comando `zig` disponível | | clang-format | .c, .cpp, .h, .hpp, .ino, e [mais](https://clang.llvm.org/docs/ClangFormat.html) | Arquivo de configuração `.clang-format` | | ktlint | .kt, .kts | Comando `ktlint` disponível | | ruff | .py, .pyi | Comando `ruff` disponível com configuração | | rustfmt | .rs | Comando `rustfmt` disponível | | cargofmt | .rs | Comando `cargo fmt` disponível | | uv | .py, .pyi | Comando `uv` disponível | | rubocop | .rb, .rake, .gemspec, .ru | Comando `rubocop` disponível | | standardrb | .rb, .rake, .gemspec, .ru | Comando `standardrb` disponível | | htmlbeautifier | .erb, .html.erb | Comando `htmlbeautifier` disponível | | air | .R | Comando `air` disponível | | dart | .dart | Comando `dart` disponível | | dfmt | .d | Comando `dfmt` disponível | | ocamlformat | .ml, .mli | Comando `ocamlformat` disponível e arquivo de configuração `.ocamlformat` | | terraform | .tf, .tfvars | Comando `terraform` disponível | | gleam | .gleam | Comando `gleam` disponível | | nixfmt | .nix | Comando `nixfmt` disponível | | shfmt | .sh, .bash | Comando `shfmt` disponível | | pint | .php | Dependência `laravel/pint` em `composer.json` | | oxfmt (Experimental) | .js, .jsx, .ts, .tsx | Dependência `oxfmt` em `package.json` e uma [variável de ambiente experimental](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | Comando `ormolu` disponível | Portanto, se seu projeto tiver `prettier` em seu `package.json`, o opencode o usará automaticamente. * * * [Como funciona](https://opencode.ai/docs/pt-br/formatters#como-funciona) ------------------------------------------------------------------------- Quando o opencode escreve ou edita um arquivo, ele: 1. Verifica a extensão do arquivo em relação a todos os formatadores habilitados. 2. Executa o comando do formatador apropriado no arquivo. 3. Aplica as alterações de formatação automaticamente. Esse processo acontece em segundo plano, garantindo que seus estilos de código sejam mantidos sem etapas manuais. * * * [Configuração](https://opencode.ai/docs/pt-br/formatters#configura%C3%A7%C3%A3o) --------------------------------------------------------------------------------- Você pode personalizar os formatadores através da seção `formatter` em sua configuração do opencode. { "$schema": "https://opencode.ai/config.json", "formatter": {}} Cada configuração de formatador suporta o seguinte: | Propriedade | Tipo | Descrição | | --- | --- | --- | | `disabled` | boolean | Defina como `true` para desabilitar o formatador | | `command` | string\[\] | O comando a ser executado para formatação | | `environment` | object | Variáveis de ambiente a serem definidas ao executar o formatador | | `extensions` | string\[\] | Extensões de arquivo que este formatador deve tratar | Vamos ver alguns exemplos. * * * ### [Desabilitando formatadores](https://opencode.ai/docs/pt-br/formatters#desabilitando-formatadores) Para desabilitar **todos** os formatadores globalmente, defina `formatter` como `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} Para desabilitar um **formatador específico**, defina `disabled` como `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [Formatadores personalizados](https://opencode.ai/docs/pt-br/formatters#formatadores-personalizados) Você pode substituir os formatadores integrados ou adicionar novos especificando o comando, variáveis de ambiente e extensões de arquivo: { "$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"] } }} O **placeholder `$FILE`** no comando será substituído pelo caminho do arquivo que está sendo formatado. --- # ฟอร์แมตเตอร์ | OpenCode [Skip to content](https://opencode.ai/docs/th/formatters#_top) ฟอร์แมตเตอร์ ============ OpenCode ใช้ตัวจัดรูปแบบเฉพาะภาษา OpenCode จะจัดรูปแบบไฟล์โดยอัตโนมัติหลังจากที่เขียนหรือแก้ไขโดยใช้ตัวจัดรูปแบบเฉพาะภาษา เพื่อให้แน่ใจว่าโค้ดที่สร้างขึ้นเป็นไปตามสไตล์โค้ดของโปรเจ็กต์ของคุณ * * * [บิวท์อิน](https://opencode.ai/docs/th/formatters#%E0%B8%9A%E0%B8%B4%E0%B8%A7%E0%B8%97%E0%B9%8C%E0%B8%AD%E0%B8%B4%E0%B8%99) ---------------------------------------------------------------------------------------------------------------------------- OpenCode มาพร้อมกับฟอร์แมตเตอร์ในตัวหลายตัวสำหรับภาษาและเฟรมเวิร์กยอดนิยม ด้านล่างนี้คือรายการฟอร์แมตเตอร์ นามสกุลไฟล์ที่รองรับ และคำสั่งหรือตัวเลือกการกำหนดค่าที่ต้องการ | ฟอร์แมตเตอร์ | ส่วนขยาย | ความต้องการ | | --- | --- | --- | | gofmt | .go | `gofmt` คำสั่งใช้ได้ | | mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` คำสั่งใช้ได้ | | prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml และ [เพิ่มเติม](https://prettier.io/docs/en/index.html) | `prettier` การพึ่งพาใน `package.json` | | biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml และ [เพิ่มเติม](https://biomejs.dev/) | `biome.json(c)` ไฟล์ปรับแต่ง | | zig | .zig, .zon | `zig` คำสั่งใช้ได้ | | clang-format | .c, .cpp, .h, .hpp, .ino และ [เพิ่มเติม](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` ไฟล์ปรับแต่ง | | ktlint | .kt, .kts | `ktlint` คำสั่งใช้ได้ | | ruff | .py, .pyi | คำสั่ง `ruff` ใช้ได้กับ config | | rust | .rs | `rustfmt` คำสั่งใช้ได้ | | cargo fmt | .rs | `cargo fmt` คำสั่งใช้ได้ | | uv | .py, .pyi | `uv` คำสั่งใช้ได้ | | rubocop | .rb, .rake, .gemspec, .ru | `rubocop` คำสั่งใช้ได้ | | standardrb | .rb, .rake, .gemspec, .ru | `standardrb` คำสั่งใช้ได้ | | htmlbeautifier | .erb, .html.erb | `htmlbeautifier` คำสั่งใช้ได้ | | air | .r | `air` คำสั่งใช้ได้ | | dart | .dart | `dart` คำสั่งใช้ได้ | | dfmt | .d | `dfmt` คำสั่งใช้ได้ | | ocamlformat | .ml, .mli | มีคำสั่ง `ocamlformat` และไฟล์ปรับแต่ง `.ocamlformat` | | terraform | .tf, .tfvars | `terraform` คำสั่งใช้ได้ | | gleam | .gleam | `gleam` คำสั่งใช้ได้ | | nix | .nix | `nixfmt` คำสั่งใช้ได้ | | shfmt | .sh, .bash | `shfmt` คำสั่งใช้ได้ | | pint | .php | `laravel/pint` การพึ่งพาใน `composer.json` | | oxfmt (ทดลอง) | .js, .jsx, .ts, .tsx | `oxfmt` การพึ่งพาใน `package.json` และ [แฟล็กตัวแปร env ทดลอง](https://opencode.ai/docs/cli/#experimental) | | ormolu | .hs | `ormolu` คำสั่งใช้ได้ | ดังนั้นหากโปรเจ็กต์ของคุณมี `prettier` ใน `package.json` OpenCode จะใช้มันโดยอัตโนมัติ * * * [มันทำงานอย่างไร](https://opencode.ai/docs/th/formatters#%E0%B8%A1%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B9%84%E0%B8%A3) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เมื่อ OpenCode เขียนหรือแก้ไขไฟล์ มันจะ: 1. ตรวจสอบนามสกุลไฟล์กับฟอร์แมตเตอร์ที่เปิดใช้งานทั้งหมด 2. รันคำสั่งฟอร์แมตเตอร์ที่เหมาะสมบนไฟล์ 3. ใช้การเปลี่ยนแปลงการจัดรูปแบบโดยอัตโนมัติ กระบวนการนี้เกิดขึ้นในเบื้องหลัง ทำให้มั่นใจได้ว่าสไตล์โค้ดของคุณจะถูกรักษาไว้โดยไม่มีขั้นตอนที่ต้องทำเอง * * * [กำหนดค่า](https://opencode.ai/docs/th/formatters#%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2) ---------------------------------------------------------------------------------------------------------------------------- คุณสามารถปรับแต่งฟอร์แมตเตอร์ได้ผ่านทางส่วน `formatter` ในการกำหนดค่า OpenCode ของคุณ { "$schema": "https://opencode.ai/config.json", "formatter": {}} การกำหนดค่าฟอร์แมตเตอร์แต่ละรายการรองรับสิ่งต่อไปนี้: | คุณสมบัติ | พิมพ์ | คำอธิบาย | | --- | --- | --- | | `disabled` | บูลีน | ตั้งค่านี้เป็น `true` เพื่อปิดใช้งานฟอร์แมตเตอร์ | | `command` | สตริง\[\] | คำสั่งให้เรียกใช้การจัดรูปแบบ | | `environment` | วัตถุ | ตัวแปรสภาพแวดล้อมที่จะตั้งค่าเมื่อรันฟอร์แมตเตอร์ | | `extensions` | สตริง\[\] | นามสกุลไฟล์ที่ฟอร์แมตเตอร์นี้ควรรองรับ | ลองดูตัวอย่างบางส่วน * * * ### [ปิดการใช้งานฟอร์แมตเตอร์](https://opencode.ai/docs/th/formatters#%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%9F%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B9%81%E0%B8%A1%E0%B8%95%E0%B9%80%E0%B8%95%E0%B8%AD%E0%B8%A3%E0%B9%8C) หากต้องการปิดการใช้งาน **ทั้งหมด** ฟอร์แมตเตอร์ทั่วโลก ให้ตั้งค่า `formatter` เป็น `false`: { "$schema": "https://opencode.ai/config.json", "formatter": false} หากต้องการปิดใช้งานฟอร์แมตเตอร์ **เฉพาะ** ให้ตั้งค่า `disabled` เป็น `true`: { "$schema": "https://opencode.ai/config.json", "formatter": { "prettier": { "disabled": true } }} * * * ### [ตัวจัดรูปแบบที่กำหนดเอง](https://opencode.ai/docs/th/formatters#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%88%E0%B8%B1%E0%B8%94%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) คุณสามารถแทนที่ฟอร์แมตเตอร์ที่มีอยู่แล้วภายในหรือเพิ่มฟอร์แมตใหม่ได้โดยการระบุคำสั่ง ตัวแปรสภาพแวดล้อม และนามสกุลไฟล์: { "$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"] } }} ตัวยึดตำแหน่ง **`$FILE`** ในคำสั่งจะถูกแทนที่ด้วยเส้นทางไปยังไฟล์ที่กำลังจัดรูปแบบ --- # Zen | OpenCode [Skip to content](https://opencode.ai/docs/zen#_top) Zen === Curated list of models provided by OpenCode. OpenCode Zen is a list of tested and verified models provided by the OpenCode team. Zen works like any other provider in OpenCode. You login to OpenCode Zen and get your API key. It’s **completely optional** and you don’t need to use it to use OpenCode. * * * [Background](https://opencode.ai/docs/zen#background) ------------------------------------------------------ There are a large number of models out there but only a few of these models work well as coding agents. Additionally, most providers are configured very differently; so you get very different performance and quality. So if you are using a model through something like OpenRouter, you can never be sure if you are getting the best version of the model you want. To fix this, we did a couple of things: 1. We tested a select group of models and talked to their teams about how to best run them. 2. We then worked with a few providers to make sure these were being served correctly. 3. Finally, we benchmarked the combination of the model/provider and came up with a list that we feel good recommending. OpenCode Zen is an AI gateway that gives you access to these models. * * * [How it works](https://opencode.ai/docs/zen#how-it-works) ---------------------------------------------------------- OpenCode Zen works like any other provider in OpenCode. 1. You sign in to **[OpenCode Zen](https://opencode.ai/auth) **, add your billing details, and copy your API key. 2. You run the `/connect` command in the TUI, select OpenCode Zen, and paste your API key. 3. Run `/models` in the TUI to see the list of models we recommend. You are charged per request and you can add credits to your account. * * * [Endpoints](https://opencode.ai/docs/zen#endpoints) ---------------------------------------------------- You can also access our models through the following API endpoints. | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GPT 5.4 Pro | gpt-5.4-pro | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex Spark | gpt-5.3-codex-spark | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | The [model id](https://opencode.ai/docs/config/#models) in your OpenCode config uses the format `opencode/`. For example, for GPT 5.3 Codex, you would use `opencode/gpt-5.3-codex` in your config. * * * ### [Models](https://opencode.ai/docs/zen#models) You can fetch the full list of available models and their metadata from: https://opencode.ai/zen/v1/models * * * [Pricing](https://opencode.ai/docs/zen#pricing) ------------------------------------------------ We support a pay-as-you-go model. Below are the prices **per 1M tokens**. | Model | Input | Output | Cached Read | Cached Write | | --- | --- | --- | --- | --- | | Big Pickle | Free | Free | Free | \- | | MiniMax M2.5 Free | Free | Free | Free | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | $0.375 | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 Pro | $30.00 | $180.00 | $30.00 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex Spark | $1.75 | $14.00 | $0.175 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Free | Free | Free | \- | You might notice _Claude Haiku 3.5_ in your usage history. This is a [low cost model](https://opencode.ai/docs/config/#models) that’s used to generate the titles of your sessions. The free models: * MiniMax M2.5 Free is available on OpenCode for a limited time. The team is using this time to collect feedback and improve the model. * Big Pickle is a stealth model that’s free on OpenCode for a limited time. The team is using this time to collect feedback and improve the model. [Contact us](mailto:contact@anoma.ly) if you have any questions. * * * ### [Auto-reload](https://opencode.ai/docs/zen#auto-reload) If your balance goes below $5, Zen will automatically reload $20. You can change the auto-reload amount. You can also disable auto-reload entirely. * * * ### [Monthly limits](https://opencode.ai/docs/zen#monthly-limits) You can also set a monthly usage limit for the entire workspace and for each member of your team. For example, let’s say you set a monthly usage limit to $20, Zen will not use more than $20 in a month. But if you have auto-reload enabled, Zen might end up charging you more than $20 if your balance goes below $5. * * * ### [Deprecated models](https://opencode.ai/docs/zen#deprecated-models) | Model | Deprecation date | | --- | --- | | Qwen3 Coder 480B | Feb 6, 2026 | | Kimi K2 Thinking | March 6, 2026 | | Kimi K2 | March 6, 2026 | | MiniMax M2.1 | March 15, 2026 | | GLM 4.7 | March 15, 2026 | | GLM 4.6 | March 15, 2026 | * * * [Privacy](https://opencode.ai/docs/zen#privacy) ------------------------------------------------ All our models are hosted in the US. Our providers follow a zero-retention policy and do not use your data for model training, with the following exceptions: * Big Pickle: During its free period, collected data may be used to improve the model. * MiniMax M2.5 Free: During its free period, collected data may be used to improve the model. * OpenAI APIs: Requests are retained for 30 days in accordance with [OpenAI’s Data Policies](https://platform.openai.com/docs/guides/your-data) . * Anthropic APIs: Requests are retained for 30 days in accordance with [Anthropic’s Data Policies](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [For Teams](https://opencode.ai/docs/zen#for-teams) ---------------------------------------------------- Zen also works great for teams. You can invite teammates, assign roles, curate the models your team uses, and more. Managing your workspace is currently free for teams as a part of the beta. We’ll be sharing more details on the pricing soon. * * * ### [Roles](https://opencode.ai/docs/zen#roles) You can invite teammates to your workspace and assign roles: * **Admin**: Manage models, members, API keys, and billing * **Member**: Manage only their own API keys Admins can also set monthly spending limits for each member to keep costs under control. * * * ### [Model access](https://opencode.ai/docs/zen#model-access) Admins can enable or disable specific models for the workspace. Requests made to a disabled model will return an error. This is useful for cases where you want to disable the use of a model that collects data. * * * ### [Bring your own key](https://opencode.ai/docs/zen#bring-your-own-key) You can use your own OpenAI or Anthropic API keys while still accessing other models in Zen. When you use your own keys, tokens are billed directly by the provider, not by Zen. For example, your organization might already have a key for OpenAI or Anthropic and you want to use that instead of the one that Zen provides. * * * [Goals](https://opencode.ai/docs/zen#goals) -------------------------------------------- We created OpenCode Zen to: 1. **Benchmark** the best models/providers for coding agents. 2. Have access to the **highest quality** options and not downgrade performance or route to cheaper providers. 3. Pass along any **price drops** by selling at cost; so the only markup is to cover our processing fees. 4. Have **no lock-in** by allowing you to use it with any other coding agent. And always let you use any other provider with OpenCode as well. --- # الإعدادات | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/config#_top) الإعدادات ========= استخدام ملف إعدادات OpenCode بصيغة JSON. يمكنك ضبط OpenCode باستخدام ملف إعدادات بصيغة JSON. * * * [التنسيق](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%AA%D9%86%D8%B3%D9%8A%D9%82) ----------------------------------------------------------------------------------------- يدعم OpenCode تنسيقي **JSON** و**JSONC** (JSON مع تعليقات). { "$schema": "https://opencode.ai/config.json", // إعدادات السمة "theme": "opencode", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true,} * * * [المواقع](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D9%88%D8%A7%D9%82%D8%B9) ----------------------------------------------------------------------------------------- يمكنك وضع ملف الإعدادات في عدة مواقع مختلفة، ولكل موقع ترتيب أولوية مختلف. تُدمَج ملفات الإعدادات معًا ولا تُستبدَل. يتم جمع الإعدادات من مواقع الإعدادات التالية. تتجاوز الإعدادات اللاحقة الإعدادات السابقة فقط عند تعارض المفاتيح. أما الإعدادات غير المتعارضة فتبقى محفوظة من جميع الملفات. على سبيل المثال، إذا كان الإعداد العام يضبط `theme: "opencode"` و`autoupdate: true`، وكان إعداد المشروع يضبط `model: "anthropic/claude-sonnet-4-5"`، فستتضمن الإعدادات النهائية الخيارات الثلاثة جميعها. * * * ### [ترتيب الأولوية](https://opencode.ai/docs/ar/config#%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8-%D8%A7%D9%84%D8%A3%D9%88%D9%84%D9%88%D9%8A%D8%A9) تُحمَّل مصادر الإعدادات بهذا الترتيب (المصادر اللاحقة تتجاوز السابقة): 1. **الإعدادات البعيدة** (من `.well-known/opencode`) - الإعدادات الافتراضية على مستوى المؤسسة 2. **الإعدادات العامة** (`~/.config/opencode/opencode.json`) - تفضيلات المستخدم 3. **إعدادات مخصصة** (`OPENCODE_CONFIG` env var) - تجاوزات مخصصة 4. **إعدادات المشروع** (`opencode.json` داخل المشروع) - إعدادات خاصة بالمشروع 5. **أدلة `.opencode`** - الوكلاء، الأوامر، الإضافات 6. **إعدادات ضمنية** (`OPENCODE_CONFIG_CONTENT` env var) - تجاوزات وقت التشغيل هذا يعني أن إعدادات المشروع يمكنها تجاوز الإعدادات العامة، وأن الإعدادات العامة يمكنها تجاوز الإعدادات الافتراضية البعيدة على مستوى المؤسسة. * * * ### [عن بُعد](https://opencode.ai/docs/ar/config#%D8%B9%D9%86-%D8%A8%D9%8F%D8%B9%D8%AF) يمكن للمؤسسات توفير إعدادات افتراضية عبر نقطة النهاية `.well-known/opencode`. يتم جلب ذلك تلقائيًا عندما تقوم بالمصادقة مع مزوّد يدعم هذه الميزة. تُحمَّل الإعدادات البعيدة أولًا لتكون طبقة الأساس. ويمكن لجميع مصادر الإعدادات الأخرى (العامة، وإعدادات المشروع) تجاوز هذه القيم الافتراضية. على سبيل المثال، إذا كانت مؤسستك توفر خوادم MCP معطّلة افتراضيًا: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} يمكنك تفعيل خوادم محددة في إعداداتك المحلية: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [عام](https://opencode.ai/docs/ar/config#%D8%B9%D8%A7%D9%85) ضع إعدادات OpenCode العامة في `~/.config/opencode/opencode.json`. استخدم الإعدادات العامة للتفضيلات على مستوى المستخدم مثل السمات، والمزوّدين، أو اختصارات المفاتيح. تتجاوز الإعدادات العامة القيم الافتراضية البعيدة الخاصة بالمؤسسة. * * * ### [لكل مشروع](https://opencode.ai/docs/ar/config#%D9%84%D9%83%D9%84-%D9%85%D8%B4%D8%B1%D9%88%D8%B9) أضف `opencode.json` في جذر مشروعك. تمتلك إعدادات المشروع أعلى أولوية بين ملفات الإعدادات القياسية، إذ تتجاوز الإعدادات العامة والبعيدة معًا. عند تشغيل OpenCode، يبحث عن ملف إعدادات في الدليل الحالي أو يصعد حتى أقرب دليل Git. ومن الآمن أيضًا تضمينه في Git، كما يستخدم نفس المخطط الخاص بالإعدادات العامة. * * * ### [مسار مخصص](https://opencode.ai/docs/ar/config#%D9%85%D8%B3%D8%A7%D8%B1-%D9%85%D8%AE%D8%B5%D8%B5) حدّد مسار ملف إعدادات مخصصًا باستخدام متغير البيئة `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" تُحمَّل الإعدادات المخصصة بين الإعدادات العامة وإعدادات المشروع ضمن ترتيب الأولوية. * * * ### [دليل مخصص](https://opencode.ai/docs/ar/config#%D8%AF%D9%84%D9%8A%D9%84-%D9%85%D8%AE%D8%B5%D8%B5) حدّد دليل إعدادات مخصصًا باستخدام متغير البيئة `OPENCODE_CONFIG_DIR`. سيتم البحث داخل هذا الدليل عن الوكلاء والأوامر والأوضاع والإضافات تمامًا مثل الدليل القياسي `.opencode`، ويجب أن يتبع نفس البنية. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" يُحمَّل الدليل المخصص بعد الإعدادات العامة وأدلة `.opencode`، لذلك **يمكنه تجاوز** إعداداتها. * * * [المخطط](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D8%AE%D8%B7%D8%B7) ---------------------------------------------------------------------------------- يحتوي ملف الإعدادات على مخطط مُعرَّف في [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . يفترض أن يتمكن محررك من التحقق والإكمال التلقائي اعتمادًا على هذا المخطط. * * * ### [TUI](https://opencode.ai/docs/ar/config#tui) يمكنك ضبط الإعدادات الخاصة بـ TUI عبر الخيار `tui`. { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} الخيارات المتاحة: * `scroll_acceleration.enabled` - تفعيل تسارع التمرير بأسلوب macOS. **له أولوية على `scroll_speed`.** * `scroll_speed` - مُضاعِف سرعة تمرير مخصص (الافتراضي: `3`، الحد الأدنى: `1`). يتم تجاهله إذا كان `scroll_acceleration.enabled` مساويًا لـ `true`. * `diff_style` - التحكم في عرض `diff`. القيمة `"auto"` تتكيف مع عرض terminal، و`"stacked"` تعرض عمودًا واحدًا دائمًا. [تعرف على المزيد حول استخدام TUI هنا](https://opencode.ai/docs/tui) . * * * ### [الخادم](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%AE%D8%A7%D8%AF%D9%85) يمكنك ضبط إعدادات الخادم لأوامر `opencode serve` و`opencode web` عبر الخيار `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} الخيارات المتاحة: * `port` - المنفذ الذي سيتم الاستماع عليه. * `hostname` - اسم المضيف الذي سيتم الاستماع عليه. عند تفعيل `mdns` وعدم ضبط اسم مضيف، تكون القيمة الافتراضية `0.0.0.0`. * `mdns` - تفعيل اكتشاف الخدمة عبر mDNS. يتيح ذلك للأجهزة الأخرى على الشبكة اكتشاف خادم OpenCode. * `mdnsDomain` - اسم نطاق مخصص لخدمة mDNS. القيمة الافتراضية هي `opencode.local`. مفيد لتشغيل عدة نُسخ على نفس الشبكة. * `cors` - أصول إضافية مسموح بها لـ CORS عند استخدام خادم HTTP من عميل يعتمد على المتصفح. يجب أن تكون القيم أصولًا كاملة (البروتوكول + المضيف + منفذ اختياري)، مثل `https://app.example.com`. [تعرف على المزيد حول الخادم هنا](https://opencode.ai/docs/server) . * * * ### [الأدوات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%A3%D8%AF%D9%88%D8%A7%D8%AA) يمكنك إدارة الأدوات التي يمكن لـ LLM استخدامها عبر الخيار `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [تعرف على المزيد حول الأدوات هنا](https://opencode.ai/docs/tools) . * * * ### [النماذج](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%86%D9%85%D8%A7%D8%B0%D8%AC) يمكنك ضبط المزوّدين والنماذج التي تريد استخدامها في إعدادات OpenCode عبر الخيارات `provider` و`model` و`small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} يضبط الخيار `small_model` نموذجًا منفصلًا للمهام الخفيفة مثل توليد العناوين. افتراضيًا يحاول OpenCode استخدام نموذج أقل تكلفة إذا كان متاحًا لدى مزوّدك، وإلا فسيعود إلى النموذج الرئيسي. قد تتضمن خيارات المزوّد `timeout` و`setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - مهلة الطلب بالميلي ثانية (الافتراضي: 300000). اضبطه إلى `false` لتعطيله. * `setCacheKey` - يضمن تعيين مفتاح التخزين المؤقت دائمًا للمزوّد المحدد. يمكنك أيضًا ضبط [النماذج المحلية](https://opencode.ai/docs/models#local) . [تعرف على المزيد](https://opencode.ai/docs/models) . * * * #### [خيارات خاصة بالمزوّد](https://opencode.ai/docs/ar/config#%D8%AE%D9%8A%D8%A7%D8%B1%D8%A7%D8%AA-%D8%AE%D8%A7%D8%B5%D8%A9-%D8%A8%D8%A7%D9%84%D9%85%D8%B2%D9%88%D9%91%D8%AF) يدعم بعض المزوّدين خيارات إعداد إضافية تتجاوز الإعدادات العامة مثل `timeout` و`apiKey`. ##### [Amazon Bedrock](https://opencode.ai/docs/ar/config#amazon-bedrock) يدعم Amazon Bedrock إعدادات خاصة بـ AWS: { "$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 لـ Bedrock (الافتراضي: متغير البيئة `AWS_REGION` أو `us-east-1`) * `profile` - ملف تعريف AWS المُسمّى من `~/.aws/credentials` (الافتراضي: متغير البيئة `AWS_PROFILE`) * `endpoint` - عنوان URL لنقطة نهاية مخصصة لنقاط نهاية VPC. هذا اسم بديل للخيار العام `baseURL` باستخدام مصطلحات AWS. إذا تم تحديدهما معًا، تكون أولوية `endpoint` أعلى. [تعرف على المزيد حول إعداد Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [السمات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%B3%D9%85%D8%A7%D8%AA) يمكنك ضبط السمة التي تريد استخدامها في إعدادات OpenCode عبر الخيار `theme`. { "$schema": "https://opencode.ai/config.json", "theme": ""} [تعرف على المزيد هنا](https://opencode.ai/docs/themes) . * * * ### [الوكلاء](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%88%D9%83%D9%84%D8%A7%D8%A1) يمكنك ضبط وكلاء متخصصين لمهام محددة عبر الخيار `agent`. { "$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": { // تعطيل أدوات تعديل الملفات لوكيل المراجعة فقط "write": false, "edit": false, }, }, },} يمكنك أيضًا تعريف الوكلاء باستخدام ملفات markdown في `~/.config/opencode/agents/` أو `.opencode/agents/`. [تعرف على المزيد هنا](https://opencode.ai/docs/agents) . * * * ### [الوكيل الافتراضي](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%88%D9%83%D9%8A%D9%84-%D8%A7%D9%84%D8%A7%D9%81%D8%AA%D8%B1%D8%A7%D8%B6%D9%8A) يمكنك تعيين الوكيل الافتراضي باستخدام الخيار `default_agent`. يحدد ذلك أي وكيل سيتم استخدامه عندما لا يتم تحديد وكيل صراحةً. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} يجب أن يكون الوكيل الافتراضي وكيلًا أساسيًا (وليس وكيلًا فرعيًا). يمكن أن يكون وكيلًا مدمجًا مثل `"build"` أو `"plan"`، أو [وكيلًا مخصصًا](https://opencode.ai/docs/agents) قمت بتعريفه. إذا لم يكن الوكيل المحدد موجودًا أو كان وكيلًا فرعيًا، فسيعود OpenCode إلى `"build"` مع تحذير. ينطبق هذا الإعداد على جميع الواجهات: TUI وCLI (`opencode run`) وتطبيق سطح المكتب وGitHub Action. * * * ### [المشاركة](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D8%B4%D8%A7%D8%B1%D9%83%D8%A9) يمكنك ضبط ميزة [share](https://opencode.ai/docs/share) عبر الخيار `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} يقبل هذا الإعداد القيم التالية: * `"manual"` - السماح بالمشاركة اليدوية عبر الأوامر (الافتراضي) * `"auto"` - مشاركة المحادثات الجديدة تلقائيًا * `"disabled"` - تعطيل المشاركة بالكامل افتراضيًا تكون المشاركة في الوضع اليدوي، حيث تحتاج إلى مشاركة المحادثات صراحةً باستخدام الأمر `/share`. * * * ### [الأوامر](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%A3%D9%88%D8%A7%D9%85%D8%B1) يمكنك ضبط أوامر مخصصة للمهام المتكررة عبر الخيار `command`. { "$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", }, },} يمكنك أيضًا تعريف الأوامر باستخدام ملفات markdown في `~/.config/opencode/commands/` أو `.opencode/commands/`. [تعرف على المزيد هنا](https://opencode.ai/docs/commands) . * * * ### [اختصارات المفاتيح](https://opencode.ai/docs/ar/config#%D8%A7%D8%AE%D8%AA%D8%B5%D8%A7%D8%B1%D8%A7%D8%AA-%D8%A7%D9%84%D9%85%D9%81%D8%A7%D8%AA%D9%8A%D8%AD) يمكنك تخصيص اختصارات المفاتيح عبر الخيار `keybinds`. { "$schema": "https://opencode.ai/config.json", "keybinds": {}} [تعرف على المزيد هنا](https://opencode.ai/docs/keybinds) . * * * ### [التحديث التلقائي](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%AA%D8%AD%D8%AF%D9%8A%D8%AB-%D8%A7%D9%84%D8%AA%D9%84%D9%82%D8%A7%D8%A6%D9%8A) سيقوم OpenCode بتنزيل أي تحديثات جديدة تلقائيًا عند بدء التشغيل. يمكنك تعطيل ذلك عبر الخيار `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} إذا لم تكن تريد التحديثات لكنك تريد الإشعار عند توفر نسخة جديدة، فاضبط `autoupdate` على `"notify"`. لاحظ أن هذا يعمل فقط إذا لم يتم تثبيته عبر مدير حزم مثل Homebrew. * * * ### [المنسّقات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D9%86%D8%B3%D9%91%D9%82%D8%A7%D8%AA) يمكنك ضبط منسّقات الشفرة عبر الخيار `formatter`. { "$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"] } }} [تعرف على المزيد حول المنسّقات هنا](https://opencode.ai/docs/formatters) . * * * ### [الأذونات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%A3%D8%B0%D9%88%D9%86%D8%A7%D8%AA) افتراضيًا يسمح opencode **بجميع العمليات** دون الحاجة إلى موافقة صريحة. يمكنك تغيير ذلك عبر الخيار `permission`. على سبيل المثال، لضمان أن أداتي `edit` و`bash` تتطلبان موافقة المستخدم: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [تعرف على المزيد حول الأذونات هنا](https://opencode.ai/docs/permissions) . * * * ### [ضغط السياق](https://opencode.ai/docs/ar/config#%D8%B6%D8%BA%D8%B7-%D8%A7%D9%84%D8%B3%D9%8A%D8%A7%D9%82) يمكنك التحكم في سلوك ضغط السياق عبر الخيار `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true }} * `auto` - ضغط الجلسة تلقائيًا عند امتلاء السياق (الافتراضي: `true`). * `prune` - إزالة مخرجات الأدوات القديمة لتوفير الرموز (tokens) (الافتراضي: `true`). * `reserved` - مخزن مؤقت للرموز (tokens) من أجل الضغط. يترك نافذة كافية لتجنب الفيضان أثناء الضغط. * * * ### [المراقِب](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D8%B1%D8%A7%D9%82%D9%90%D8%A8) يمكنك ضبط أنماط التجاهل لمراقِب الملفات عبر الخيار `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} تتبع الأنماط صياغة `glob`. استخدم ذلك لاستبعاد الأدلة المزدحمة من مراقبة الملفات. * * * ### [خوادم MCP](https://opencode.ai/docs/ar/config#%D8%AE%D9%88%D8%A7%D8%AF%D9%85-mcp) يمكنك ضبط خوادم MCP التي تريد استخدامها عبر الخيار `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [تعرف على المزيد هنا](https://opencode.ai/docs/mcp-servers) . * * * ### [الإضافات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%A5%D8%B6%D8%A7%D9%81%D8%A7%D8%AA) [الإضافات](https://opencode.ai/docs/plugins) توسّع OpenCode بأدوات وخُطافات وتكاملات مخصصة. ضع ملفات الإضافات في `.opencode/plugins/` أو `~/.config/opencode/plugins/`. يمكنك أيضًا تحميل إضافات من npm عبر الخيار `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [تعرف على المزيد هنا](https://opencode.ai/docs/plugins) . * * * ### [التعليمات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D8%AA%D8%B9%D9%84%D9%8A%D9%85%D8%A7%D8%AA) يمكنك ضبط التعليمات الخاصة بالنموذج الذي تستخدمه عبر الخيار `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} يقبل هذا مصفوفة من المسارات وأنماط `glob` لملفات التعليمات. [تعرف على المزيد حول القواعد هنا](https://opencode.ai/docs/rules) . * * * ### [المزوّدون المعطّلون](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D8%B2%D9%88%D9%91%D8%AF%D9%88%D9%86-%D8%A7%D9%84%D9%85%D8%B9%D8%B7%D9%91%D9%84%D9%88%D9%86) يمكنك تعطيل المزوّدين الذين يتم تحميلهم تلقائيًا عبر الخيار `disabled_providers`. هذا مفيد عندما تريد منع تحميل مزوّدين معينين حتى لو كانت بيانات الاعتماد الخاصة بهم متاحة. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} يقبل الخيار `disabled_providers` مصفوفة من معرفات المزوّدين. عند تعطيل مزوّد: * لن يتم تحميله حتى لو كانت متغيرات البيئة مضبوطة. * لن يتم تحميله حتى لو كانت مفاتيح API مضبوطة عبر الأمر `/connect`. * لن تظهر نماذج هذا المزوّد في قائمة اختيار النموذج. * * * ### [المزوّدون المفعّلون](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D8%B2%D9%88%D9%91%D8%AF%D9%88%D9%86-%D8%A7%D9%84%D9%85%D9%81%D8%B9%D9%91%D9%84%D9%88%D9%86) يمكنك تحديد قائمة سماح للمزوّدين عبر الخيار `enabled_providers`. عند ضبطه، سيتم تفعيل المزوّدين المحددين فقط وسيتم تجاهل البقية. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} هذا مفيد عندما تريد تقييد OpenCode لاستخدام مزوّدين محددين بدلًا من تعطيلهم واحدًا تلو الآخر. إذا ظهر مزوّد ضمن كل من `enabled_providers` و`disabled_providers`، تكون أولوية `disabled_providers` أعلى للتوافق مع الإصدارات السابقة. * * * ### [تجريبي](https://opencode.ai/docs/ar/config#%D8%AA%D8%AC%D8%B1%D9%8A%D8%A8%D9%8A) يحتوي المفتاح `experimental` على خيارات قيد التطوير النشط. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [المتغيرات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D8%AA%D8%BA%D9%8A%D8%B1%D8%A7%D8%AA) ------------------------------------------------------------------------------------------------------- يمكنك استخدام استبدال المتغيرات في ملفات الإعدادات للإشارة إلى متغيرات البيئة ومحتويات الملفات. * * * ### [متغيرات البيئة](https://opencode.ai/docs/ar/config#%D9%85%D8%AA%D8%BA%D9%8A%D8%B1%D8%A7%D8%AA-%D8%A7%D9%84%D8%A8%D9%8A%D8%A6%D8%A9) استخدم `{env:VARIABLE_NAME}` لاستبدال متغيرات البيئة: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} إذا لم يكن متغير البيئة مضبوطًا، فسيتم استبداله بسلسلة فارغة. * * * ### [الملفات](https://opencode.ai/docs/ar/config#%D8%A7%D9%84%D9%85%D9%84%D9%81%D8%A7%D8%AA) استخدم `{file:path/to/file}` لاستبدال محتويات ملف: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} يمكن أن تكون مسارات الملفات: * نسبية إلى دليل ملف الإعدادات * أو مسارات مطلقة تبدأ بـ `/` أو `~` يُفيد ذلك في: * الاحتفاظ بالبيانات الحساسة مثل مفاتيح API في ملفات منفصلة. * تضمين ملفات تعليمات كبيرة دون تشويش ملف الإعدادات. * مشاركة مقتطفات إعدادات مشتركة عبر عدة ملفات إعدادات. --- # Конфигурация | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/config#_top) Конфигурация ============ Использование конфигурации opencode JSON. Вы можете настроить opencode, используя файл конфигурации JSON. * * * [Формат](https://opencode.ai/docs/ru/config#%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82) ---------------------------------------------------------------------------------- opencode поддерживает форматы **JSON** и **JSONC** (JSON с комментариями). { "$schema": "https://opencode.ai/config.json", // Theme configuration "theme": "opencode", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true,} * * * [Расположение](https://opencode.ai/docs/ru/config#%D1%80%D0%B0%D1%81%D0%BF%D0%BE%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) ---------------------------------------------------------------------------------------------------------------------------- Вы можете разместить свою конфигурацию в нескольких разных местах, и у них есть разный порядок старшинства. Файлы конфигурации объединяются, а не заменяются. Настройки из следующих мест конфигурации объединяются. Более поздние конфигурации переопределяют предыдущие только в случае конфликта ключей. Неконфликтные настройки из всех конфигов сохраняются. Например, если ваша глобальная конфигурация устанавливает `theme: "opencode"` и `autoupdate: true`, а конфигурация вашего проекта устанавливает `model: "anthropic/claude-sonnet-4-5"`, окончательная конфигурация будет включать все три параметра. * * * ### [Порядок приоритета](https://opencode.ai/docs/ru/config#%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BE%D0%BA-%D0%BF%D1%80%D0%B8%D0%BE%D1%80%D0%B8%D1%82%D0%B5%D1%82%D0%B0) Источники конфигурации загружаются в следующем порядке (более поздние источники переопределяют более ранние): 1. **Удаленная конфигурация** (от `.well-known/opencode`) – организационные настройки по умолчанию. 2. **Глобальная конфигурация** (`~/.config/opencode/opencode.json`) — настройки пользователя. 3. **Пользовательская конфигурация** (`OPENCODE_CONFIG` env var) – пользовательские переопределения 4. **Конфигурация проекта** (`opencode.json` в проекте) — настройки, специфичные для проекта. 5. **Каталоги `.opencode`** — агенты, команды, плагины 6. **Встроенная конфигурация** (`OPENCODE_CONFIG_CONTENT` env var) – переопределяет время выполнения Это означает, что конфигурации проекта могут переопределять глобальные настройки по умолчанию, а глобальные конфигурации могут переопределять настройки по умолчанию для удаленной организации. * * * ### [Удаленная](https://opencode.ai/docs/ru/config#%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%BD%D0%B0%D1%8F) Организации могут предоставить конфигурацию по умолчанию через конечную точку `.well-known/opencode`. Он извлекается автоматически при аутентификации у провайдера, который его поддерживает. Удаленная конфигурация загружается первой и служит базовым слоем. Все остальные источники конфигурации (глобальные, проектные) могут переопределить эти значения по умолчанию. Например, если ваша организация предоставляет серверы MCP, которые по умолчанию отключены: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Вы можете включить определенные серверы в локальной конфигурации: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Глобальная](https://opencode.ai/docs/ru/config#%D0%B3%D0%BB%D0%BE%D0%B1%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F) Поместите глобальную конфигурацию opencode в `~/.config/opencode/opencode.json`. Используйте глобальную конфигурацию для общепользовательских настроек, таких как темы, поставщики или привязки клавиш. Для настроек, специфичных для TUI, используйте `~/.config/opencode/tui.json`. Глобальная конфигурация переопределяет настройки по умолчанию для удаленной организации. * * * ### [Проектная](https://opencode.ai/docs/ru/config#%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%BD%D0%B0%D1%8F) Добавьте `opencode.json` в корень вашего проекта. Конфигурация проекта имеет наивысший приоритет среди стандартных файлов конфигурации — она переопределяет как глобальные, так и удаленные конфигурации. Для настроек TUI, специфичных для проекта, добавьте `tui.json` рядом с ним. Когда opencode запускается, он ищет файл конфигурации в текущем каталоге или переходит к ближайшему каталогу Git. Его также можно безопасно зарегистрировать в Git, и он использует ту же схему, что и глобальная. * * * ### [Пользовательский путь](https://opencode.ai/docs/ru/config#%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B9-%D0%BF%D1%83%D1%82%D1%8C) Укажите собственный путь к файлу конфигурации, используя переменную среды `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Пользовательская конфигурация загружается между глобальными и проектными конфигурациями в порядке приоритета. * * * ### [Пользовательский каталог](https://opencode.ai/docs/ru/config#%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B9-%D0%BA%D0%B0%D1%82%D0%B0%D0%BB%D0%BE%D0%B3) Укажите пользовательский каталог конфигурации, используя переменную среды `OPENCODE_CONFIG_DIR`. В этом каталоге будет выполняться поиск агентов, команд, режимов и плагинов (аналогично стандартному каталогу `.opencode`), и он должен иметь ту же структуру. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" Пользовательский каталог загружается после каталогов global config и `.opencode`, поэтому он **может переопределить** их настройки. * * * [Схема](https://opencode.ai/docs/ru/config#%D1%81%D1%85%D0%B5%D0%BC%D0%B0) --------------------------------------------------------------------------- Файл конфигурации имеет схему, определенную в [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . Конфигурация TUI использует [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) . Ваш редактор должен иметь возможность проверять и автозаполнять данные на основе схемы. * * * ### [TUI](https://opencode.ai/docs/ru/config#tui) Используйте специальный файл `tui.json` (или `tui.jsonc`) для настроек, специфичных для TUI. { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Используйте `OPENCODE_TUI_CONFIG`, чтобы указать на пользовательский файл конфигурации TUI. Устаревшие ключи `theme`, `keybinds` и `tui` в `opencode.json` устарели и автоматически переносятся, когда это возможно. [Подробнее об использовании TUI можно узнать здесь](https://opencode.ai/docs/tui#configure) . * * * ### [Сервер](https://opencode.ai/docs/ru/config#%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80) Вы можете настроить параметры сервера для команд `opencode serve` и `opencode web` с помощью опции `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Доступные варианты: * `port` — порт для прослушивания. * `hostname` — имя хоста для прослушивания. Если `mdns` включен и имя хоста не задано, по умолчанию используется `0.0.0.0`. * `mdns` — включить обнаружение службы mDNS. Это позволит другим устройствам в сети обнаружить ваш сервер opencode. * `mdnsDomain` — собственное доменное имя для службы mDNS. По умолчанию `opencode.local`. Полезно для запуска нескольких экземпляров в одной сети. * `cors` — дополнительные источники, позволяющие использовать CORS при использовании HTTP-сервера из браузерного клиента. Значения должны быть полными источниками (схема + хост + дополнительный порт), например `https://app.example.com`. [Подробнее о сервере можно узнать здесь](https://opencode.ai/docs/server) . * * * ### [Инструменты](https://opencode.ai/docs/ru/config#%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B) Вы можете управлять инструментами, которые LLM может использовать, с помощью опции `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Подробнее об инструментах можно узнать здесь](https://opencode.ai/docs/tools) . * * * ### [models](https://opencode.ai/docs/ru/config#models) Вы можете настроить поставщиков и модели, которые хотите использовать в своей конфигурации opencode, с помощью параметров `provider`, `model` и `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} Опция `small_model` настраивает отдельную модель для облегченных задач, таких как создание заголовков. По умолчанию opencode пытается использовать более дешевую модель, если она доступна у вашего провайдера, в противном случае он возвращается к вашей основной модели. Опции провайдера могут включать `timeout` и `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` — таймаут запроса в миллисекундах (по умолчанию: 300000). Установите `false` для отключения. * `setCacheKey` — убедитесь, что ключ кэша всегда установлен для назначенного поставщика. Вы также можете настроить [локальные модели](https://opencode.ai/docs/models#local) . [Подробнее](https://opencode.ai/docs/models) . * * * #### [Параметры, зависящие от поставщика](https://opencode.ai/docs/ru/config#%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B-%D0%B7%D0%B0%D0%B2%D0%B8%D1%81%D1%8F%D1%89%D0%B8%D0%B5-%D0%BE%D1%82-%D0%BF%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D1%89%D0%B8%D0%BA%D0%B0) Некоторые поставщики поддерживают дополнительные параметры конфигурации помимо общих настроек `timeout` и `apiKey`. ##### [Amazon](https://opencode.ai/docs/ru/config#amazon) Amazon Bedrock поддерживает конфигурацию, специфичную для AWS: { "$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 для Bedrock (по умолчанию переменная среды `AWS_REGION` или `us-east-1`) * `profile` — именованный профиль AWS из `~/.aws/credentials` (по умолчанию переменная окружения `AWS_PROFILE`) * `endpoint` — URL-адрес пользовательской конечной точки для конечных точек VPC. Это псевдоним общего параметра `baseURL`, использующий терминологию, специфичную для AWS. Если указаны оба параметра, `endpoint` имеет приоритет. [Подробнее о конфигурации Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [theme](https://opencode.ai/docs/ru/config#theme) Установите тему пользовательского интерфейса в `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [Подробнее здесь](https://opencode.ai/docs/themes) . * * * ### [agent](https://opencode.ai/docs/ru/config#agent) Вы можете настроить специализированные агенты для конкретных задач с помощью опции `agent`. { "$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, }, }, },} Вы также можете определить агентов, используя файлы Markdown в `~/.config/opencode/agents/` или `.opencode/agents/`. [Подробнее здесь](https://opencode.ai/docs/agents) . * * * ### [default\_agent](https://opencode.ai/docs/ru/config#default_agent) Вы можете установить агента по умолчанию, используя опцию `default_agent`. Это определяет, какой агент используется, если ни один из них не указан явно. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} Агент по умолчанию должен быть основным агентом (а не субагентом). Это может быть встроенный агент, например `"build"` или `"plan"`, или [пользовательский агент](https://opencode.ai/docs/agents) , который вы определили. Если указанный агент не существует или является субагентом, opencode вернется к `"build"` с предупреждением. Этот параметр применяется ко всем интерфейсам: TUI, CLI (`opencode run`), настольному приложению и действию GitHub. * * * Функцию [share](https://opencode.ai/docs/share) можно настроить с помощью опции `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Принимает значения: * `"manual"` — разрешить общий доступ вручную с помощью команд (по умолчанию). * `"auto"` — автоматически делиться новыми беседами. * `"disabled"` — полностью отключить общий доступ По умолчанию общий доступ установлен в ручной режим, в котором вам необходимо явно делиться разговорами с помощью команды `/share`. * * * ### [Команды](https://opencode.ai/docs/ru/config#%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D1%8B) Вы можете настроить собственные команды для повторяющихся задач с помощью опции `command`. { "$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", }, },} Вы также можете определять команды, используя файлы Markdown в `~/.config/opencode/commands/` или `.opencode/commands/`. [Подробнее здесь](https://opencode.ai/docs/commands) . * * * ### [Сочетания клавиш](https://opencode.ai/docs/ru/config#%D1%81%D0%BE%D1%87%D0%B5%D1%82%D0%B0%D0%BD%D0%B8%D1%8F-%D0%BA%D0%BB%D0%B0%D0%B2%D0%B8%D1%88) Настройте привязки клавиш в `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [Подробнее здесь](https://opencode.ai/docs/keybinds) . * * * ### [Автообновление](https://opencode.ai/docs/ru/config#%D0%B0%D0%B2%D1%82%D0%BE%D0%BE%D0%B1%D0%BD%D0%BE%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5) opencode автоматически загрузит все новые обновления при запуске. Вы можете отключить это с помощью опции `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Если вы не хотите получать обновления, но хотите получать уведомления о появлении новой версии, установите для `autoupdate` значение `"notify"`. Обратите внимание, что это работает только в том случае, если оно было установлено без использования менеджера пакетов, такого как Homebrew. * * * ### [Форматтеры](https://opencode.ai/docs/ru/config#%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D1%82%D0%B5%D1%80%D1%8B) Вы можете настроить форматировщики кода с помощью опции `formatter`. { "$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"] } }} [Подробнее о форматтерах можно узнать здесь](https://opencode.ai/docs/formatters) . * * * ### [permission](https://opencode.ai/docs/ru/config#permission) По умолчанию opencode **разрешает все операции**, не требуя явного разрешения. Вы можете изменить это, используя опцию `permission`. Например, чтобы гарантировать, что инструменты `edit` и `bash` требуют одобрения пользователя: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Подробнее о разрешениях можно узнать здесь](https://opencode.ai/docs/permissions) . * * * ### [compaction](https://opencode.ai/docs/ru/config#compaction) Вы можете управлять поведением сжатия контекста с помощью опции `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` — автоматически сжимать сеанс при заполнении контекста (по умолчанию: `true`). * `prune` — удалить старые выходные данные инструмента для сохранения токенов (по умолчанию: `true`). * `reserved` — Буфер токенов для сжатия. Оставляет достаточное окно, чтобы избежать переполнения во время сжатия. * * * ### [watcher](https://opencode.ai/docs/ru/config#watcher) Вы можете настроить шаблоны игнорирования средства отслеживания файлов с помощью опции `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Шаблоны соответствуют синтаксису glob. Используйте это, чтобы исключить зашумленные каталоги из просмотра файлов. * * * ### [mcp](https://opencode.ai/docs/ru/config#mcp) Вы можете настроить серверы MCP, которые хотите использовать, с помощью опции `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Подробнее здесь](https://opencode.ai/docs/mcp-servers) . * * * ### [Плагины](https://opencode.ai/docs/ru/config#%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD%D1%8B) [Плагины](https://opencode.ai/docs/plugins) расширяют opencode с помощью пользовательских инструментов, перехватчиков и интеграций. Поместите файлы плагина в `.opencode/plugins/` или `~/.config/opencode/plugins/`. Вы также можете загружать плагины из npm с помощью опции `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Подробнее здесь](https://opencode.ai/docs/plugins) . * * * ### [instructions](https://opencode.ai/docs/ru/config#instructions) Вы можете настроить инструкции для используемой вами модели с помощью опции `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Для этого требуется массив путей и шаблонов glob для файлов инструкций. [Подробнее о правилах читайте здесь](https://opencode.ai/docs/rules) . * * * ### [disabled\_providers](https://opencode.ai/docs/ru/config#disabled_providers) Вы можете отключить поставщиков, которые загружаются автоматически, с помощью опции `disabled_providers`. Это полезно, если вы хотите запретить загрузку определенных поставщиков, даже если их учетные данные доступны. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} Опция `disabled_providers` принимает массив идентификаторов поставщиков. Когда провайдер отключен: * Он не будет загружен, даже если установлены переменные среды. * Он не будет загружен, даже если ключи API настроены с помощью команды `/connect`. * Модели поставщика не появятся в списке выбора моделей. * * * ### [enabled\_providers](https://opencode.ai/docs/ru/config#enabled_providers) Вы можете указать белый список поставщиков с помощью опции `enabled_providers`. Если этот параметр установлен, будут включены только указанные поставщики, а все остальные будут игнорироваться. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Это полезно, если вы хотите ограничить opencode использованием только определенных поставщиков, а не отключать их по одному. Если поставщик указан как в `enabled_providers`, так и в `disabled_providers`, `disabled_providers` имеет приоритет для обратной совместимости. * * * ### [Экспериментальные возможности](https://opencode.ai/docs/ru/config#%D1%8D%D0%BA%D1%81%D0%BF%D0%B5%D1%80%D0%B8%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5-%D0%B2%D0%BE%D0%B7%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%D1%81%D1%82%D0%B8) Ключ `experimental` содержит параметры, находящиеся в активной разработке. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Переменные](https://opencode.ai/docs/ru/config#%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5) -------------------------------------------------------------------------------------------------------------- Вы можете использовать подстановку переменных в файлах конфигурации для ссылки на переменные среды и содержимое файлов. * * * ### [Переменные окружения](https://opencode.ai/docs/ru/config#%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5-%D0%BE%D0%BA%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F) Используйте `{env:VARIABLE_NAME}` для замены переменных среды: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Если переменная среды не установлена, она будет заменена пустой строкой. * * * ### [Файлы](https://opencode.ai/docs/ru/config#%D1%84%D0%B0%D0%B9%D0%BB%D1%8B) Используйте `{file:path/to/file}` для замены содержимого файла: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Пути к файлам могут быть: * Относительно каталога файла конфигурации * Или абсолютные пути, начинающиеся с `/` или `~`. Они полезны для: * Хранение конфиденциальных данных, таких как ключи API, в отдельных файлах. * Включая большие файлы инструкций, не загромождая вашу конфигурацию. * Совместное использование общих фрагментов конфигурации в нескольких файлах конфигурации. --- # IDE | OpenCode [Skip to content](https://opencode.ai/docs/ide#_top) IDE === The OpenCode extension for VS Code, Cursor, and other IDEs OpenCode integrates with VS Code, Cursor, or any IDE that supports a terminal. Just run `opencode` in the terminal to get started. * * * [Usage](https://opencode.ai/docs/ide#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](https://opencode.ai/docs/ide#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](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Manual Install](https://opencode.ai/docs/ide#manual-install) Search for **OpenCode** in the Extension Marketplace and click **Install**. * * * ### [Troubleshooting](https://opencode.ai/docs/ide#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 --- # Konfiguration | OpenCode [Gå til indhold](https://opencode.ai/docs/da/config#_top) Konfiguration ============= Ved at bruge OpenCode JSON konfig. Du kan konfigurere OpenCode ved hjælp af en JSON-konfigurationsfil. * * * [Format](https://opencode.ai/docs/da/config#format) ---------------------------------------------------- OpenCode understøtter både **JSON** og **JSONC** (JSON med kommentarer) formater. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [Placeringer](https://opencode.ai/docs/da/config#placeringer) -------------------------------------------------------------- Du kan placere din konfiguration et par forskellige steder, og de har en forskellig rækkefølge. Konfigurationsfiler flettes sammen, erstattes ikke. Indstillinger fra følgende konfigurationssteder kombineret. Senere konfigurationer tilsidesætter kun tidligere konfigurationer for modstridende nøgler. Ikke-modstridende indstillinger fra alle konfigurationer bevares. For eksempel, hvis dine globale konfigurationssæt `autoupdate: true`, og dine projektkonfigurationssæt `model: "anthropic/claude-sonnet-4-5"`, vil den endelige konfiguration integrere begge indstillinger. * * * ### [Prioritetsrækkefølge](https://opencode.ai/docs/da/config#prioritetsr%C3%A6kkef%C3%B8lge) Konfigurationskilder indlæses i denne rækkefølge (senere kilder tilsidesætter tidligere): 1. **Fjernkonfiguration** (fra `.well-known/opencode`) - organisatoriske standardindstillinger 2. **Global config** (`~/.config/opencode/opencode.json`) - brugerpræferencer 3. **Tilpasset konfiguration** (`OPENCODE_CONFIG` env var) - tilpassede tilsidesættelser 4. **Project config** (`opencode.json` i projekt) - projektspecifikke indstillinger 5. **`.opencode` mapper** - agent, kommandoer, plugins 6. **Inline config** (`OPENCODE_CONFIG_CONTENT` env var) - runtime tilsidesættelser Dette betyder, at projektkonfigurationer kan tilsidesætte globale standardindstillinger, og globale konfigurationer kan tilsidesætte eksterne organisatoriske standarder. * * * ### [Ekstern konfiguration](https://opencode.ai/docs/da/config#ekstern-konfiguration) Organisationer kan levere standardkonfiguration via `.well-known/opencode`\-slutpunktet. Dette hentes automatisk, når du godkender med en udbyder, der understøtter det. Remote config indlæses først og fungerer som basislaget. Alle andre konfigurationskilder (global, projekt) kan tilsidesætte disse standardindstillinger. Hvis din organisation f.eks. leverer MCP-servere, der er deaktiveret som standard: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Du kan aktivere specifikke servere i din lokale konfiguration: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global](https://opencode.ai/docs/da/config#global) Placer din globale OpenCode-konfiguration i `~/.config/opencode/opencode.json`. Brug global konfiguration til brugerdækkende præferencer som temaer, udbydere eller nøglebindinger. Global config tilsidesætter eksterne organisatoriske standarder. * * * ### [Projekt-niveau](https://opencode.ai/docs/da/config#projekt-niveau) Tilføj `opencode.json` i dit projektrod. Project config har den højeste forrang blandt standard config-filer - den tilsidesætter både globale og eksterne config. Når OpenCode starter op, søger den efter en konfigurationsfil i den aktuelle mappe eller går op til den nærmeste Git-mappe. Dette er også sikkert at blive tjekket ind i Git og bruger det samme skema som det globale. * * * ### [Brugerdefineret sti](https://opencode.ai/docs/da/config#brugerdefineret-sti) Angiv en brugerdefineret konfigurationsfilsti ved hjælp af miljøvariablen `OPENCODE_CONFIG`. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Brugerdefineret konfigurationsindlæses mellem globale konfigurationer og projektkonfigurationer i prioriteret rækkefølge. * * * ### [Brugerdefineret mappe](https://opencode.ai/docs/da/config#brugerdefineret-mappe) Angiv en brugerdefineret konfigurationsmappe ved hjælp af `OPENCODE_CONFIG_DIR` miljøvariabel. Dette kort vil blive søgt efter agenter, kommandoer, modes og plugins ligesom standard `.opencode` mappen, og bør følge samme struktur. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" Den brugerdefinerede mappe indlæses efter den globale konfig og `.opencode` mapper, så den **kan tilsidesætte** deres indstillinger. * * * [Skema](https://opencode.ai/docs/da/config#skema) -------------------------------------------------- Konfigurationsfilen har et skema, der defineres i [**`opencode.ai/config.json`**](https://opencode.ai/config.json) . Din editor skal være i stand til at validere og autofuldføre baseret på skemaet. * * * ### [TUI](https://opencode.ai/docs/da/config#tui) Du kan konfigurere TUI-specifikke indstillinger gennem indstillingen `tui`. { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} Tilgængelige muligheder: * `scroll_acceleration.enabled` - Aktiver macOS-stil rulleacceleration. **Har forrang frem for `scroll_speed`.** * `scroll_speed` - Brugerdefineret rullehastighedsmultiplikator (standard: `3`, minimum: `1`). Ignoreres, hvis `scroll_acceleration.enabled` er `true`. * `diff_style` - Kontroller diff-gengivelse. `"auto"` tilpasser sig terminalbredden, `"stacked"` viser altid en enkelt kolonne. [Learn more about using the TUI here](https://opencode.ai/docs/tui) . * * * ### [Server](https://opencode.ai/docs/da/config#server) Du kan konfigurere serverindstillinger for kommandoerne `opencode serve` og `opencode web` gennem indstillingen `server`. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Tilgængelige muligheder: * `port` - Port til at lytte på. * `hostname` - Værtsnavn at lytte på. Når `mdns` er aktiveret, og der ikke er angivet noget værtsnavn, er standarden `0.0.0.0`. * `mdns` - Aktiver mDNS-tjenesteopdagelse. Dette gør det muligt for andre enheder på netværket at opdage din OpenCode-server. * `mdnsDomain` - Brugerdefineret domænenavn til mDNS-tjeneste. Som standard er `opencode.local`. Nyttigt til at køre flere forekomster på det samme netværk. * `cors` - Yderligere oprindelser for at tillade CORS ved brug af HTTP-serveren fra en browserbaseret klient. Værdier skal være fulde oprindelser (skema + vært + valgfri port), f.eks. `https://app.example.com`. [Learn more about the server here](https://opencode.ai/docs/server) . * * * ### [Værktøjer (`tools`)](https://opencode.ai/docs/da/config#v%C3%A6rkt%C3%B8jer-tools) Du kan administrere de værktøjer, en LLM kan bruge, gennem indstillingen `tools`. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Learn more about tools here](https://opencode.ai/docs/tools) . * * * ### [Modeller (`models`)](https://opencode.ai/docs/da/config#modeller-models) Du kan konfigurere de udbydere og modeller, du vil bruge i din OpenCode-konfiguration, gennem mulighederne `provider`, `model` og `small_model`. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} Indstillingen `small_model` konfigurerer en separat model til lette opgaver som titelgenerering. Som standard forsøger OpenCode at bruge en billigere model, hvis en er tilgængelig fra din udbyder, ellers falder den tilbage til din hovedmodel. Udbydermuligheder kan omfatte `timeout` og `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Anmodningstimeout i millisekunder (standard: 300000). Indstil til `false` for at deaktivere. * `setCacheKey` - Sørg for, at en cache-nøgle altid er indstillet til den udpegede udbyder. Du kan også konfigurere [local models](https://opencode.ai/docs/models#local) . [Learn more](https://opencode.ai/docs/models) . * * * #### [Udbyder-specifikke muligheder](https://opencode.ai/docs/da/config#udbyder-specifikke-muligheder) Nogle udbydere understøtter yderligere konfigurationsmuligheder ud over de generiske `timeout` og `apiKey` indstillinger. ##### [Amazon Bedrock](https://opencode.ai/docs/da/config#amazon-bedrock) Amazon Bedrock understøtter AWS-specifik konfiguration: { "$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 (standard til `AWS_REGION` env var eller `us-east-1`) * `profile` - AWS navngivet profil fra `~/.aws/credentials` (standard til `AWS_PROFILE` env var) * `endpoint` - Brugerdefineret slutpunkt URL for VPC-endepunkter. Dette er et alias for den generiske `baseURL`\-indstilling, der bruger AWS-specifik terminologi. Hvis begge er angivet, har `endpoint` forrang. [Learn more about Amazon Bedrock configuration](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Temaer (`themes`)](https://opencode.ai/docs/da/config#temaer-themes) Du kan konfigurere det tema, du vil bruge i din OpenCode-konfiguration, gennem indstillingen `theme`. { "$schema": "https://opencode.ai/config.json", "theme": ""} [Learn more here](https://opencode.ai/docs/themes) . * * * ### [Agent](https://opencode.ai/docs/da/config#agent) Du kan konfigurere opgaver specialiserede agenter til specifikke indstillinger gennem indstillingen `agent`. { "$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, }, }, },} Du kan også definere agenter ved at bruge markdown-filer i `~/.config/opencode/agents/` eller `.opencode/agents/`. [Learn more here](https://opencode.ai/docs/agents) . * * * ### [Standardagent (`default_agent`)](https://opencode.ai/docs/da/config#standardagent-default_agent) Du kan indstille standardagenten ved at bruge indstillingen `default_agent`. Dette bestemmer, hvilken agent der bruges, når ingen er eksplicit angivet. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} Standardagenten skal være en primær agent (ikke en subagent). Dette kan være en indbygget agent som `"build"` eller `"plan"`, eller en [custom agent](https://opencode.ai/docs/agents) , du har defineret. Hvis den angivne agent ikke eksisterer eller er en underagent, vil OpenCode falde tilbage til `"build"` med en advarsel. Denne indstilling gælder på tværs af alle grænseflader: TUI, CLI (`opencode run`), desktop-app og GitHub Action. * * * ### [Deling (`share`)](https://opencode.ai/docs/da/config#deling-share) Du kan konfigurere funktionen [share](https://opencode.ai/docs/share) gennem indstillingen `share`. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Dette kræver: * `"manual"` - Tillad manuel deling via kommandoer (standard) * `"auto"` - Del automatisk nye samtaler * `"disabled"` - Deaktiver deling helt Som standard er deling indstillet til manuel tilstand, hvor du eksplicit skal dele samtaler ved hjælp af kommandoen `/share`. * * * ### [Kommandoer (`command`)](https://opencode.ai/docs/da/config#kommandoer-command) Du kan konfigurere brugerdefinerede kommandoer til gentagne opgaver gennem indstillingen `command`. { "$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", }, },} Du kan også definere kommandoer ved hjælp af markdown-filer i `~/.config/opencode/commands/` eller `.opencode/commands/`. [Learn more here](https://opencode.ai/docs/commands) . * * * ### [Tastebindinger (`keybinds`)](https://opencode.ai/docs/da/config#tastebindinger-keybinds) Du kan tilpasse dine nøglebindinger gennem indstillingen `keybinds`. { "$schema": "https://opencode.ai/config.json", "keybinds": {}} [Learn more here](https://opencode.ai/docs/keybinds) . * * * ### [Auto-opdatering (`autoupdate`)](https://opencode.ai/docs/da/config#auto-opdatering-autoupdate) OpenCode vil automatisk downloade alle nye opdateringer, når den starter op. Du kan deaktivere dette med indstillingen `autoupdate`. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Hvis du ikke ønsker opdatering, men ønsker at blive underrettet, når en ny version er tilgængelig, skal du indstille `autoupdate` til `"notify"`. Bemærk, at dette kun virker, hvis det ikke blev installeret ved hjælp af en pakkehåndtering såsom Homebrew. * * * ### [Formater (`formatter`)](https://opencode.ai/docs/da/config#formater-formatter) Du kan konfigurere kodeformatere gennem indstillingen `formatter`. { "$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](https://opencode.ai/docs/formatters) . * * * ### [Tilladelse (`permission`)](https://opencode.ai/docs/da/config#tilladelse-permission) Som standard opencode **tillader alle operationer** uden at kræve eksplicit godkendelse. Du kan ændre dette ved at bruge indstillingen `permission`. For at sikre, at værktøjerne `edit` og `bash` for eksempel kræver brugergodkendelse: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [Learn more about permissions here](https://opencode.ai/docs/permissions) . * * * ### [Komprimering (`compaction`)](https://opencode.ai/docs/da/config#komprimering-compaction) Du kan styre kontekstkomprimeringsadfærd gennem indstillingen `compaction`. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - Komprimer automatisk sessionen, når konteksten er fuld (standard: `true`). * `prune` - Fjern gamle værktøjsudgange for at gemme tokens (standard: `true`). * `reserved` - Tokenbuffer til komprimering. Efterlader nok vindue til at undgå overløb under komprimering * * * ### [Overvågning (`watcher`)](https://opencode.ai/docs/da/config#overv%C3%A5gning-watcher) Du kan konfigurere ignoreringsmønstre for filovervåger gennem indstillingen `watcher`. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Mønstre følger glob-syntaks. Brug dette til at udelukke støjende mapper fra filvisning. * * * ### [MCP](https://opencode.ai/docs/da/config#mcp) Du kan konfigurere MCP-servere, som du vil bruge, gennem indstillingen `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Learn more here](https://opencode.ai/docs/mcp-servers) . * * * ### [Plugin](https://opencode.ai/docs/da/config#plugin) [Plugins](https://opencode.ai/docs/plugins) udvide OpenCode med brugerdefinerede værktøjer, kroge og integrationer. Placer plugin-filer i `.opencode/plugins/` eller `~/.config/opencode/plugins/`. Du kan også indlæse plugins fra npm gennem indstillingen `plugin`. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Learn more here](https://opencode.ai/docs/plugins) . * * * ### [Instruktioner (`instructions`)](https://opencode.ai/docs/da/config#instruktioner-instructions) Du kan konfigurere brugervejledningen til den model, du kan gennem indstillingen `instructions`. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Dette kræver en række stier og globmønstre til instruktionsfiler. [Læs mere om regler her](https://opencode.ai/docs/rules) . * * * ### [Deaktiverede udbydere (`disabled_providers`)](https://opencode.ai/docs/da/config#deaktiverede-udbydere-disabled_providers) Du kan deaktivere udbydere, der indlæses automatisk gennem `disabled_providers`\-indstillingen. Dette er nyttigt, når du vil forhindre visse udbydere i at blive indlæst, deres legitimationsoplysninger er tilgængelige. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} Indstillingen `disabled_providers` accepterer en række udbyder-id’er. Når en udbyder er deaktiveret: * Den vil ikke blive indlæst, selvom miljøvariabler er indstillet. * Den vil ikke blive indlæst, selvom API-nøgler er konfigureret via `/connect`\-kommandoen. * Udbyderens modeller vises ikke på modelvalgslisten. * * * ### [Aktiverede udbydere (`enabled_providers`)](https://opencode.ai/docs/da/config#aktiverede-udbydere-enabled_providers) Du kan angive en tilladelsesliste over udbydere gennem muligheden `enabled_providers`. Når den er indstillet, vil kun de angivne udbydere blive aktiveret, og alle andre vil blive ignoreret. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Dette er nyttigt, når du vil begrænse OpenCode til kun at bruge specifikke udbydere i stedet for at deaktivere dem én efter én. Hvis en udbyder optræder i både `enabled_providers` og `disabled_providers`, har `disabled_providers` prioritet for bagudkompatibilitet. * * * ### [Eksperimentel (`experimental`)](https://opencode.ai/docs/da/config#eksperimentel-experimental) Nøglen `experimental` indeholder muligheder, der er under aktiv udvikling. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Variabler](https://opencode.ai/docs/da/config#variabler) ---------------------------------------------------------- Du kan bruge variabelsubstitution i dine konfigurationsfiler til at referere til miljøvariabler og filindhold. * * * ### [Miljøvariabler](https://opencode.ai/docs/da/config#milj%C3%B8variabler) Brug `{env:VARIABLE_NAME}` til at erstatte miljøvariabler: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Hvis miljøvariablen ikke er indstillet, vil den blive erstattet med en tom streng. * * * ### [Filer](https://opencode.ai/docs/da/config#filer) Brug `{file:path/to/file}` til at erstatte indholdet af en fil: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Filstier kan være: * I forhold til konfigurationsfilbiblioteket * Eller absolutte stier, der starter med `/` eller `~` Disse er nyttige til: * Opbevaring af følsomme data som API-nøgler i separate filer. * Inklusiv store instruktionsfiler uden at rode i din konfiguration. * Deling af fælles konfigurationsuddrag på tværs af flere konfigurationsfiler. --- # การกำหนดค่า | OpenCode [Skip to content](https://opencode.ai/docs/th/config#_top) การกำหนดค่า =========== การใช้การกำหนดค่า OpenCode JSON คุณสามารถกำหนดค่า OpenCode ได้โดยใช้ไฟล์กำหนดค่า JSON * * * [รูปแบบ](https://opencode.ai/docs/th/config#%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B9%81%E0%B8%9A%E0%B8%9A) ---------------------------------------------------------------------------------------------------- OpenCode รองรับทั้งรูปแบบ **JSON** และ **JSONC** (JSON พร้อมความคิดเห็น) { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true, "server": { "port": 4096, },} * * * [สถานที่](https://opencode.ai/docs/th/config#%E0%B8%AA%E0%B8%96%E0%B8%B2%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88) -------------------------------------------------------------------------------------------------------------- คุณสามารถวางการกำหนดค่าของคุณในสถานที่ต่าง ๆ สองสามแห่งและมี ลำดับความสำคัญที่แตกต่างกัน ไฟล์การกำหนดค่าจะถูกรวมเข้าด้วยกัน โดยไม่มีการแทนที่ การตั้งค่าจากตำแหน่งการกำหนดค่าต่อไปนี้จะรวมกัน การกำหนดค่าในภายหลังจะแทนที่การกำหนดค่าก่อนหน้าสำหรับคีย์ที่ขัดแย้งกันเท่านั้น การตั้งค่าที่ไม่ขัดแย้งจากการกำหนดค่าทั้งหมดจะยังคงอยู่ ตัวอย่างเช่น หากการกำหนดค่าส่วนกลางของคุณตั้งค่า `autoupdate: true` และการกำหนดค่าโปรเจ็กต์ของคุณตั้งค่า `model: "anthropic/claude-sonnet-4-5"` การกำหนดค่าสุดท้ายจะรวมการตั้งค่าทั้งสองรายการไว้ด้วย * * * ### [ลำดับความสำคัญ](https://opencode.ai/docs/th/config#%E0%B8%A5%E0%B8%B3%E0%B8%94%E0%B8%B1%E0%B8%9A%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%AA%E0%B8%B3%E0%B8%84%E0%B8%B1%E0%B8%8D) แหล่งที่มาของการกำหนดค่าถูกโหลดตามลำดับนี้ (แหล่งที่มาภายหลังจะแทนที่แหล่งที่มาก่อนหน้า): 1. **การกำหนดค่าระยะไกล** (จาก `.well-known/opencode`) - ค่าเริ่มต้นขององค์กร 2. **การกำหนดค่าสากล** (`~/.config/opencode/opencode.json`) - การตั้งค่าของผู้ใช้ 3. **การกำหนดค่าแบบกำหนดเอง** (`OPENCODE_CONFIG` env var) - การแทนที่แบบกำหนดเอง 4. **การกำหนดค่าโครงการ** (`opencode.json` ในโครงการ) - การตั้งค่าเฉพาะโครงการ 5. **`.opencode` ไดเรกทอรี** - ตัวแทน คำสั่ง ปลั๊กอิน 6. **การกำหนดค่าแบบอินไลน์** (`OPENCODE_CONFIG_CONTENT` env var) - การแทนที่รันไทม์ ซึ่งหมายความว่าการกำหนดค่าโปรเจ็กต์สามารถแทนที่ค่าเริ่มต้นส่วนกลางได้ และการกำหนดค่าส่วนกลางสามารถแทนที่ค่าเริ่มต้นขององค์กรระยะไกลได้ * * * ### [ระยะไกล](https://opencode.ai/docs/th/config#%E0%B8%A3%E0%B8%B0%E0%B8%A2%E0%B8%B0%E0%B9%84%E0%B8%81%E0%B8%A5) องค์กรสามารถจัดเตรียมการกำหนดค่าเริ่มต้นผ่านทางจุดสิ้นสุด `.well-known/opencode` สิ่งนี้จะถูกดึงออกมาโดยอัตโนมัติเมื่อคุณตรวจสอบสิทธิ์กับผู้ให้บริการที่รองรับ โหลดการกำหนดค่าระยะไกลก่อน โดยทำหน้าที่เป็นเลเยอร์พื้นฐาน แหล่งการกำหนดค่าอื่นๆ ทั้งหมด (ส่วนกลาง โปรเจ็กต์) สามารถแทนที่ค่าเริ่มต้นเหล่านี้ได้ ตัวอย่างเช่น หากองค์กรของคุณมีเซิร์ฟเวอร์ MCP ที่ถูกปิดใช้งานตามค่าเริ่มต้น: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} คุณสามารถเปิดใช้งานเซิร์ฟเวอร์เฉพาะในการกำหนดค่าภายในเครื่องของคุณได้: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [ทั่วโลก](https://opencode.ai/docs/th/config#%E0%B8%97%E0%B8%B1%E0%B9%88%E0%B8%A7%E0%B9%82%E0%B8%A5%E0%B8%81) วางการกำหนดค่า OpenCode ส่วนกลางของคุณใน `~/.config/opencode/opencode.json` ใช้การกำหนดค่าส่วนกลางสำหรับการตั้งค่าทั้งผู้ใช้ เช่น ผู้ให้บริการ รุ่น และสิทธิ์ สำหรับการตั้งค่าเฉพาะ TUI ให้ใช้ `~/.config/opencode/tui.json` การกำหนดค่าส่วนกลางจะแทนที่ค่าเริ่มต้นขององค์กรระยะไกล * * * ### [ต่อโครงการ](https://opencode.ai/docs/th/config#%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B9%82%E0%B8%84%E0%B8%A3%E0%B8%87%E0%B8%81%E0%B8%B2%E0%B8%A3) เพิ่ม `opencode.json` ในรูทโปรเจ็กต์ของคุณ การกำหนดค่าโปรเจ็กต์มีความสำคัญสูงสุดในบรรดาไฟล์กำหนดค่ามาตรฐาน โดยจะแทนที่การกำหนดค่าทั้งส่วนกลางและระยะไกล สำหรับการตั้งค่า TUI เฉพาะโครงการ ให้เพิ่ม `tui.json` ควบคู่ไปกับมัน เมื่อ OpenCode เริ่มต้นระบบ จะค้นหาไฟล์กำหนดค่าในไดเร็กทอรีปัจจุบันหรือข้ามไปยังไดเร็กทอรี Git ที่ใกล้ที่สุด นอกจากนี้ยังปลอดภัยที่จะตรวจสอบใน Git และใช้สคีมาเดียวกันกับสคีมาระดับโลก * * * ### [เส้นทางที่กำหนดเอง](https://opencode.ai/docs/th/config#%E0%B9%80%E0%B8%AA%E0%B9%89%E0%B8%99%E0%B8%97%E0%B8%B2%E0%B8%87%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) ระบุเส้นทางไฟล์กำหนดค่าที่กำหนดเองโดยใช้ตัวแปรสภาพแวดล้อม `OPENCODE_CONFIG` export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" มีการโหลดการกำหนดค่าแบบกำหนดเองระหว่างการกำหนดค่าส่วนกลางและโครงการตามลำดับความสำคัญ * * * ### [ไดเรกทอรีที่กำหนดเอง](https://opencode.ai/docs/th/config#%E0%B9%84%E0%B8%94%E0%B9%80%E0%B8%A3%E0%B8%81%E0%B8%97%E0%B8%AD%E0%B8%A3%E0%B8%B5%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) ระบุไดเร็กทอรีการกำหนดค่าที่กำหนดเองโดยใช้ `OPENCODE_CONFIG_DIR` ตัวแปรสภาพแวดล้อม ไดเร็กทอรีนี้จะถูกค้นหาตัวแทน, คำสั่ง, โหมดและปลั๊กอินเหมือนกับไดเร็กทอรี `.opencode` มาตรฐานและควร เป็นไปตามโครงสร้างเดียวกัน export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" ไดเร็กทอรีที่กำหนดเองถูกโหลดหลังจากไดเร็กทอรี config ส่วนกลางและ `.opencode` ดังนั้นจึง **สามารถแทนที่** การตั้งค่าได้ * * * [สคีมา](https://opencode.ai/docs/th/config#%E0%B8%AA%E0%B8%84%E0%B8%B5%E0%B8%A1%E0%B8%B2) ------------------------------------------------------------------------------------------ ไฟล์กำหนดค่ามีสคีมาที่กำหนดไว้ใน [**`opencode.ai/config.json`**](https://opencode.ai/config.json) การกำหนดค่า TUI ใช้ [**`opencode.ai/tui.json`**](https://opencode.ai/tui.json) ผู้แก้ไขของคุณควรสามารถตรวจสอบและเติมข้อความอัตโนมัติตามสคีมาได้ * * * ### [TUI](https://opencode.ai/docs/th/config#tui) ใช้ไฟล์ `tui.json` (หรือ `tui.jsonc`) เฉพาะสำหรับการตั้งค่าเฉพาะ TUI { "$schema": "https://opencode.ai/tui.json", "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} ใช้ `OPENCODE_TUI_CONFIG` เพื่อชี้ไปยังไฟล์กำหนดค่า TUI ที่กำหนดเอง คีย์ `theme`, `keybinds` และ `tui` แบบเดิมใน `opencode.json` เลิกใช้แล้วและจะถูกย้ายโดยอัตโนมัติเมื่อเป็นไปได้ [เรียนรู้เพิ่มเติมเกี่ยวกับการใช้ TUI ที่นี่](https://opencode.ai/docs/tui#configure) * * * ### [เซิร์ฟเวอร์](https://opencode.ai/docs/th/config#%E0%B9%80%E0%B8%8B%E0%B8%B4%E0%B8%A3%E0%B9%8C%E0%B8%9F%E0%B9%80%E0%B8%A7%E0%B8%AD%E0%B8%A3%E0%B9%8C) คุณสามารถกำหนดการตั้งค่าเซิร์ฟเวอร์สำหรับคำสั่ง `opencode serve` และ `opencode web` ผ่านตัวเลือก `server` { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} ตัวเลือกที่มี: * `port` - ​​พอร์ตสำหรับฟัง * `hostname` - ​​ชื่อโฮสต์ที่จะฟัง เมื่อเปิดใช้งาน `mdns` และไม่ได้ตั้งชื่อโฮสต์ ค่าเริ่มต้นจะเป็น `0.0.0.0` * `mdns` - ​​เปิดใช้งานการค้นหาบริการ mDNS ซึ่งช่วยให้อุปกรณ์อื่นๆ บนเครือข่ายค้นพบเซิร์ฟเวอร์ OpenCode ของคุณได้ * `mdnsDomain` - ​​ชื่อโดเมนที่กำหนดเองสำหรับบริการ mDNS ค่าเริ่มต้นเป็น `opencode.local` มีประโยชน์สำหรับการเรียกใช้หลายอินสแตนซ์บนเครือข่ายเดียวกัน * `cors` - ​​ต้นกำเนิดเพิ่มเติมเพื่ออนุญาต CORS เมื่อใช้เซิร์ฟเวอร์ HTTP จากไคลเอนต์ที่ใช้เบราว์เซอร์ ค่าจะต้องเป็นต้นกำเนิดแบบเต็ม (สคีมา + โฮสต์ + พอร์ตเสริม) เช่น `https://app.example.com` [เรียนรู้เพิ่มเติมเกี่ยวกับเซิร์ฟเวอร์ที่นี่](https://opencode.ai/docs/server) * * * ### [เครื่องมือ](https://opencode.ai/docs/th/config#%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD) คุณสามารถจัดการเครื่องมือที่ LLM สามารถใช้ได้ผ่านตัวเลือก `tools` { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [เรียนรู้เพิ่มเติมเกี่ยวกับเครื่องมือที่นี่](https://opencode.ai/docs/tools) * * * ### [Models](https://opencode.ai/docs/th/config#models) คุณสามารถกำหนดค่าผู้ให้บริการและรุ่นที่คุณต้องการใช้ในการกำหนดค่า OpenCode ของคุณได้ผ่านตัวเลือก `provider`, `model` และ `small_model` { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} ตัวเลือก `small_model` จะกำหนดค่าโมเดลแยกต่างหากสำหรับงานที่ไม่ซับซ้อน เช่น การสร้างชื่อเรื่อง ตามค่าเริ่มต้น OpenCode จะพยายามใช้โมเดลที่ถูกกว่าหากมีให้บริการจากผู้ให้บริการของคุณ ไม่เช่นนั้นโมเดลจะกลับไปเป็นโมเดลหลักของคุณ ตัวเลือกผู้ให้บริการอาจรวมถึง `timeout` และ `setCacheKey`: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - ​​คำขอหมดเวลาเป็นมิลลิวินาที (ค่าเริ่มต้น: 300000) ตั้งค่าเป็น `false` เพื่อปิดใช้งาน * `setCacheKey` - ​​ตรวจสอบให้แน่ใจว่าได้ตั้งค่าคีย์แคชสำหรับผู้ให้บริการที่กำหนดเสมอ คุณยังสามารถกำหนดค่า [รุ่นท้องถิ่น](https://opencode.ai/docs/models#local) ได้ [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/models) * * * #### [ตัวเลือกเฉพาะของผู้ให้บริการ](https://opencode.ai/docs/th/config#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81%E0%B9%80%E0%B8%89%E0%B8%9E%E0%B8%B2%E0%B8%B0%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%9C%E0%B8%B9%E0%B9%89%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3) ผู้ให้บริการบางรายรองรับตัวเลือกการกำหนดค่าเพิ่มเติมนอกเหนือจากการตั้งค่า `timeout` และ `apiKey` ทั่วไป ##### [Amazon Bedrock](https://opencode.ai/docs/th/config#amazon-bedrock) Amazon Bedrock รองรับ AWS-การกำหนดค่าเฉพาะ: { "$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 ภูมิภาคสำหรับ Bedrock (ค่าเริ่มต้นเป็น `AWS_REGION` env var หรือ `us-east-1`) * `profile` - ​​AWS ตั้งชื่อโปรไฟล์จาก `~/.aws/credentials` (ค่าเริ่มต้นเป็น `AWS_PROFILE` env var) * `endpoint` - ​​จุดสิ้นสุดที่กำหนดเอง URL สำหรับจุดสิ้นสุด VPC นี่เป็นนามแฝงสำหรับตัวเลือก `baseURL` ทั่วไปโดยใช้คำศัพท์เฉพาะ AWS หากระบุทั้งสองรายการ `endpoint` จะมีความสำคัญกว่า [เรียนรู้เพิ่มเติมเกี่ยวกับการกำหนดค่า Amazon Bedrock](https://opencode.ai/docs/providers#amazon-bedrock) * * * ### [Themes](https://opencode.ai/docs/th/config#themes) ตั้งค่าธีม UI ของคุณใน `tui.json` { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} [เรียนรู้เพิ่มเติมที่นี่](https://opencode.ai/docs/themes) * * * ### [Agents](https://opencode.ai/docs/th/config#agents) คุณสามารถกำหนดค่าตัวแทนเฉพาะสำหรับงานเฉพาะผ่านตัวเลือก `agent` { "$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, }, }, },} คุณยังสามารถกำหนดตัวแทนโดยใช้ไฟล์ Markdown ใน `~/.config/opencode/agents/` หรือ `.opencode/agents/` [เรียนรู้เพิ่มเติมที่นี่](https://opencode.ai/docs/agents) * * * ### [Default Agent](https://opencode.ai/docs/th/config#default-agent) คุณสามารถตั้งค่าตัวแทนเริ่มต้นได้โดยใช้ตัวเลือก `default_agent` ซึ่งจะกำหนดว่าเอเจนต์ใดที่จะใช้เมื่อไม่มีการระบุอย่างชัดเจน { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} ตัวแทนเริ่มต้นจะต้องเป็นตัวแทนหลัก (ไม่ใช่ตัวแทนย่อย) ซึ่งอาจเป็นตัวแทนในตัว เช่น `"build"` หรือ `"plan"` หรือ [ตัวแทนที่กำหนดเอง](https://opencode.ai/docs/agents) ที่คุณกำหนดไว้ หากไม่มีตัวแทนที่ระบุหรือเป็นตัวแทนย่อย OpenCode จะถอยกลับไปที่ `"build"` พร้อมคำเตือน การตั้งค่านี้ใช้กับอินเทอร์เฟซทั้งหมด: TUI, CLI (`opencode run`) แอปเดสก์ท็อป และ GitHub Action * * * ### [Sharing](https://opencode.ai/docs/th/config#sharing) คุณสามารถกำหนดค่าคุณสมบัติ [แบ่งปัน](https://opencode.ai/docs/share) ได้ผ่านทางตัวเลือก `share` { "$schema": "https://opencode.ai/config.json", "share": "manual"} ใช้เวลา: * `"manual"` - ​​อนุญาตให้แชร์ด้วยตนเองผ่านคำสั่ง (ค่าเริ่มต้น) * `"auto"` - ​​แบ่งปันการสนทนาใหม่โดยอัตโนมัติ * `"disabled"` - ​​ปิดการใช้งานการแชร์ทั้งหมด ตามค่าเริ่มต้น การแชร์จะถูกตั้งค่าเป็นโหมดกำหนดเอง ซึ่งคุณต้องแชร์การสนทนาอย่างชัดเจนโดยใช้คำสั่ง `/share` * * * ### [คำสั่ง](https://opencode.ai/docs/th/config#%E0%B8%84%E0%B8%B3%E0%B8%AA%E0%B8%B1%E0%B9%88%E0%B8%87) คุณสามารถกำหนดค่าคำสั่งที่กำหนดเองสำหรับงานซ้ำๆ ได้ผ่านตัวเลือก `command` { "$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", }, },} คุณยังสามารถกำหนดคำสั่งโดยใช้ไฟล์ Markdown ใน `~/.config/opencode/commands/` หรือ `.opencode/commands/` [เรียนรู้เพิ่มเติมที่นี่](https://opencode.ai/docs/commands) * * * ### [คีย์ลัด](https://opencode.ai/docs/th/config#%E0%B8%84%E0%B8%B5%E0%B8%A2%E0%B9%8C%E0%B8%A5%E0%B8%B1%E0%B8%94) ปรับแต่งปุ่มลัดใน `tui.json` { "$schema": "https://opencode.ai/tui.json", "keybinds": {}} [เรียนรู้เพิ่มเติมที่นี่](https://opencode.ai/docs/keybinds) * * * ### [อัปเดตอัตโนมัติ](https://opencode.ai/docs/th/config#%E0%B8%AD%E0%B8%B1%E0%B8%9B%E0%B9%80%E0%B8%94%E0%B8%95%E0%B8%AD%E0%B8%B1%E0%B8%95%E0%B9%82%E0%B8%99%E0%B8%A1%E0%B8%B1%E0%B8%95%E0%B8%B4) OpenCode จะดาวน์โหลดการอัปเดตใหม่โดยอัตโนมัติเมื่อเริ่มต้นระบบ คุณสามารถปิดการใช้งานนี้ได้โดยใช้ตัวเลือก `autoupdate` { "$schema": "https://opencode.ai/config.json", "autoupdate": false} หากคุณไม่ต้องการการอัปเดตแต่ต้องการรับการแจ้งเตือนเมื่อมีเวอร์ชันใหม่ ให้ตั้งค่า `autoupdate` เป็น `"notify"` โปรดสังเกตว่าสิ่งนี้ใช้ได้เฉพาะเมื่อไม่ได้ติดตั้งโดยใช้ตัวจัดการแพ็คเกจเช่น Homebrew * * * ### [ตัวจัดรูปแบบ](https://opencode.ai/docs/th/config#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%88%E0%B8%B1%E0%B8%94%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B9%81%E0%B8%9A%E0%B8%9A) คุณสามารถกำหนดค่าตัวจัดรูปแบบโค้ดผ่านตัวเลือก `formatter` { "$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"] } }} [เรียนรู้เพิ่มเติมเกี่ยวกับฟอร์แมตเตอร์ที่นี่](https://opencode.ai/docs/formatters) * * * ### [การอนุญาต](https://opencode.ai/docs/th/config#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AD%E0%B8%99%E0%B8%B8%E0%B8%8D%E0%B8%B2%E0%B8%95) ตามค่าเริ่มต้น opencode **อนุญาตการดำเนินการทั้งหมด** โดยไม่ต้องมีการอนุมัติอย่างชัดเจน คุณสามารถเปลี่ยนสิ่งนี้ได้โดยใช้ตัวเลือก `permission` ตัวอย่างเช่น เพื่อให้แน่ใจว่าเครื่องมือ `edit` และ `bash` ต้องได้รับการอนุมัติจากผู้ใช้: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [เรียนรู้เพิ่มเติมเกี่ยวกับการอนุญาตที่นี่](https://opencode.ai/docs/permissions) * * * ### [การบีบอัด](https://opencode.ai/docs/th/config#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9A%E0%B8%B5%E0%B8%9A%E0%B8%AD%E0%B8%B1%E0%B8%94) คุณสามารถควบคุมลักษณะการทำงานของการบีบอัดบริบทได้โดยใช้ตัวเลือก `compaction` { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - ​​กระชับเซสชันโดยอัตโนมัติเมื่อบริบทเต็ม (ค่าเริ่มต้น: `true`) * `prune` - ​​ลบเอาท์พุตเครื่องมือเก่าเพื่อบันทึก tokens (ค่าเริ่มต้น: `true`) * `reserved` - บัฟเฟอร์โทเค็นสำหรับการบีบอัด ให้หน้าต่างเพียงพอเพื่อหลีกเลี่ยงการล้นระหว่างการบีบอัด * * * ### [ตัวเฝ้าดู](https://opencode.ai/docs/th/config#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%9D%E0%B9%89%E0%B8%B2%E0%B8%94%E0%B8%B9) คุณสามารถกำหนดค่ารูปแบบการละเว้นตัวเฝ้าดูไฟล์ได้ผ่านตัวเลือก `watcher` { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} รูปแบบเป็นไปตามไวยากรณ์ glob ใช้ตัวเลือกนี้เพื่อยกเว้นไดเร็กทอรีที่มีเสียงดังจากการดูไฟล์ * * * ### [MCP Servers](https://opencode.ai/docs/th/config#mcp-servers) คุณสามารถกำหนดค่าเซิร์ฟเวอร์ MCP ที่คุณต้องการใช้ผ่านตัวเลือก `mcp` { "$schema": "https://opencode.ai/config.json", "mcp": {}} [เรียนรู้เพิ่มเติมที่นี่](https://opencode.ai/docs/mcp-servers) * * * ### [ปลั๊กอิน](https://opencode.ai/docs/th/config#%E0%B8%9B%E0%B8%A5%E0%B8%B1%E0%B9%8A%E0%B8%81%E0%B8%AD%E0%B8%B4%E0%B8%99) [ปลั๊กอิน](https://opencode.ai/docs/plugins) ขยาย OpenCode ด้วยเครื่องมือที่กำหนดเอง hooks และการผสานรวม วางไฟล์ปลั๊กอินใน `.opencode/plugins/` หรือ `~/.config/opencode/plugins/` คุณยังสามารถโหลดปลั๊กอินจาก npm ผ่านตัวเลือก `plugin` { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [เรียนรู้เพิ่มเติมที่นี่](https://opencode.ai/docs/plugins) * * * ### [คำแนะนำ](https://opencode.ai/docs/th/config#%E0%B8%84%E0%B8%B3%E0%B9%81%E0%B8%99%E0%B8%B0%E0%B8%99%E0%B8%B3) คุณสามารถกำหนดค่าคำแนะนำสำหรับรุ่นที่คุณใช้ผ่านตัวเลือก `instructions` { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} สิ่งนี้จะนำอาร์เรย์ของเส้นทางและรูปแบบ glob ไปยังไฟล์คำสั่ง [เรียนรู้เพิ่มเติม เกี่ยวกับกฎที่นี่](https://opencode.ai/docs/rules) * * * ### [Disabled Providers](https://opencode.ai/docs/th/config#disabled-providers) คุณสามารถปิดการใช้งานผู้ให้บริการที่โหลดโดยอัตโนมัติผ่านตัวเลือก `disabled_providers` สิ่งนี้มีประโยชน์เมื่อคุณต้องการป้องกันไม่ให้โหลดผู้ให้บริการบางรายแม้ว่าจะมีข้อมูลประจำตัวอยู่ก็ตาม { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} ตัวเลือก `disabled_providers` ยอมรับอาร์เรย์ของรหัสผู้ให้บริการ เมื่อผู้ให้บริการถูกปิดใช้งาน: * มันจะไม่ถูกโหลดแม้ว่าจะมีการตั้งค่าตัวแปรสภาพแวดล้อมก็ตาม * มันจะไม่ถูกโหลดแม้ว่าจะมีการกำหนดค่าคีย์ API ผ่านคำสั่ง `/connect` * รุ่นของผู้ให้บริการจะไม่ปรากฏในรายการการเลือกรุ่น * * * ### [Enabled Providers](https://opencode.ai/docs/th/config#enabled-providers) คุณสามารถระบุรายชื่อผู้ให้บริการที่อนุญาตได้ผ่านตัวเลือก `enabled_providers` เมื่อตั้งค่าแล้ว เฉพาะผู้ให้บริการที่ระบุเท่านั้นที่จะเปิดใช้งาน และผู้ให้บริการอื่นๆ ทั้งหมดจะถูกละเว้น { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} สิ่งนี้มีประโยชน์เมื่อคุณต้องการจำกัด OpenCode ให้ใช้เฉพาะผู้ให้บริการบางราย แทนที่จะปิดการใช้งานทีละราย หากผู้ให้บริการปรากฏทั้ง `enabled_providers` และ `disabled_providers` `disabled_providers` จะมีลำดับความสำคัญสำหรับความเข้ากันได้แบบย้อนหลัง * * * ### [ขั้นทดลอง](https://opencode.ai/docs/th/config#%E0%B8%82%E0%B8%B1%E0%B9%89%E0%B8%99%E0%B8%97%E0%B8%94%E0%B8%A5%E0%B8%AD%E0%B8%87) ปุ่ม `experimental` มีตัวเลือกที่อยู่ระหว่างการพัฒนา { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [ตัวแปร](https://opencode.ai/docs/th/config#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%9B%E0%B8%A3) ---------------------------------------------------------------------------------------------------- คุณสามารถใช้การทดแทนตัวแปรในไฟล์กำหนดค่าของคุณเพื่ออ้างอิงตัวแปรสภาพแวดล้อมและเนื้อหาไฟล์ได้ * * * ### [ตัวแปร Env](https://opencode.ai/docs/th/config#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%9B%E0%B8%A3-env) ใช้ `{env:VARIABLE_NAME}` เพื่อทดแทนตัวแปรสภาพแวดล้อม: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} หากไม่ได้ตั้งค่าตัวแปรสภาพแวดล้อม ตัวแปรนั้นจะถูกแทนที่ด้วยสตริงว่าง * * * ### [ไฟล์](https://opencode.ai/docs/th/config#%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C) ใช้ `{file:path/to/file}` เพื่อทดแทนเนื้อหาของไฟล์: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} เส้นทางไฟล์อาจเป็น: * สัมพันธ์กับไดเร็กทอรีไฟล์ปรับแต่ง * หรือเส้นทางที่แน่นอนเริ่มต้นด้วย `/` หรือ `~` สิ่งเหล่านี้มีประโยชน์สำหรับ: * เก็บข้อมูลที่ละเอียดอ่อนเช่นคีย์ API ไว้ในไฟล์แยกกัน * รวมไฟล์คำสั่งขนาดใหญ่โดยไม่ทำให้การกำหนดค่าของคุณเกะกะ * การแชร์ข้อมูลโค้ดการกำหนดค่าทั่วไปในไฟล์กำหนดค่าหลายไฟล์ --- # Zen | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/zen#_top) Zen === Kuratierte Modellliste direkt von OpenCode. OpenCode Zen ist eine vom OpenCode-Team getestete und verifizierte Modellliste. Zen funktioniert wie jeder andere Provider in OpenCode. Du meldest dich bei OpenCode Zen an, holst dir deinen API-Key und nutzt ihn optional. * * * [Hintergrund](https://opencode.ai/docs/de/zen#hintergrund) ----------------------------------------------------------- Es gibt sehr viele Modelle, aber nur ein Teil davon eignet sich wirklich gut als Coding-Agent. Ausserdem konfigurieren Provider Modelle sehr unterschiedlich, was die Qualitaet stark beeinflusst. Wenn du Modelle ueber Gateways wie OpenRouter nutzt, ist oft unklar, ob du die beste Ausfuehrung eines Modells bekommst. Um das zu verbessern, haben wir: 1. Eine Auswahl an Modellen getestet und mit den Teams ueber optimale Laufzeit-Setups gesprochen 2. Mit Providern zusammengearbeitet, damit diese Modelle korrekt ausgeliefert werden 3. Modell/Provider-Kombinationen gebenchmarkt und eine empfehlenswerte Liste erstellt OpenCode Zen ist ein AI-Gateway, das dir Zugriff auf genau diese Modelle gibt. * * * [Funktionsweise](https://opencode.ai/docs/de/zen#funktionsweise) ----------------------------------------------------------------- OpenCode Zen funktioniert wie jeder andere Provider in OpenCode. 1. Melde dich bei **[OpenCode Zen](https://opencode.ai/auth) ** an, hinterlege Zahlungsdaten und kopiere deinen API-Key. 2. Fuehre in der TUI `/connect` aus, waehle OpenCode Zen und fuege den API-Key ein. 3. Starte `/models` in der TUI, um empfohlene Modelle zu sehen. Abgerechnet wird pro Anfrage, Guthaben kannst du jederzeit aufladen. * * * [Endpunkte](https://opencode.ai/docs/de/zen#endpunkte) ------------------------------------------------------- Du kannst unsere Modelle auch ueber die folgenden API-Endpunkte aufrufen. | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | Die [Model-ID](https://opencode.ai/docs/config/#models) in deiner OpenCode-Konfiguration hat das Format `opencode/`. Fuer GPT 5.2 Codex verwendest du zum Beispiel `opencode/gpt-5.2-codex`. * * * ### [Models](https://opencode.ai/docs/de/zen#models) Die komplette Liste verfuegbarer Modelle inklusive Metadaten findest du unter: https://opencode.ai/zen/v1/models * * * [Preisgestaltung](https://opencode.ai/docs/de/zen#preisgestaltung) ------------------------------------------------------------------- Wir nutzen ein Pay-as-you-go-Modell. Unten siehst du die Preise **pro 1 Mio. Tokens**. | Model | Input | Output | Cached Read | Cached Write | | --- | --- | --- | --- | --- | | Big Pickle | Free | Free | Free | \- | | MiniMax M2.5 Free | Free | Free | Free | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | $0.375 | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Free | Free | Free | \- | In deinem Verlauf siehst du eventuell _Claude Haiku 3.5_. Das ist ein [guenstiges Modell](https://opencode.ai/docs/config/#models) , das fuer Session-Titel verwendet wird. Die kostenlosen Modelle: * MiniMax M2.5 Free ist fuer begrenzte Zeit auf OpenCode verfuegbar. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern. * Big Pickle ist ein Stealth-Modell, das fuer begrenzte Zeit kostenlos auf OpenCode verfuegbar ist. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern. Wenn du Fragen hast, [kontaktiere uns](mailto:contact@anoma.ly) . * * * ### [Auto-reload](https://opencode.ai/docs/de/zen#auto-reload) Wenn dein Guthaben unter $5 faellt, laedt Zen automatisch $20 nach. Du kannst den Betrag anpassen oder Auto-Reload komplett deaktivieren. * * * ### [Monatslimits](https://opencode.ai/docs/de/zen#monatslimits) Du kannst monatliche Limits fuer den gesamten Workspace und pro Teammitglied festlegen. Wenn du z. B. ein Monatslimit von $20 setzt, verbraucht Zen nicht mehr als $20 pro Monat. Mit aktiviertem Auto-Reload kann die Abrechnung dennoch darueber liegen, falls das Guthaben unter $5 sinkt. * * * ### [Veraltete Modelle](https://opencode.ai/docs/de/zen#veraltete-modelle) | Model | Datum der Abschaltung | | --- | --- | | Qwen3 Coder 480B | 6\. Feb. 2026 | | Kimi K2 Thinking | 6\. Maerz 2026 | | Kimi K2 | 6\. Maerz 2026 | | MiniMax M2.1 | 15\. Maerz 2026 | | GLM 4.7 | 15\. Maerz 2026 | | GLM 4.6 | 15\. Maerz 2026 | * * * [Datenschutz](https://opencode.ai/docs/de/zen#datenschutz) ----------------------------------------------------------- Alle Modelle werden in den USA gehostet. Unsere Provider arbeiten grundsaetzlich mit Zero-Retention und nutzen deine Daten nicht zum Training, mit folgenden Ausnahmen: * Big Pickle: Waehrend der kostenlosen Phase koennen gesammelte Daten zur Verbesserung des Modells genutzt werden. * MiniMax M2.5 Free: Waehrend der kostenlosen Phase koennen gesammelte Daten zur Verbesserung des Modells genutzt werden. * OpenAI APIs: Anfragen werden fuer 30 Tage gemaess [OpenAI’s Data Policies](https://platform.openai.com/docs/guides/your-data) aufbewahrt. * Anthropic APIs: Anfragen werden fuer 30 Tage gemaess [Anthropic’s Data Policies](https://docs.anthropic.com/en/docs/claude-code/data-usage) aufbewahrt. * * * [Für Teams](https://opencode.ai/docs/de/zen#f%C3%BCr-teams) ------------------------------------------------------------ Zen eignet sich auch gut fuer Teams. Du kannst Mitglieder einladen, Rollen vergeben und den Modellzugriff fuer dein Team steuern. Workspace-Verwaltung ist in der Beta kostenlos. Details zur spaeteren Preisgestaltung folgen. * * * ### [Rollen](https://opencode.ai/docs/de/zen#rollen) Du kannst Teammitglieder einladen und Rollen vergeben: * **Admin**: Verwalten Modelle, Mitglieder, API-Keys und Abrechnung * **Member**: Verwalten nur eigene API-Keys Admins koennen zusaetzlich monatliche Ausgabenlimits pro Mitglied setzen. * * * ### [Modellzugriff](https://opencode.ai/docs/de/zen#modellzugriff) Admins koennen einzelne Modelle fuer den Workspace aktivieren oder deaktivieren. Anfragen an deaktivierte Modelle liefern einen Fehler. Das ist hilfreich, wenn bestimmte datenverarbeitende Modelle ausgeschlossen werden sollen. * * * ### [Eigenen Key mitbringen](https://opencode.ai/docs/de/zen#eigenen-key-mitbringen) Du kannst eigene OpenAI- oder Anthropic-API-Keys verwenden und trotzdem andere Zen-Modelle nutzen. Bei eigenen Keys erfolgt die Token-Abrechnung direkt ueber den Provider, nicht ueber Zen. Zum Beispiel hat deine Organisation vielleicht bereits einen Key fuer OpenAI oder Anthropic und du moechtest diesen anstelle des von Zen bereitgestellten nutzen. * * * [Ziele](https://opencode.ai/docs/de/zen#ziele) ----------------------------------------------- Wir haben OpenCode Zen entwickelt, um: 1. Die besten Modell/Provider-Kombinationen fuer Coding-Agenten zu **benchmarken** 2. Stets **hohe Qualitaet** ohne Downgrades oder versteckte Umleitungen auf billigere Provider zu liefern 3. **Preissenkungen** zum Selbstkostenpreis weiterzugeben, mit Aufschlag nur fuer Zahlungsgebuehren 4. **Kein Lock-in** zu erzwingen, damit du Zen mit anderen Coding-Agents und OpenCode weiter mit anderen Providern nutzen kannst --- # เซิร์ฟเวอร์ | OpenCode [Skip to content](https://opencode.ai/docs/th/server#_top) เซิร์ฟเวอร์ =========== โต้ตอบกับเซิร์ฟเวอร์ opencode ผ่าน HTTP คำสั่ง `opencode serve` รันเซิร์ฟเวอร์ HTTP ที่ไม่มีหัวซึ่งเปิดเผยตำแหน่งข้อมูล OpenAPI ที่ไคลเอนต์ opencode สามารถใช้ได้ * * * ### [การใช้งาน](https://opencode.ai/docs/th/server#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99) opencode serve [--port ] [--hostname ] [--cors ] #### [ตัวเลือก](https://opencode.ai/docs/th/server#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81) | Flag | คำอธิบาย | ค่าเริ่มต้น | | --- | --- | --- | | `--port` | พอร์ตที่จะฟัง | `4096` | | `--hostname` | ชื่อโฮสต์ที่จะฟัง | `127.0.0.1` | | `--mdns` | เปิดใช้งานการค้นพบ mDNS | `false` | | `--mdns-domain` | ชื่อโดเมนที่กำหนดเองสำหรับบริการ mDNS | `opencode.local` | | `--cors` | ต้นกำเนิดเบราว์เซอร์เพิ่มเติมที่จะอนุญาต | `[]` | `--cors` สามารถส่งผ่านได้หลายครั้ง: opencode serve --cors http://localhost:5173 --cors https://app.example.com * * * ### [การรับรองความถูกต้อง](https://opencode.ai/docs/th/server#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%96%E0%B8%B9%E0%B8%81%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87) ตั้งค่า `OPENCODE_SERVER_PASSWORD` เพื่อปกป้องเซิร์ฟเวอร์ด้วย HTTP การตรวจสอบสิทธิ์ขั้นพื้นฐาน ชื่อผู้ใช้มีค่าเริ่มต้นเป็น `opencode` หรือตั้งค่า `OPENCODE_SERVER_USERNAME` เพื่อแทนที่ชื่อผู้ใช้ สิ่งนี้ใช้ได้กับทั้ง `opencode serve` และ `opencode web` OPENCODE_SERVER_PASSWORD=your-password opencode serve * * * ### [มันทำงานอย่างไร](https://opencode.ai/docs/th/server#%E0%B8%A1%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B9%84%E0%B8%A3) เมื่อคุณรัน `opencode` มันจะเริ่มต้น TUI และเซิร์ฟเวอร์ โดยที่ TUI คือ ลูกค้าที่พูดคุยกับเซิร์ฟเวอร์ เซิร์ฟเวอร์เปิดเผยข้อมูลจำเพาะของ OpenAPI 3.1 จุดสิ้นสุด ตำแหน่งข้อมูลนี้ยังใช้เพื่อสร้าง [SDK](https://opencode.ai/docs/sdk) สถาปัตยกรรมนี้ช่วยให้ opencode รองรับไคลเอนต์หลายตัว และช่วยให้คุณสามารถโต้ตอบกับ opencode โดยทางโปรแกรมได้ คุณสามารถเรียกใช้ `opencode serve` เพื่อเริ่มเซิร์ฟเวอร์แบบสแตนด์อโลน ถ้าคุณมี opencode TUI ทำงาน `opencode serve` จะเริ่มเซิร์ฟเวอร์ใหม่ * * * #### [เชื่อมต่อกับเซิร์ฟเวอร์ที่มีอยู่](https://opencode.ai/docs/th/server#%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B9%80%E0%B8%8B%E0%B8%B4%E0%B8%A3%E0%B9%8C%E0%B8%9F%E0%B9%80%E0%B8%A7%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%A1%E0%B8%B5%E0%B8%AD%E0%B8%A2%E0%B8%B9%E0%B9%88) เมื่อคุณเริ่ม TUI มันจะสุ่มกำหนดพอร์ตและชื่อโฮสต์ คุณสามารถผ่าน `--hostname` และ `--port` [ธง](https://opencode.ai/docs/cli) แทนได้ จากนั้นใช้สิ่งนี้เพื่อเชื่อมต่อกับเซิร์ฟเวอร์ ตำแหน่งข้อมูล [`/tui`](https://opencode.ai/docs/th/server#tui) สามารถใช้เพื่อขับเคลื่อน TUI ผ่านเซิร์ฟเวอร์ ตัวอย่างเช่น คุณสามารถกรอกข้อมูลล่วงหน้าหรือเรียกใช้พร้อมท์ได้ การตั้งค่านี้ถูกใช้โดยปลั๊กอิน OpenCode [IDE](https://opencode.ai/docs/ide) * * * [ข้อมูลจำเพาะ](https://opencode.ai/docs/th/server#%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5%E0%B8%88%E0%B8%B3%E0%B9%80%E0%B8%9E%E0%B8%B2%E0%B8%B0) ---------------------------------------------------------------------------------------------------------------------------------------------------------------- เซิร์ฟเวอร์เผยแพร่ข้อมูลจำเพาะ OpenAPI 3.1 ที่สามารถดูได้ที่: http://:/doc ตัวอย่างเช่น `http://localhost:4096/doc` ใช้ข้อมูลจำเพาะเพื่อสร้างไคลเอ็นต์หรือตรวจสอบคำขอและประเภทการตอบกลับ หรือดูใน Swagger explorer * * * [API](https://opencode.ai/docs/th/server#api) ---------------------------------------------- เซิร์ฟเวอร์ opencode เปิดเผย API ต่อไปนี้ * * * ### [ทั่วโลก](https://opencode.ai/docs/th/server#%E0%B8%97%E0%B8%B1%E0%B9%88%E0%B8%A7%E0%B9%82%E0%B8%A5%E0%B8%81) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/global/health` | รับสถานะและเวอร์ชันของเซิร์ฟเวอร์ | `{ healthy: true, version: string }` | | `GET` | `/global/event` | รับกิจกรรมระดับโลก (SSE สตรีม) | สตรีมกิจกรรม | * * * ### [โครงการ](https://opencode.ai/docs/th/server#%E0%B9%82%E0%B8%84%E0%B8%A3%E0%B8%87%E0%B8%81%E0%B8%B2%E0%B8%A3) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/project` | แสดงรายการโครงการทั้งหมด | [`Project[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/project/current` | รับโครงการปัจจุบัน | [`Project`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [เส้นทาง & VCS](https://opencode.ai/docs/th/server#%E0%B9%80%E0%B8%AA%E0%B9%89%E0%B8%99%E0%B8%97%E0%B8%B2%E0%B8%87--vcs) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/path` | รับเส้นทางปัจจุบัน | [`Path`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/vcs` | รับข้อมูล VCS สำหรับโครงการปัจจุบัน | [`VcsInfo`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [ตัวอย่าง](https://opencode.ai/docs/th/server#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `POST` | `/instance/dispose` | กำจัดอินสแตนซ์ปัจจุบัน | `boolean` | * * * ### [การกำหนดค่า](https://opencode.ai/docs/th/server#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/config` | รับข้อมูลการกำหนดค่า | [`กำหนดค่า`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `PATCH` | `/config` | อัปเดตการกำหนดค่า | [`กำหนดค่า`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/config/providers` | ผู้ให้บริการรายชื่อและโมเดลเริ่มต้น | `{ providers:` [ผู้ให้บริการ\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: { [key: string]: string } }` | * * * ### [ผู้ให้บริการ](https://opencode.ai/docs/th/server#%E0%B8%9C%E0%B8%B9%E0%B9%89%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/provider` | รายชื่อผู้ให้บริการทั้งหมด | `{ all:` [ผู้ให้บริการ\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, default: {...}, connected: string[] }` | | `GET` | `/provider/auth` | รับวิธีการตรวจสอบความถูกต้องของผู้ให้บริการ | `{ [providerID: string]:` [ProviderAuthMethod\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/provider/{id}/oauth/authorize` | ให้สิทธิ์ผู้ให้บริการโดยใช้ OAuth | [`การอนุญาตของผู้ให้บริการ`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/provider/{id}/oauth/callback` | จัดการการโทรกลับ OAuth สำหรับผู้ให้บริการ | `boolean` | * * * ### [เซสชัน](https://opencode.ai/docs/th/server#%E0%B9%80%E0%B8%8B%E0%B8%AA%E0%B8%8A%E0%B8%B1%E0%B8%99) | Method | เส้นทาง | คำอธิบาย | หมายเหตุ | | --- | --- | --- | --- | | `GET` | `/session` | แสดงรายการเซสชันทั้งหมด | ส่งคืน [`เซสชัน[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session` | สร้างเซสชันใหม่ | body: `{ parentID?, title? }` ส่งคืน [`เซสชัน`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/status` | รับสถานะเซสชันสำหรับเซสชันทั้งหมด | ส่งคืน `{ [sessionID: string]:` [SessionStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id` | รับรายละเอียดเซสชั่น | ส่งคืน [`เซสชัน`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id` | ลบเซสชันและข้อมูลทั้งหมด | ส่งคืน `boolean` | | `PATCH` | `/session/:id` | อัปเดตคุณสมบัติเซสชัน | body: `{ title? }` ส่งคืน [`เซสชัน`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/children` | รับเซสชันย่อยของเซสชัน | ส่งคืน [`เซสชัน[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/todo` | รับรายการสิ่งที่ต้องทำสำหรับเซสชัน | ส่งคืน [`สิ่งที่ต้องทำ[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/init` | วิเคราะห์แอปและสร้าง `AGENTS.md` | เนื้อความ: `{ messageID, providerID, modelID }` ส่งคืน `boolean` | | `POST` | `/session/:id/fork` | แยกเซสชันที่มีอยู่ไปที่ข้อความ | body: `{ messageID? }` ส่งคืน [`เซสชัน`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/abort` | ยกเลิกเซสชันที่ทำงานอยู่ | ส่งคืน `boolean` | | `POST` | `/session/:id/share` | แบ่งปันเซสชั่น | ส่งคืน [`เซสชัน`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `DELETE` | `/session/:id/share` | ยกเลิกการแชร์เซสชัน | ส่งคืน [`เซสชัน`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/session/:id/diff` | รับความแตกต่างสำหรับเซสชั่นนี้ | ข้อความค้นหา: `messageID?` ส่งคืน [`FileDiff[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `POST` | `/session/:id/summarize` | สรุปเซสชัน | เนื้อความ: `{ providerID, modelID }` ส่งคืน `boolean` | | `POST` | `/session/:id/revert` | คืนค่าข้อความ | เนื้อความ: `{ messageID, partID? }` ส่งคืน `boolean` | | `POST` | `/session/:id/unrevert` | กู้คืนข้อความที่เปลี่ยนกลับทั้งหมด | ส่งคืน `boolean` | | `POST` | `/session/:id/permissions/:permissionID` | ตอบสนองต่อการร้องขอการอนุญาต | เนื้อความ: `{ response, remember? }` ส่งคืน `boolean` | * * * ### [ข้อความ](https://opencode.ai/docs/th/server#%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1) | Method | เส้นทาง | คำอธิบาย | หมายเหตุ | | --- | --- | --- | --- | | `GET` | `/session/:id/message` | แสดงรายการข้อความในเซสชัน | ข้อความค้นหา: `limit?` ส่งคืน `{ info:` [ข้อความ](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [ส่วน\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}[]` | | `POST` | `/session/:id/message` | ส่งข้อความและรอการตอบกลับ | เนื้อความ: `{ messageID?, model?, agent?, noReply?, system?, tools?, parts }` ส่งคืน `{ info:` [ข้อความ](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [ส่วน\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `GET` | `/session/:id/message/:messageID` | รับรายละเอียดข้อความ | ส่งคืน `{ info:` [ข้อความ](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [ส่วนหนึ่ง\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/prompt_async` | ส่งข้อความแบบอะซิงโครนัส (ไม่ต้องรอ) | เนื้อความ: เหมือนกับ `/session/:id/message` ส่งคืน `204 No Content` | | `POST` | `/session/:id/command` | ดำเนินการคำสั่งเครื่องหมายทับ | เนื้อความ: `{ messageID?, agent?, model?, command, arguments }` ส่งคืน `{ info:` [ข้อความ](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [ส่วน\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/session/:id/shell` | รันคำสั่ง shell | เนื้อความ: `{ agent, model?, command }` ส่งคืน `{ info:` [ข้อความ](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`, parts:` [ส่วน\[\]](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | * * * ### [คำสั่ง](https://opencode.ai/docs/th/server#%E0%B8%84%E0%B8%B3%E0%B8%AA%E0%B8%B1%E0%B9%88%E0%B8%87) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/command` | แสดงรายการคำสั่งทั้งหมด | [`Command[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [ไฟล์](https://opencode.ai/docs/th/server#%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/find?pattern=` | ค้นหาข้อความในไฟล์ | อาร์เรย์ของวัตถุที่ตรงกับ `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | | `GET` | `/find/file?query=` | ค้นหาไฟล์และไดเร็กทอรีตามชื่อ | `string[]` (paths) | | `GET` | `/find/symbol?query=` | ค้นหาสัญลักษณ์พื้นที่ทำงาน | [`Symbol[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file?path=` | แสดงรายการไฟล์และไดเร็กทอรี | [`FileNode[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/content?path=

` | อ่านไฟล์ | [`เนื้อหาไฟล์`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/file/status` | รับสถานะสำหรับไฟล์ที่ถูกติดตาม | [`File[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | #### [`/find/file` พารามิเตอร์การสืบค้น](https://opencode.ai/docs/th/server#findfile-%E0%B8%9E%E0%B8%B2%E0%B8%A3%E0%B8%B2%E0%B8%A1%E0%B8%B4%E0%B9%80%E0%B8%95%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AA%E0%B8%B7%E0%B8%9A%E0%B8%84%E0%B9%89%E0%B8%99) * `query` (จำเป็น) — สตริงการค้นหา (การจับคู่แบบคลุมเครือ) * `type` (ไม่บังคับ) — จำกัดผลลัพธ์ไว้ที่ `"file"` หรือ `"directory"` * `directory` (เป็นทางเลือก) — แทนที่รูทโปรเจ็กต์สำหรับการค้นหา * `limit` (ไม่บังคับ) — ผลลัพธ์สูงสุด (1–200) * `dirs` (ไม่บังคับ) — แฟล็กดั้งเดิม (`"false"` ส่งคืนเฉพาะไฟล์) * * * ### [เครื่องมือ (ขั้นทดลอง)](https://opencode.ai/docs/th/server#%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD-%E0%B8%82%E0%B8%B1%E0%B9%89%E0%B8%99%E0%B8%97%E0%B8%94%E0%B8%A5%E0%B8%AD%E0%B8%87) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/experimental/tool/ids` | แสดงรายการรหัสเครื่องมือทั้งหมด | [`รหัสเครื่องมือ`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/experimental/tool?provider=

&model=` | แสดงรายการเครื่องมือที่มีสกีมา JSON สำหรับโมเดล | [`รายการเครื่องมือ`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [LSP, ฟอร์แมตเตอร์ & MCP](https://opencode.ai/docs/th/server#lsp-%E0%B8%9F%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B9%81%E0%B8%A1%E0%B8%95%E0%B9%80%E0%B8%95%E0%B8%AD%E0%B8%A3%E0%B9%8C--mcp) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/lsp` | รับ LSP สถานะเซิร์ฟเวอร์ | [`LSPStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/formatter` | รับสถานะฟอร์แมตเตอร์ | [`FormatterStatus[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | | `GET` | `/mcp` | รับ MCP สถานะเซิร์ฟเวอร์ | `{ [name: string]:` [MCPStatus](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts)
`}` | | `POST` | `/mcp` | เพิ่มเซิร์ฟเวอร์ MCP แบบไดนามิก | body: `{ name, config }` ส่งคืนออบเจ็กต์สถานะ MCP | * * * ### [ตัวแทน](https://opencode.ai/docs/th/server#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%97%E0%B8%99) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/agent` | รายชื่อตัวแทนที่มีอยู่ทั้งหมด | [`ตัวแทน[]`](https://github.com/anomalyco/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts) | * * * ### [การบันทึก](https://opencode.ai/docs/th/server#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9A%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B6%E0%B8%81) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `POST` | `/log` | เขียนรายการบันทึก เนื้อความ: `{ service, level, message, extra? }` | `boolean` | * * * ### [TUI](https://opencode.ai/docs/th/server#tui) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `POST` | `/tui/append-prompt` | เพิ่มข้อความต่อท้ายข้อความแจ้ง | `boolean` | | `POST` | `/tui/open-help` | เปิดกล่องโต้ตอบความช่วยเหลือ | `boolean` | | `POST` | `/tui/open-sessions` | เปิดตัวเลือกเซสชัน | `boolean` | | `POST` | `/tui/open-themes` | เปิดตัวเลือกธีม | `boolean` | | `POST` | `/tui/open-models` | เปิดตัวเลือกรุ่น | `boolean` | | `POST` | `/tui/submit-prompt` | ส่งข้อความแจ้งปัจจุบัน | `boolean` | | `POST` | `/tui/clear-prompt` | ล้างข้อความแจ้ง | `boolean` | | `POST` | `/tui/execute-command` | ดำเนินการคำสั่ง (`{ command }`) | `boolean` | | `POST` | `/tui/show-toast` | โชว์ขนมปังปิ้ง (`{ title?, message, variant }`) | `boolean` | | `GET` | `/tui/control/next` | รอคำขอควบคุมถัดไป | วัตถุคำขอควบคุม | | `POST` | `/tui/control/response` | ตอบสนองต่อคำขอควบคุม (`{ body }`) | `boolean` | * * * ### [การรับรองความถูกต้อง](https://opencode.ai/docs/th/server#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%96%E0%B8%B9%E0%B8%81%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87-1) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `PUT` | `/auth/:id` | ตั้งค่าข้อมูลประจำตัวการรับรองความถูกต้อง เนื้อความต้องตรงกับสคีมาของผู้ให้บริการ | `boolean` | * * * ### [กิจกรรม](https://opencode.ai/docs/th/server#%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%81%E0%B8%A3%E0%B8%A3%E0%B8%A1) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/event` | สตรีมเหตุการณ์ที่เซิร์ฟเวอร์ส่ง งานแรกคือ `server.connected` จากนั้นงานรถบัส | สตรีมเหตุการณ์ที่เซิร์ฟเวอร์ส่ง | * * * ### [เอกสาร](https://opencode.ai/docs/th/server#%E0%B9%80%E0%B8%AD%E0%B8%81%E0%B8%AA%E0%B8%B2%E0%B8%A3) | Method | เส้นทาง | คำอธิบาย | การตอบสนอง | | --- | --- | --- | --- | | `GET` | `/doc` | ข้อมูลจำเพาะของ OpenAPI 3.1 | HTML หน้าพร้อมข้อมูลจำเพาะ OpenAPI | --- # IDE | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/ide#_top) IDE === 适用于 VS Code、Cursor 及其他 IDE 的 OpenCode 扩展 OpenCode 可与 VS Code、Cursor 或任何支持终端的 IDE 集成。只需在终端中运行 `opencode` 即可开始使用。 * * * [用法](https://opencode.ai/docs/zh-cn/ide#%E7%94%A8%E6%B3%95) ------------------------------------------------------------ * **快速启动**:使用 `Cmd+Esc`(Mac)或 `Ctrl+Esc`(Windows/Linux)在分屏终端视图中打开 OpenCode,如果已有终端会话正在运行,则会自动聚焦到该会话。 * **新建会话**:使用 `Cmd+Shift+Esc`(Mac)或 `Ctrl+Shift+Esc`(Windows/Linux)启动新的 OpenCode 终端会话,即使已有会话在运行也会新建。你也可以点击界面中的 OpenCode 按钮。 * **上下文感知**:自动将当前选中内容或标签页共享给 OpenCode。 * **文件引用快捷键**:使用 `Cmd+Option+K`(Mac)或 `Alt+Ctrl+K`(Linux/Windows)插入文件引用。例如 `@File#L37-42`。 * * * [安装](https://opencode.ai/docs/zh-cn/ide#%E5%AE%89%E8%A3%85) ------------------------------------------------------------ 在 VS Code 及其常见分支(如 Cursor、Windsurf、VSCodium)上安装 OpenCode: 1. 打开 VS Code 2. 打开集成终端 3. 运行 `opencode`——扩展将自动安装 如果你希望在 TUI 中执行 `/editor` 或 `/export` 时使用自己的 IDE,需要设置 `export EDITOR="code --wait"`。[了解更多](https://opencode.ai/docs/tui/#editor-setup) 。 * * * ### [手动安装](https://opencode.ai/docs/zh-cn/ide#%E6%89%8B%E5%8A%A8%E5%AE%89%E8%A3%85) 在扩展商店中搜索 **OpenCode**,然后点击 **Install**。 * * * ### [故障排除](https://opencode.ai/docs/zh-cn/ide#%E6%95%85%E9%9A%9C%E6%8E%92%E9%99%A4) 如果扩展未能自动安装: * 确保你是在集成终端中运行的 `opencode`。 * 确认你的 IDE 对应的 CLI 命令已安装: * VS Code:`code` 命令 * Cursor:`cursor` 命令 * Windsurf:`windsurf` 命令 * VSCodium:`codium` 命令 * 如果未安装,请按 `Cmd+Shift+P`(Mac)或 `Ctrl+Shift+P`(Windows/Linux),搜索 “Shell Command: Install ‘code’ command in PATH”(或你的 IDE 对应的命令) * 确保 VS Code 有权限安装扩展 --- # Zen | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/zen#_top) Zen === 由 OpenCode 提供的精选模型列表。 OpenCode Zen 是由 OpenCode 团队提供的一组经过测试和验证的模型列表。 Zen 的工作方式与 OpenCode 中的任何其他提供商相同。你只需登录 OpenCode Zen 并获取你的 API 密钥。它是**完全可选的**,你无需使用它也能正常使用 OpenCode。 * * * [背景](https://opencode.ai/docs/zh-cn/zen#%E8%83%8C%E6%99%AF) ------------------------------------------------------------ 市面上有大量的模型,但其中只有少数能够很好地充当编码代理。此外,大多数提供商的配置方式差异很大,因此你获得的性能和质量也会截然不同。 所以如果你通过 OpenRouter 之类的服务使用模型,你永远无法确定是否获得了你想要的模型的最佳版本。 为了解决这个问题,我们做了以下几件事: 1. 我们测试了一组精选的模型,并与它们的团队讨论了最佳运行方式。 2. 然后我们与几家提供商合作,确保这些模型能被正确地提供服务。 3. 最后,我们对模型与提供商的组合进行了基准测试,整理出了一份我们有信心推荐的列表。 OpenCode Zen 是一个 AI 网关,让你可以访问这些模型。 * * * [工作原理](https://opencode.ai/docs/zh-cn/zen#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) -------------------------------------------------------------------------------- OpenCode Zen 的工作方式与 OpenCode 中的任何其他提供商相同。 1. 登录 **[OpenCode Zen](https://opencode.ai/auth) **,添加你的账单信息,然后复制你的 API 密钥。 2. 在 TUI 中运行 `/connect` 命令,选择 OpenCode Zen,然后粘贴你的 API 密钥。 3. 在 TUI 中运行 `/models` 查看我们推荐的模型列表。 你按请求付费,并且可以向你的账户中充值。 * * * [端点](https://opencode.ai/docs/zh-cn/zen#%E7%AB%AF%E7%82%B9) ------------------------------------------------------------ 你还可以通过以下 API 端点访问我们的模型。 | 模型 | 模型 ID | 端点 | AI SDK 包 | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | 在 OpenCode 配置中,[模型 ID](https://opencode.ai/docs/config/#models) 使用 `opencode/` 格式。例如,对于 GPT 5.2 Codex,你需要在配置中使用 `opencode/gpt-5.2-codex`。 * * * ### [模型](https://opencode.ai/docs/zh-cn/zen#%E6%A8%A1%E5%9E%8B) 你可以从以下地址获取可用模型及其元数据的完整列表: https://opencode.ai/zen/v1/models * * * [定价](https://opencode.ai/docs/zh-cn/zen#%E5%AE%9A%E4%BB%B7) ------------------------------------------------------------ 我们支持按量付费模式。以下是**每 100 万 Token** 的价格。 | 模型 | 输入 | 输出 | 缓存读取 | 缓存写入 | | --- | --- | --- | --- | --- | | Big Pickle | 免费 | 免费 | 免费 | \- | | MiniMax M2.5 Free | 免费 | 免费 | 免费 | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | 免费 | 免费 | 免费 | \- | 你可能会在使用记录中看到 _Claude Haiku 3.5_。这是一个[低成本模型](https://opencode.ai/docs/config/#models) ,用于生成会话标题。 免费模型说明: * MiniMax M2.5 Free 在 OpenCode 上限时免费提供。团队正在利用这段时间收集反馈并改进模型。 * Big Pickle 是一个隐身模型,在 OpenCode 上限时免费提供。团队正在利用这段时间收集反馈并改进模型。 如有任何疑问,请[联系我们](mailto:contact@anoma.ly) 。 * * * ### [自动充值](https://opencode.ai/docs/zh-cn/zen#%E8%87%AA%E5%8A%A8%E5%85%85%E5%80%BC) 如果你的余额低于 $5,Zen 将自动充值 $20。 你可以更改自动充值的金额,也可以完全禁用自动充值功能。 * * * ### [月度限额](https://opencode.ai/docs/zh-cn/zen#%E6%9C%88%E5%BA%A6%E9%99%90%E9%A2%9D) 你还可以为整个工作区以及团队中的每个成员设置月度使用限额。 例如,假设你将月度使用限额设为 $20,Zen 在一个月内的使用量将不会超过 $20。但如果你启用了自动充值,当余额低于 $5 时,Zen 可能会向你收取超过 $20 的费用。 * * * ### [已弃用模型](https://opencode.ai/docs/zh-cn/zen#%E5%B7%B2%E5%BC%83%E7%94%A8%E6%A8%A1%E5%9E%8B) | 模型 | 弃用日期 | | --- | --- | | Qwen3 Coder 480B | 2026 年 2 月 6 日 | | Kimi K2 Thinking | 2026 年 3 月 6 日 | | Kimi K2 | 2026 年 3 月 6 日 | | MiniMax M2.1 | 2026 年 3 月 15 日 | | GLM 4.7 | 2026 年 3 月 15 日 | | GLM 4.6 | 2026 年 3 月 15 日 | * * * [隐私](https://opencode.ai/docs/zh-cn/zen#%E9%9A%90%E7%A7%81) ------------------------------------------------------------ 我们所有的模型都托管在美国。我们的提供商遵循零保留政策,不会将你的数据用于模型训练,但以下情况除外: * Big Pickle:在免费期间,收集的数据可能会被用于改进模型。 * MiniMax M2.5 Free:在免费期间,收集的数据可能会被用于改进模型。 * OpenAI API:请求会根据 [OpenAI 数据政策](https://platform.openai.com/docs/guides/your-data) 保留 30 天。 * Anthropic API:请求会根据 [Anthropic 数据政策](https://docs.anthropic.com/en/docs/claude-code/data-usage) 保留 30 天。 * * * [团队版](https://opencode.ai/docs/zh-cn/zen#%E5%9B%A2%E9%98%9F%E7%89%88) ---------------------------------------------------------------------- Zen 也非常适合团队使用。你可以邀请队友、分配角色、管理团队使用的模型等。 作为测试版的一部分,管理工作区目前对团队免费。我们将很快公布更多定价详情。 * * * ### [角色](https://opencode.ai/docs/zh-cn/zen#%E8%A7%92%E8%89%B2) 你可以邀请团队成员加入你的工作区并分配角色: * **管理员**:管理模型、成员、API 密钥和账单 * **成员**:仅管理自己的 API 密钥 管理员还可以为每个成员设置月度支出限额,以控制成本。 * * * ### [模型访问](https://opencode.ai/docs/zh-cn/zen#%E6%A8%A1%E5%9E%8B%E8%AE%BF%E9%97%AE) 管理员可以启用或禁用工作区中的特定模型。对已禁用模型发出的请求将返回错误。 这在你想要禁用某个会收集数据的模型时非常有用。 * * * ### [自带密钥](https://opencode.ai/docs/zh-cn/zen#%E8%87%AA%E5%B8%A6%E5%AF%86%E9%92%A5) 你可以使用自己的 OpenAI 或 Anthropic API 密钥,同时仍然可以访问 Zen 中的其他模型。 当你使用自己的密钥时,Token 费用由提供商直接计费,而非通过 Zen 计费。 例如,你的组织可能已经拥有 OpenAI 或 Anthropic 的密钥,你希望使用它们而不是 Zen 提供的密钥。 * * * [目标](https://opencode.ai/docs/zh-cn/zen#%E7%9B%AE%E6%A0%87) ------------------------------------------------------------ 我们创建 OpenCode Zen 的目的是: 1. 为编码代理**基准测试**最佳的模型和提供商组合。 2. 提供**最高质量**的选项,不降低性能或路由到更廉价的提供商。 3. 以成本价销售来传递任何**降价优惠**;唯一的加价仅用于覆盖我们的处理费用。 4. **无锁定**,允许你将其与任何其他编码代理配合使用,同时也始终允许你在 OpenCode 中使用任何其他提供商。 --- # Zen | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/zen#_top) Zen === 由 OpenCode 提供的精選模型列表。 OpenCode Zen 是由 OpenCode 團隊提供的一組經過測試和驗證的模型列表。 Zen 的工作方式與 OpenCode 中的任何其他供應商相同。你只需登入 OpenCode Zen 並取得你的 API 金鑰。它是**完全選用的**,你無需使用它也能正常使用 OpenCode。 * * * [背景](https://opencode.ai/docs/zh-tw/zen#%E8%83%8C%E6%99%AF) ------------------------------------------------------------ 市面上有大量的模型,但其中只有少數能夠很好地充當編碼代理。此外,大多數供應商的設定方式差異很大,因此你獲得的效能和品質也會截然不同。 所以如果你透過 OpenRouter 之類的服務使用模型,你永遠無法確定是否獲得了你想要的模型的最佳版本。 為了解決這個問題,我們做了以下幾件事: 1. 我們測試了一組精選的模型,並與它們的團隊討論了最佳執行方式。 2. 然後我們與幾家供應商合作,確保這些模型能被正確地提供服務。 3. 最後,我們對模型與供應商的組合進行了基準測試,整理出了一份我們有信心推薦的列表。 OpenCode Zen 是一個 AI 閘道,讓你可以存取這些模型。 * * * [工作原理](https://opencode.ai/docs/zh-tw/zen#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) -------------------------------------------------------------------------------- OpenCode Zen 的工作方式與 OpenCode 中的任何其他供應商相同。 1. 登入 **[OpenCode Zen](https://opencode.ai/auth) **,新增你的帳單資訊,然後複製你的 API 金鑰。 2. 在 TUI 中執行 `/connect` 指令,選擇 OpenCode Zen,然後貼上你的 API 金鑰。 3. 在 TUI 中執行 `/models` 查看我們推薦的模型列表。 你按請求付費,並且可以向你的帳戶中儲值。 * * * [端點](https://opencode.ai/docs/zh-tw/zen#%E7%AB%AF%E9%BB%9E) ------------------------------------------------------------ 你還可以透過以下 API 端點存取我們的模型。 | 模型 | 模型 ID | 端點 | AI SDK 套件 | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | 在 OpenCode 設定中,[模型 ID](https://opencode.ai/docs/config/#models) 使用 `opencode/` 格式。例如,對於 GPT 5.2 Codex,你需要在設定中使用 `opencode/gpt-5.2-codex`。 * * * ### [模型](https://opencode.ai/docs/zh-tw/zen#%E6%A8%A1%E5%9E%8B) 你可以從以下位址取得可用模型及其中繼資料的完整列表: https://opencode.ai/zen/v1/models * * * [定價](https://opencode.ai/docs/zh-tw/zen#%E5%AE%9A%E5%83%B9) ------------------------------------------------------------ 我們支援按量付費模式。以下是**每 100 萬 Token** 的價格。 | 模型 | 輸入 | 輸出 | 快取讀取 | 快取寫入 | | --- | --- | --- | --- | --- | | Big Pickle | 免費 | 免費 | 免費 | \- | | MiniMax M2.5 Free | 免費 | 免費 | 免費 | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K Token) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K Token) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K Token) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K Token) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K Token) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K Token) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K Token) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K Token) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K Token) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K Token) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K Token) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K Token) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | 免費 | 免費 | 免費 | \- | 你可能會在使用記錄中看到 _Claude Haiku 3.5_。這是一個[低成本模型](https://opencode.ai/docs/config/#models) ,用於產生工作階段標題。 免費模型說明: * MiniMax M2.5 Free 在 OpenCode 上限時免費提供。團隊正在利用這段時間收集回饋並改進模型。 * Big Pickle 是一個隱身模型,在 OpenCode 上限時免費提供。團隊正在利用這段時間收集回饋並改進模型。 如有任何疑問,請[聯絡我們](mailto:contact@anoma.ly) 。 * * * ### [自動儲值](https://opencode.ai/docs/zh-tw/zen#%E8%87%AA%E5%8B%95%E5%84%B2%E5%80%BC) 如果你的餘額低於 $5,Zen 將自動儲值 $20。 你可以更改自動儲值的金額,也可以完全停用自動儲值功能。 * * * ### [月度限額](https://opencode.ai/docs/zh-tw/zen#%E6%9C%88%E5%BA%A6%E9%99%90%E9%A1%8D) 你還可以為整個工作區以及團隊中的每個成員設定月度使用限額。 例如,假設你將月度使用限額設為 $20,Zen 在一個月內的使用量將不會超過 $20。但如果你啟用了自動儲值,當餘額低於 $5 時,Zen 可能會向你收取超過 $20 的費用。 * * * ### [已棄用的模型](https://opencode.ai/docs/zh-tw/zen#%E5%B7%B2%E6%A3%84%E7%94%A8%E7%9A%84%E6%A8%A1%E5%9E%8B) | 模型 | 棄用日期 | | --- | --- | | Qwen3 Coder 480B | 2026 年 2 月 6 日 | | Kimi K2 Thinking | 2026 年 3 月 6 日 | | Kimi K2 | 2026 年 3 月 6 日 | | MiniMax M2.1 | 2026 年 3 月 15 日 | | GLM 4.7 | 2026 年 3 月 15 日 | | GLM 4.6 | 2026 年 3 月 15 日 | * * * [隱私](https://opencode.ai/docs/zh-tw/zen#%E9%9A%B1%E7%A7%81) ------------------------------------------------------------ 我們所有的模型都託管在美國。我們的供應商遵循零保留政策,不會將你的資料用於模型訓練,但以下情況除外: * Big Pickle:在免費期間,收集的資料可能會被用於改進模型。 * MiniMax M2.5 Free:在免費期間,收集的資料可能會被用於改進模型。 * OpenAI API:請求會根據 [OpenAI 資料政策](https://platform.openai.com/docs/guides/your-data) 保留 30 天。 * Anthropic API:請求會根據 [Anthropic 資料政策](https://docs.anthropic.com/en/docs/claude-code/data-usage) 保留 30 天。 * * * [團隊版](https://opencode.ai/docs/zh-tw/zen#%E5%9C%98%E9%9A%8A%E7%89%88) ---------------------------------------------------------------------- Zen 也非常適合團隊使用。你可以邀請隊友、分配角色、管理團隊使用的模型等。 作為測試版的一部分,管理工作區目前對團隊免費。我們將很快公布更多定價詳情。 * * * ### [角色](https://opencode.ai/docs/zh-tw/zen#%E8%A7%92%E8%89%B2) 你可以邀請團隊成員加入你的工作區並分配角色: * **管理員**:管理模型、成員、API 金鑰和帳單 * **成員**:僅管理自己的 API 金鑰 管理員還可以為每個成員設定月度支出限額,以控制成本。 * * * ### [模型存取](https://opencode.ai/docs/zh-tw/zen#%E6%A8%A1%E5%9E%8B%E5%AD%98%E5%8F%96) 管理員可以啟用或停用工作區中的特定模型。對已停用模型發出的請求將回傳錯誤。 這在你想要停用某個會收集資料的模型時非常有用。 * * * ### [自帶金鑰](https://opencode.ai/docs/zh-tw/zen#%E8%87%AA%E5%B8%B6%E9%87%91%E9%91%B0) 你可以使用自己的 OpenAI 或 Anthropic API 金鑰,同時仍然可以存取 Zen 中的其他模型。 當你使用自己的金鑰時,Token 費用由供應商直接計費,而非透過 Zen 計費。 例如,你的組織可能已經擁有 OpenAI 或 Anthropic 的金鑰,你希望使用它們而不是 Zen 提供的金鑰。 * * * [目標](https://opencode.ai/docs/zh-tw/zen#%E7%9B%AE%E6%A8%99) ------------------------------------------------------------ 我們建立 OpenCode Zen 的目的是: 1. 為編碼代理**基準測試**最佳的模型和供應商組合。 2. 提供**最高品質**的選項,不降低效能或路由到更廉價的供應商。 3. 以成本價銷售來傳遞任何**降價優惠**;唯一的加價僅用於覆蓋我們的處理費用。 4. **無鎖定**,允許你將其與任何其他編碼代理配合使用,同時也始終允許你在 OpenCode 中使用任何其他供應商。 --- # IDE | OpenCode [Gå til indhold](https://opencode.ai/docs/da/ide#_top) IDE === OpenCode-udvidelsen til VS Code, Cursor og andre IDE'er OpenCode integreres med VS Code, Cursor eller enhver IDE, der understøtter en terminal. Bare kør `opencode` i terminalen for at komme i gang. * * * [Brug](https://opencode.ai/docs/da/ide#brug) --------------------------------------------- * **Hurtig start**: Brug `Cmd+Esc` (Mac) eller `Ctrl+Esc` (Windows/Linux) til at åbne OpenCode i en delt terminalvisning, eller fokuser en eksisterende terminalsession, hvis en allerede kører. * **Ny session**: Brug `Cmd+Shift+Esc` (Mac) eller `Ctrl+Shift+Esc` (Windows/Linux) til at starte en ny OpenCode terminalsession, mulighed en allerede er åben. Du kan også klikke på knappen OpenCode i brugergrænsefladen. * **Kontekstbevidsthed**: Del automatisk dit nuværende valg eller din fane med OpenCode. * **Filreferencegenveje**: Brug `Cmd+Option+K` (Mac) eller `Alt+Ctrl+K` (Linux/Windows) til at indsætte filreferencer. For eksempel `@File#L37-42`. * * * [Installation](https://opencode.ai/docs/da/ide#installation) ------------------------------------------------------------- Sådan installeres OpenCode på VS Code og populære gafler som Cursor, Windsurf, VSCodium: 1. Åbn VS Code 2. Åbn den integrerede terminal 3. Kør `opencode` - udvidelsen installeres automatisk Hvis du på den anden side vil bruge din egen IDE, når du kører `/editor` eller `/export` fra TUI, skal du indstille `export EDITOR="code --wait"`. [Learn more](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Manuel installation](https://opencode.ai/docs/da/ide#manuel-installation) Søg efter **OpenCode** i Extension Marketplace, og klik på **Installer**. * * * ### [Fejlfinding](https://opencode.ai/docs/da/ide#fejlfinding) Hvis udvidelsen ikke kan installeres automatisk: * Sørg for, at du kører `opencode` i den integrerede terminal. * Bekræft, at CLI for din IDE er installeret: * For VS Code: `code` kommando * For Cursor: `cursor` kommando * For Windsurf: `windsurf` kommando * For VSCodium: `codium` kommando * Hvis ikke, så kør `Cmd+Shift+P` (Mac) eller `Ctrl+Shift+P` (Windows/Linux) og søg efter “Shell Command: Install ‘code’ command in PATH” (eller tilsvarende for din IDE) * Sørg for, at VS Code har tilladelse til at installere udvidelser --- # Go | OpenCode [Skip to content](https://opencode.ai/docs/go#_top) Go == Low cost subscription for open coding models. OpenCode Go is a low cost **$10/month** subscription that gives you reliable access to popular open coding models. Go works like any other provider in OpenCode. You subscribe to OpenCode Go and get your API key. It’s **completely optional** and you don’t need to use it to use OpenCode. It is designed primarily for international users, with models hosted in the US, EU, and Singapore for stable global access. * * * [Background](https://opencode.ai/docs/go#background) ----------------------------------------------------- Open models have gotten really good. They now reach performance close to proprietary models for coding tasks. And because many providers can serve them competitively, they are usually far cheaper. However, getting reliable, low latency access to them can be difficult. Providers vary in quality and availability. To fix this, we did a couple of things: 1. We tested a select group of open models and talked to their teams about how to best run them. 2. We then worked with a few providers to make sure these were being served correctly. 3. Finally, we benchmarked the combination of the model/provider and came up with a list that we feel good recommending. OpenCode Go gives you access to these models for **$10/month**. * * * [How it works](https://opencode.ai/docs/go#how-it-works) --------------------------------------------------------- OpenCode Go works like any other provider in OpenCode. 1. You sign in to **[OpenCode Zen](https://opencode.ai/auth) **, subscribe to Go, and copy your API key. 2. You run the `/connect` command in the TUI, select `OpenCode Go`, and paste your API key. 3. Run `/models` in the TUI to see the list of models available through Go. The current list of models includes: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** The list of models may change as we test and add new ones. * * * [Usage limits](https://opencode.ai/docs/go#usage-limits) --------------------------------------------------------- OpenCode Go includes the following limits: * **5 hour limit** — $12 of usage * **Weekly limit** — $30 of usage * **Monthly limit** — $60 of usage Limits are defined in dollar value. This means your actual request count depends on the model you use. Cheaper models like MiniMax M2.5 allow for more requests, while higher-cost models like GLM-5 allow for fewer. The table below provides an estimated request count based on typical Go usage patterns: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | requests per 5 hour | 1,150 | 1,850 | 20,000 | | requests per week | 2,880 | 4,630 | 50,000 | | requests per month | 5,750 | 9,250 | 100,000 | Estimates are based on observed average request patterns: * GLM-5 — 700 input, 52,000 cached, 150 output tokens per request * Kimi K2.5 — 870 input, 55,000 cached, 200 output tokens per request * MiniMax M2.5 — 300 input, 55,000 cached, 125 output tokens per request You can track your current usage in the **[console](https://opencode.ai/auth) **. Usage limits may change as we learn from early usage and feedback. * * * ### [Usage beyond limits](https://opencode.ai/docs/go#usage-beyond-limits) If you also have credits on your Zen balance, you can enable the **Use balance** option in the console. When enabled, Go will fall back to your Zen balance after you’ve reached your usage limits instead of blocking requests. * * * [Endpoints](https://opencode.ai/docs/go#endpoints) --------------------------------------------------- You can also access Go models through the following API endpoints. | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | The [model id](https://opencode.ai/docs/config/#models) in your OpenCode config uses the format `opencode-go/`. For example, for Kimi K2.5, you would use `opencode-go/kimi-k2.5` in your config. * * * [Privacy](https://opencode.ai/docs/go#privacy) ----------------------------------------------- The plan is designed primarily for international users, with models hosted in the US, EU, and Singapore for stable global access. [Contact us](mailto:contact@anoma.ly) if you have any questions. * * * [Goals](https://opencode.ai/docs/go#goals) ------------------------------------------- We created OpenCode Go to: 1. Make AI coding **accessible** to more people with a low cost subscription. 2. Provide **reliable** access to the best open coding models. 3. Curate models that are **tested and benchmarked** for coding agent use. 4. Have **no lock-in** by allowing you to use any other provider with OpenCode as well. --- # IDE | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/ide#_top) IDE === VS Code, Cursor ve diğer IDE'ler için opencode uzantısı opencode, VS Code, Cursor veya bir terminali destekleyen herhangi bir IDE ile entegre olur. Başlamak için terminalde `opencode` komutunu çalıştırmanız yeterli. * * * [Kullanım](https://opencode.ai/docs/tr/ide#kullan%C4%B1m) ---------------------------------------------------------- * **Hızlı Başlatma**: opencode’u bölünmüş terminal görünümünde açmak veya zaten çalışıyorsa mevcut bir terminal oturumuna odaklanmak için `Cmd+Esc` (Mac) veya `Ctrl+Esc` (Windows/Linux) kullanın. * **Yeni Oturum**: Zaten açık olsa bile yeni bir opencode terminal oturumu başlatmak için `Cmd+Shift+Esc` (Mac) veya `Ctrl+Shift+Esc` (Windows/Linux) kullanın. Ayrıca kullanıcı arayüzündeki opencode düğmesini de tıklayabilirsiniz. * **Bağlam Farkındalığı**: Geçerli seçiminizi veya sekmenizi opencode ile otomatik olarak paylaşın. * **Dosya Referansı Kısayolları**: Dosya referansları eklemek için `Cmd+Option+K` (Mac) veya `Alt+Ctrl+K` (Linux/Windows) kullanın. Örneğin, `@File#L37-42`. * * * [Kurulum](https://opencode.ai/docs/tr/ide#kurulum) --------------------------------------------------- opencode’u VS Code’a ve Cursor, Windsurf, VSCodium gibi popüler çatallara yüklemek için: 1. VS Code’u Aç 2. Entegre terminali açın 3. `opencode` komutunu çalıştırın - uzantı otomatik olarak yüklenir TUI içinden `/editor` veya `/export` komutlarını çalıştırdığınızda kendi IDE’nizi kullanmak istiyorsanız `export EDITOR="code --wait"` ayarlayın. [Daha fazla bilgi](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Manuel Kurulum](https://opencode.ai/docs/tr/ide#manuel-kurulum) Extension Marketplace’te **opencode**’u arayın ve **Yükle**’ye tıklayın. * * * ### [Sorun giderme](https://opencode.ai/docs/tr/ide#sorun-giderme) Uzantı otomatik olarak yüklenemezse: * Entegre terminalde `opencode` çalıştırdığınızdan emin olun. * IDE cihazınız için CLI’nin kurulu olduğunu doğrulayın: * VS Code için: `code` komutu * Cursor için: `cursor` komutu * Windsurf için: `windsurf` komutu * VSCodium için: `codium` komutu * Değilse `Cmd+Shift+P` (Mac) veya `Ctrl+Shift+P` (Windows/Linux) çalıştırın ve “Shell Command: Install ‘code’ command in PATH” komutunu seçin (veya IDE’nizdeki eşdeğerini kullanın). * VS Code’un uzantı yükleme iznine sahip olduğundan emin olun --- # Yapılandırma | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/config#_top) Yapılandırma ============ opencode JSON yapılandırması kullanır. opencode’u JSON yapılandırma dosyası kullanarak yapılandırabilirsiniz. * * * [Format](https://opencode.ai/docs/tr/config#format) ---------------------------------------------------- opencode hem **JSON** hem de **JSONC** (JSON Yorumlarla birlikte) formatlarını destekler. { "$schema": "https://opencode.ai/config.json", // Theme configuration "theme": "opencode", "model": "anthropic/claude-sonnet-4-5", "autoupdate": true,} * * * [Konumlar](https://opencode.ai/docs/tr/config#konumlar) -------------------------------------------------------- Yapılandırmanızı birkaç farklı konuma yerleştirebilirsiniz ve bunların farklı öncelik sırası vardır. Yapılandırma dosyaları değiştirilmez, birleştirilir. Aşağıdaki yapılandırma konumlarındaki ayarlar birleştirilir. Daha sonraki yapılandırmalar, yalnızca çakışan anahtarlar için önceki yapılandırmaları geçersiz kılar. Tüm yapılandırmalardaki çakışmayan ayarlar korunur. Örneğin, genel ayarınız `theme: "opencode"` ve `autoupdate: true`’yi ayarlıyorsa ve proje ayarlarınız `model: "anthropic/claude-sonnet-4-5"`’yi ayarlıyorsa, nihai yapılandırma üç ayarı da içerecektir. * * * ### [Öncelik sırası](https://opencode.ai/docs/tr/config#%C3%B6ncelik-s%C4%B1ras%C4%B1) Yapılandırma kaynakları bu sırayla yüklenir (sonraki kaynaklar öncekileri geçersiz kılar): 1. **Uzak yapılandırma** (`.well-known/opencode`’dan) - kurumsal varsayılanlar 2. **Genel yapılandırma** (`~/.config/opencode/opencode.json`) - kullanıcı tercihleri 3. **Özel yapılandırma** (`OPENCODE_CONFIG` env var) - özel geçersiz kılmalar 4. **Proje yapılandırması** (projedeki `opencode.json`) - projeye özgü ayarlar 5. **`.opencode` dizinleri** - agent’lar, komutlar, eklentiler 6. **Satır içi yapılandırma** (`OPENCODE_CONFIG_CONTENT` env var) - çalışma zamanı geçersiz kılmaları Bu, proje yapılandırmalarının genel varsayılanları geçersiz kılabileceği ve genel yapılandırmaların uzak organizasyonel varsayılanları geçersiz kılabileceği anlamına gelir. * * * ### [Uzak](https://opencode.ai/docs/tr/config#uzak) Kuruluşlar, `.well-known/opencode` uç noktası aracılığıyla varsayılan yapılandırmayı sağlayabilir. Bu, onu destekleyen bir sağlayıcıyla kimlik doğrulaması yaptığınızda otomatik olarak alınır. Uzak yapılandırma ilk olarak yüklenir ve temel katman görevi görür. Diğer tüm yapılandırma kaynakları (genel, proje) bu varsayılanları geçersiz kılabilir. Örneğin, kuruluşunuz varsayılan olarak devre dışı bırakılan MCP sunucuları sağlıyorsa: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": false } }} Yerel yapılandırmanızda belirli sunucuları etkinleştirebilirsiniz: { "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} * * * ### [Global](https://opencode.ai/docs/tr/config#global) Global opencode yapılandırmanızı `~/.config/opencode/opencode.json` içine yerleştirin. Temalar, sağlayıcılar veya tuş atamaları gibi kullanıcı çapındaki tercihler için genel yapılandırmayı kullanın. Genel yapılandırma, uzak kurumsal varsayılanları geçersiz kılar. * * * ### [Proje başına](https://opencode.ai/docs/tr/config#proje-ba%C5%9F%C4%B1na) Proje kökünüze `opencode.json` ekleyin. Proje yapılandırması, standart yapılandırma dosyaları arasında en yüksek önceliğe sahiptir; hem genel hem de uzak yapılandırmaları geçersiz kılar. opencode başlatıldığında geçerli dizinde bir yapılandırma dosyası arar veya en yakın Git dizinine gider. Bunun Git’te kontrol edilmesi de güvenlidir ve global olanla aynı şemayı kullanır. * * * ### [Özel yol](https://opencode.ai/docs/tr/config#%C3%B6zel-yol) `OPENCODE_CONFIG` ortam değişkenini kullanarak özel bir yapılandırma dosyası yolu belirtin. export OPENCODE_CONFIG=/path/to/my/custom-config.jsonopencode run "Hello world" Özel yapılandırma genel ve proje yapılandırmaları arasında öncelik sırasına göre yüklenir. * * * ### [Özel dizin](https://opencode.ai/docs/tr/config#%C3%B6zel-dizin) `OPENCODE_CONFIG_DIR` kullanarak özel bir yapılandırma dizini belirtin ortam değişkeni. Bu dizin agent’lar, komutlar için aranacaktır. modlar ve eklentiler tıpkı standart `.opencode` dizini gibi olmalıdır ve aynı yapıyı takip edin. export OPENCODE_CONFIG_DIR=/path/to/my/config-directoryopencode run "Hello world" Özel dizin, genel yapılandırma ve `.opencode` dizinlerinden sonra yüklenir, böylece bunların ayarlarını **geçersiz kılabilir**. * * * [Şema](https://opencode.ai/docs/tr/config#%C5%9Fema) ----------------------------------------------------- Yapılandırma dosyası [**`opencode.ai/config.json`**](https://opencode.ai/config.json) ’da tanımlanan bir şemaya sahiptir. Editörünüz şemaya göre doğrulama ve otomatik tamamlama yapabilmelidir. * * * ### [TUI](https://opencode.ai/docs/tr/config#tui) TUI’ye özgü ayarları `tui` seçeneği aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto" }} Mevcut seçenekler: * `scroll_acceleration.enabled` - MacOS tarzı kaydırma hızlandırmayı etkinleştirin. **`scroll_speed`’ye göre önceliklidir.** * `scroll_speed` - Özel kaydırma hızı çarpanı (varsayılan: `3`, minimum: `1`). `scroll_acceleration.enabled` `true` ise dikkate alınmaz. * `diff_style` - Fark oluşturmayı kontrol edin. `"auto"` terminal genişliğine uyum sağlar, `"stacked"` her zaman tek sütunu gösterir. [TUI kullanımı hakkında daha fazla bilgi](https://opencode.ai/docs/tui) . * * * ### [Sunucu](https://opencode.ai/docs/tr/config#sunucu) `opencode serve` ve `opencode web` komutları için sunucu ayarlarını `server` seçeneği aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "mdnsDomain": "myproject.local", "cors": ["http://localhost:5173"] }} Mevcut seçenekler: * `port` - Dinlenecek port. * `hostname` - Dinlenecek ana bilgisayar adı. `mdns` etkinleştirildiğinde ve hiçbir ana bilgisayar adı ayarlanmadığında, varsayılan değer `0.0.0.0` olur. * `mdns` - mDNS hizmet bulmayı etkinleştirin. Bu, ağdaki diğer cihazların opencode sunucunuzu keşfetmesine olanak tanır. * `mdnsDomain` - mDNS hizmeti için özel alan adı. Varsayılan olarak `opencode.local` şeklindedir. Aynı ağda birden fazla örneği çalıştırmak için kullanışlıdır. * `cors` - Tarayıcı tabanlı bir istemciden HTTP sunucusunu kullanırken CORS’ye izin verecek ek kaynaklar. Değerler tam kaynaklar olmalıdır (şema + ana bilgisayar + isteğe bağlı bağlantı noktası), örneğin `https://app.example.com`. [Sunucu hakkında daha fazla bilgi](https://opencode.ai/docs/server) . * * * ### [Araçlar](https://opencode.ai/docs/tr/config#ara%C3%A7lar) Bir LLM’nin kullanabileceği araçları `tools` seçeneği aracılığıyla yönetebilirsiniz. { "$schema": "https://opencode.ai/config.json", "tools": { "write": false, "bash": false }} [Araçlar hakkında daha fazla bilgi](https://opencode.ai/docs/tools) . * * * ### [Modeller](https://opencode.ai/docs/tr/config#modeller) opencode yapılandırmanızda kullanmak istediğiniz sağlayıcıları ve modelleri `provider`, `model` ve `small_model` seçenekleri aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5"} `small_model` seçeneği, başlık oluşturma gibi hafif görevler için ayrı bir model yapılandırır. Varsayılan olarak opencode, sağlayıcınızda mevcutsa daha ucuz bir model kullanmaya çalışır, aksi takdirde ana modelinize geri döner. Sağlayıcı seçenekleri `timeout` ve `setCacheKey` içerebilir: { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "options": { "timeout": 600000, "setCacheKey": true } } }} * `timeout` - Milisaniye cinsinden istek zaman aşımı (varsayılan: 300000). Devre dışı bırakmak için `false` olarak ayarlayın. * `setCacheKey` - Belirlenen sağlayıcı için her zaman bir önbellek anahtarının ayarlandığından emin olun. Ayrıca [local models](https://opencode.ai/docs/models#local) ayarlayabilirsiniz. [Daha fazla bilgi](https://opencode.ai/docs/models) . * * * #### [Sağlayıcıya Özel Seçenekler](https://opencode.ai/docs/tr/config#sa%C4%9Flay%C4%B1c%C4%B1ya-%C3%B6zel-se%C3%A7enekler) Bazı sağlayıcılar genel `timeout` ve `apiKey` ayarlarının ötesinde ek yapılandırma seçeneklerini destekler. ##### [Amazon Bedrock](https://opencode.ai/docs/tr/config#amazon-bedrock) Amazon Bedrock, AWS’a özgü yapılandırmayı destekler: { "$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` - Bedrock için AWS bölgesi (varsayılanı `AWS_REGION` env var veya `us-east-1`’dir) * `profile` - `~/.aws/credentials`’den AWS adlı profil (varsayılanı `AWS_PROFILE` env var’dır) * `endpoint` - VPC uç noktaları için özel uç nokta URL. Bu, AWS’e özgü terminolojiyi kullanan genel `baseURL` seçeneğinin takma adıdır. Her ikisi de belirtilirse `endpoint` öncelikli olur. [Amazon Bedrock yapılandırması hakkında daha fazla bilgi](https://opencode.ai/docs/providers#amazon-bedrock) . * * * ### [Temalar](https://opencode.ai/docs/tr/config#temalar) opencode yapılandırmanızda kullanmak istediğiniz temayı `theme` seçeneği aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "theme": ""} [Daha fazla bilgi](https://opencode.ai/docs/themes) . * * * ### [Agent’lar](https://opencode.ai/docs/tr/config#agentlar) `agent` seçeneği aracılığıyla özel görevlere yönelik özel agent’ları yapılandırabilirsiniz. { "$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, "bash": true, }, }, },} Agent’ları `~/.config/opencode/agents/` veya `.opencode/agents/` içindeki Markdown dosyalarıyla da tanımlayabilirsiniz. [Daha fazla bilgi](https://opencode.ai/docs/agents) . * * * ### [Varsayılan agent](https://opencode.ai/docs/tr/config#varsay%C4%B1lan-agent) `default_agent` seçeneğini kullanarak varsayılan agent’ı ayarlayabilirsiniz. Bu, hiçbiri açıkça belirtilmediğinde hangi agent’ın kullanılacağını belirler. { "$schema": "https://opencode.ai/config.json", "default_agent": "plan"} Varsayılan agent, birincil agent olmalıdır (alt agent değil). Bu, `"build"` veya `"plan"` gibi yerleşik bir agent ya da tanımladığınız bir [özel agent](https://opencode.ai/docs/agents) olabilir. Belirtilen agent mevcut değilse veya bir alt agent ise, opencode bir uyarıyla birlikte `"build"`’ye geri döner. Bu ayar tüm arayüzler için geçerlidir: TUI, CLI (`opencode run`), masaüstü uygulaması ve GitHub Action. * * * ### [Paylaşma](https://opencode.ai/docs/tr/config#payla%C5%9Fma) [share](https://opencode.ai/docs/share) özelliğini `share` seçeneği aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "share": "manual"} Bu şunları gerektirir: * `"manual"` - Komutlar aracılığıyla manuel paylaşıma izin ver (varsayılan) * `"auto"` - Yeni konuşmaları otomatik olarak paylaş * `"disabled"` - Paylaşımı tamamen devre dışı bırak Varsayılan olarak paylaşım, `/share` komutunu kullanarak konuşmaları açıkça paylaşmanız gereken manuel moda ayarlanmıştır. * * * ### [Komutlar](https://opencode.ai/docs/tr/config#komutlar) `command` seçeneği aracılığıyla tekrarlanan görevler için özel komutlar yapılandırabilirsiniz. { "$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", }, },} Komutları `~/.config/opencode/commands/` veya `.opencode/commands/` içindeki Markdown dosyalarıyla da tanımlayabilirsiniz. [Daha fazla bilgi](https://opencode.ai/docs/commands) . * * * ### [Tuş atamaları](https://opencode.ai/docs/tr/config#tu%C5%9F-atamalar%C4%B1) Tuş atamalarınızı `keybinds` seçeneği aracılığıyla özelleştirebilirsiniz. { "$schema": "https://opencode.ai/config.json", "keybinds": {}} [Daha fazla bilgi](https://opencode.ai/docs/keybinds) . * * * ### [Otomatik Güncelleme](https://opencode.ai/docs/tr/config#otomatik-g%C3%BCncelleme) opencode başlatıldığında yeni güncellemeleri otomatik olarak indirecektir. Bunu `autoupdate` seçeneğiyle devre dışı bırakabilirsiniz. { "$schema": "https://opencode.ai/config.json", "autoupdate": false} Güncelleme istemiyor ancak yeni bir sürüm mevcut olduğunda bilgilendirilmek istiyorsanız `autoupdate` öğesini `"notify"` olarak ayarlayın. Bunun yalnızca Homebrew gibi bir paket yöneticisi kullanılarak yüklenmemişse işe yaradığına dikkat edin. * * * ### [Biçimlendiriciler](https://opencode.ai/docs/tr/config#bi%C3%A7imlendiriciler) Kod formatlayıcılarını `formatter` seçeneği aracılığıyla yapılandırabilirsiniz. { "$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"] } }} [Formatter’lar hakkında daha fazla bilgi](https://opencode.ai/docs/formatters) . * * * ### [İzinler](https://opencode.ai/docs/tr/config#i%CC%87zinler) Varsayılan olarak, opencode açık bir onay gerektirmeden **tüm işlemlere izin verir**. `permission` seçeneğini kullanarak bunu değiştirebilirsiniz. Örneğin, `edit` ve `bash` araçlarının kullanıcı onayı gerektirdiğinden emin olmak için: { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "ask", "bash": "ask" }} [İzinler hakkında daha fazla bilgi](https://opencode.ai/docs/permissions) . * * * ### [Sıkıştırma](https://opencode.ai/docs/tr/config#s%C4%B1k%C4%B1%C5%9Ft%C4%B1rma) Bağlam sıkıştırma davranışını `compaction` seçeneği aracılığıyla kontrol edebilirsiniz. { "$schema": "https://opencode.ai/config.json", "compaction": { "auto": true, "prune": true, "reserved": 10000 }} * `auto` - Bağlam dolduğunda oturumu otomatik olarak sıkıştırır (varsayılan: `true`). * `prune` - Belirteçleri kaydetmek için eski araç çıktılarını kaldırın (varsayılan: `true`). * `reserved` - Sıkıştırma için belirteç tamponu. Sıkıştırma sırasında taşmayı önlemek için yeterli pencere bırakır. * * * ### [İzleyici](https://opencode.ai/docs/tr/config#i%CC%87zleyici) Dosya izleyicinin yok sayma kalıplarını `watcher` seçeneği aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "watcher": { "ignore": ["node_modules/**", "dist/**", ".git/**"] }} Desenler glob sözdizimini takip eder. Gürültülü dizinleri dosya izlemenin dışında bırakmak için bunu kullanın. * * * ### [MCP sunucuları](https://opencode.ai/docs/tr/config#mcp-sunucular%C4%B1) Kullanmak istediğiniz MCP sunucularını `mcp` seçeneği aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "mcp": {}} [Daha fazla bilgi](https://opencode.ai/docs/mcp-servers) . * * * ### [Eklentiler](https://opencode.ai/docs/tr/config#eklentiler) [Eklentiler](https://opencode.ai/docs/plugins) opencode’u özel araçlar, kancalar ve entegrasyonlarla genişletin. Eklenti dosyalarını `.opencode/plugins/` veya `~/.config/opencode/plugins/` içine yerleştirin. Ayrıca eklentileri `plugin` seçeneği aracılığıyla npm’den de yükleyebilirsiniz. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"]} [Daha fazla bilgi](https://opencode.ai/docs/plugins) . * * * ### [Talimatlar](https://opencode.ai/docs/tr/config#talimatlar) Kullandığınız modele ilişkin talimatları `instructions` seçeneği aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Bu, talimat dosyalarına giden bir dizi yolu ve glob desenini alır. [Kurallar hakkında daha fazla bilgiyi buradan edinin](https://opencode.ai/docs/rules) . * * * ### [Devre dışı bırakılan sağlayıcılar](https://opencode.ai/docs/tr/config#devre-d%C4%B1%C5%9F%C4%B1-b%C4%B1rak%C4%B1lan-sa%C4%9Flay%C4%B1c%C4%B1lar) `disabled_providers` seçeneği aracılığıyla otomatik olarak yüklenen sağlayıcıları devre dışı bırakabilirsiniz. Bu, belirli sağlayıcıların kimlik bilgileri mevcut olsa bile yüklenmesini engellemek istediğinizde kullanışlıdır. { "$schema": "https://opencode.ai/config.json", "disabled_providers": ["openai", "gemini"]} `disabled_providers` seçeneği bir dizi sağlayıcı kimliğini kabul eder. Bir sağlayıcı devre dışı bırakıldığında: * Ortam değişkenleri ayarlanmış olsa bile yüklenmez. * API anahtarları `/connect` komutu aracılığıyla yapılandırılsa bile yüklenmeyecektir. * Sağlayıcının modelleri, model seçim listesinde görünmez. * * * ### [Etkin sağlayıcılar](https://opencode.ai/docs/tr/config#etkin-sa%C4%9Flay%C4%B1c%C4%B1lar) `enabled_providers` seçeneğini kullanarak sağlayıcıların izin verilenler listesini belirtebilirsiniz. Ayarlandığında yalnızca belirtilen sağlayıcılar etkinleştirilecek ve diğerleri göz ardı edilecektir. { "$schema": "https://opencode.ai/config.json", "enabled_providers": ["anthropic", "openai"]} Bu, opencode’u tek tek devre dışı bırakmak yerine yalnızca belirli sağlayıcıları kullanacak şekilde kısıtlamak istediğinizde kullanışlıdır. Bir sağlayıcı hem `enabled_providers` hem de `disabled_providers`’de görünüyorsa, geriye dönük uyumluluk için `disabled_providers` önceliğe sahiptir. * * * ### [Deneysel](https://opencode.ai/docs/tr/config#deneysel) `experimental` anahtarı aktif olarak geliştirilmekte olan seçenekleri içerir. { "$schema": "https://opencode.ai/config.json", "experimental": {}} * * * [Değişkenler](https://opencode.ai/docs/tr/config#de%C4%9Fi%C5%9Fkenler) ------------------------------------------------------------------------ Ortam değişkenlerine ve dosya içeriklerine referans vermek için yapılandırma dosyalarınızda değişken değiştirmeyi kullanabilirsiniz. * * * ### [Ortam değişkenleri](https://opencode.ai/docs/tr/config#ortam-de%C4%9Fi%C5%9Fkenleri) Ortam değişkenlerini değiştirmek için `{env:VARIABLE_NAME}` kullanın: { "$schema": "https://opencode.ai/config.json", "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "models": {}, "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } }} Ortam değişkeni ayarlanmamışsa boş bir dizeyle değiştirilecektir. * * * ### [Dosyalar](https://opencode.ai/docs/tr/config#dosyalar) Bir dosyanın biçimini değiştirmek için `{file:path/to/file}` kullanın: { "$schema": "https://opencode.ai/config.json", "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } }} Dosya yolları şunlar olabilir: * Yapılandırma dosyası dizinine göre * Veya `/` veya `~` ile başlayan mutlak yollar Bunlar aşağıdakiler için faydalıdır: * API anahtarları gibi hassas verileri ayrı dosyalarda tutmak. * Yapılandırmanızı karmaşıklaştırmadan büyük talimat dosyaları içerir. * Birden fazla yapılandırma dosyasında ortak yapılandırma parçacıklarının paylaşılması. --- # Zen | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/zen#_top) Zen === Lista seleccionada de modelos proporcionada por OpenCode. OpenCode Zen es una lista de modelos probados y verificados proporcionada por el equipo OpenCode. Zen funciona como cualquier otro proveedor en OpenCode. Inicias sesion en OpenCode Zen y obtienes tu API key. Es **completamente opcional** y no necesitas usarlo para usar OpenCode. * * * [Contexto](https://opencode.ai/docs/es/zen#contexto) ----------------------------------------------------- Hay una gran cantidad de modelos, pero solo unos pocos funcionan bien como agentes de coding. Ademas, la mayoria de proveedores se configura de forma diferente, asi que el rendimiento y la calidad varian mucho. Si usas un modelo a traves de algo como OpenRouter, nunca puedes estar seguro de que recibes la mejor version del modelo que quieres. Para solucionar este problema, hicimos un par de cosas: 1. Probamos un grupo selecto de modelos y hablamos con sus equipos sobre cómo mejor ejecutarlos. 2. Luego trabajamos con algunos proveedores para asegurarnos de que estuvieran siendo atendidos. correctamente. 3. Finalmente, comparamos la combinación modelo/proveedor y llegamos con una lista que nos sentimos bien recomendando. OpenCode Zen es una puerta de enlace de IA que le brinda acceso a estos modelos. * * * [Cómo funciona](https://opencode.ai/docs/es/zen#c%C3%B3mo-funciona) -------------------------------------------------------------------- OpenCode Zen funciona como cualquier otro proveedor en OpenCode. 1. Inicias sesión en **[OpenCode Zen](https://opencode.ai/auth) **, agregas tu facturación detalles y copie su clave API. 2. Ejecuta el comando `/connect` en TUI, selecciona OpenCode Zen y pega tu clave API. 3. Ejecute `/models` en TUI para ver la lista de modelos que recomendamos. Se le cobra por solicitud y puede agregar créditos a su cuenta. * * * [Puntos finales](https://opencode.ai/docs/es/zen#puntos-finales) ----------------------------------------------------------------- También puede acceder a nuestros modelos a través de los siguientes puntos finales API. | Modelo | Model ID | Endpoint | AI SDK package | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | El [model ID](https://opencode.ai/docs/config/#models) en tu configuracion de OpenCode usa el formato `opencode/`. Por ejemplo, para GPT 5.2 Codex, debes usar `opencode/gpt-5.2-codex` en tu configuracion. * * * ### [Modelos](https://opencode.ai/docs/es/zen#modelos) Puede obtener la lista completa de modelos disponibles y sus metadatos en: https://opencode.ai/zen/v1/models * * * [Precios](https://opencode.ai/docs/es/zen#precios) --------------------------------------------------- Apoyamos un modelo de pago por uso. A continuación se muestran los precios **por 1 millón de tokens**. | Modelo | Entrada | Salida | Lectura en caché | Escritura en caché | | --- | --- | --- | --- | --- | | Big Pickle | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 Free | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 | $0,30 | $1,20 | $0,06 | \- | | MiniMax M2.1 | $0,30 | $1,20 | $0,10 | \- | | GLM 5 | $1,00 | $3,20 | $0,20 | \- | | GLM 4.7 | $0,60 | $2.20 | $0,10 | \- | | GLM 4.6 | $0,60 | $2.20 | $0,10 | \- | | Kimi K2.5 | $0,60 | $3.00 | $0,08 | \- | | Kimi K2 Thinking | $0,40 | $2.50 | \- | \- | | Kimi K2 | $0,40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0,45 | $1,50 | \- | \- | | Claude Opus 4.6 (≤ 200.000 tokens) | $5.00 | $25.00 | $0,50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37,50 | $1.00 | $12,50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0,50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1,50 | $18,75 | | Claude Sonnet 4.6 (≤ 200.000 tokens) | $3.00 | $15.00 | $0,30 | $3,75 | | Claude Sonnet 4.6 (> 200.000 tokens) | $6.00 | $22,50 | $0,60 | $7.50 | | Claude Sonnet 4.5 (≤ 200.000 tokens) | $3.00 | $15.00 | $0,30 | $3,75 | | Claude Sonnet 4.5 (> 200.000 tokens) | $6.00 | $22,50 | $0,60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0,30 | $3,75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22,50 | $0,60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0,10 | $1,25 | | Claude Haiku 3.5 | $0,80 | $4.00 | $0,08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0,20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0,40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0,20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0,40 | \- | | Gemini 3 Flash | $0,50 | $3.00 | $0,05 | \- | | GPT 5.4 | $2,50 | $15,00 | $0,25 | \- | | GPT 5.3 Codex | $1,75 | $14.00 | $0,175 | \- | | GPT 5.2 | $1,75 | $14.00 | $0,175 | \- | | GPT 5.2 Codex | $1,75 | $14.00 | $0,175 | \- | | GPT 5.1 | $1.07 | $8,50 | $0,107 | \- | | GPT 5.1 Codex | $1.07 | $8,50 | $0,107 | \- | | GPT 5.1 Codex Max | $1,25 | $10.00 | $0,125 | \- | | GPT 5.1 Codex Mini | $0,25 | $2.00 | $0,025 | \- | | GPT 5 | $1.07 | $8,50 | $0,107 | \- | | GPT 5 Codex | $1.07 | $8,50 | $0,107 | \- | | GPT 5 Nano | Gratis | Gratis | Gratis | \- | Es posible que notes _Claude Haiku 3.5_ en tu historial de uso. Este es un [modelo de bajo costo](https://opencode.ai/docs/config/#models) que se utiliza para generar los títulos de tus sesiones. Los modelos gratuitos: * MiniMax M2.5 Free está disponible en OpenCode por tiempo limitado. El equipo está aprovechando este tiempo para recopilar comentarios y mejorar el modelo. * Big Pickle es un modelo sigiloso gratuito en OpenCode por tiempo limitado. El equipo está aprovechando este tiempo para recopilar comentarios y mejorar el modelo. [Contáctenos](mailto:contact@anoma.ly) si tiene alguna pregunta. * * * ### [Recarga automática](https://opencode.ai/docs/es/zen#recarga-autom%C3%A1tica) Si su saldo es inferior a $5, Zen recargará automáticamente $20. Puedes cambiar el monto de la recarga automática. También puedes desactivar la recarga automática por completo. * * * ### [Límites mensuales](https://opencode.ai/docs/es/zen#l%C3%ADmites-mensuales) También puede establecer un límite de uso mensual para todo el espacio de trabajo y para cada miembro de tu equipo. Por ejemplo, digamos que establece un límite de uso mensual de $20, Zen no usará más de $20 en un mes. Pero si tienes habilitada la recarga automática, Zen podría terminar cobrarle más de $20 si su saldo es inferior a $5. * * * ### [Modelos obsoletos](https://opencode.ai/docs/es/zen#modelos-obsoletos) | Modelo | Fecha de retiro | | --- | --- | | Qwen3 Coder 480B | 6 de feb. de 2026 | | Kimi K2 Thinking | 6 de marzo de 2026 | | Kimi K2 | 6 de marzo de 2026 | | MiniMax M2.1 | 15 de marzo de 2026 | | GLM 4.7 | 15 de marzo de 2026 | | GLM 4.6 | 15 de marzo de 2026 | * * * [Privacidad](https://opencode.ai/docs/es/zen#privacidad) --------------------------------------------------------- Todos nuestros modelos están alojados en los EE. UU. Nuestros proveedores siguen una política de retención cero y no utilizan sus datos para la capacitación de modelos, con las siguientes excepciones: * Big Pickle: Durante su periodo gratuito, los datos recopilados podrán utilizarse para mejorar el modelo. * MiniMax M2.5 Free: Durante su período gratuito, los datos recopilados podrán utilizarse para mejorar el modelo. * API de OpenAI: las solicitudes se conservan durante 30 días de acuerdo con las [Políticas de datos de OpenAI](https://platform.openai.com/docs/guides/your-data) . * API de Anthropic: las solicitudes se conservan durante 30 días de acuerdo con las [Políticas de datos de Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [Para equipos](https://opencode.ai/docs/es/zen#para-equipos) ------------------------------------------------------------- Zen también funciona muy bien para equipos. Puedes invitar a compañeros de equipo, asignar roles, seleccionar los modelos que utiliza su equipo y más. Actualmente, administrar su espacio de trabajo es gratuito para equipos como parte de la versión beta. estaremos compartiremos más detalles sobre los precios pronto. * * * ### [Roles](https://opencode.ai/docs/es/zen#roles) Puedes invitar a compañeros de equipo a tu espacio de trabajo y asignar roles: * **Administrador**: administra modelos, miembros, claves API y facturación * **Miembro**: administra solo sus propias claves API Los administradores también pueden establecer límites de gastos mensuales para cada miembro para mantener los costos bajo control. * * * ### [Acceso al modelo](https://opencode.ai/docs/es/zen#acceso-al-modelo) Los administradores pueden habilitar o deshabilitar modelos específicos para el espacio de trabajo. Las solicitudes realizadas a un modelo deshabilitado devolverán un error. Esto es útil para los casos en los que desea desactivar el uso de un modelo que recopila datos. * * * ### [Trae tu propia clave API](https://opencode.ai/docs/es/zen#trae-tu-propia-clave-api) Puedes usar tus propias API keys de OpenAI o Anthropic mientras accedes a otros modelos en Zen. Cuando utiliza sus propias claves, los tokens los factura directamente el proveedor, no Zen. Por ejemplo, es posible que su organización ya tenga una clave para OpenAI o Anthropic. y quieres usar ese en lugar del que proporciona Zen. * * * [Objetivos](https://opencode.ai/docs/es/zen#objetivos) ------------------------------------------------------- Creamos OpenCode Zen para: 1. **Evaluar** los mejores modelos/proveedores de agentes de codificación. 2. Tener acceso a las opciones de **más alta calidad** y no degradar el rendimiento ni recurrir a proveedores más baratos. 3. Transmitir cualquier **bajada de precio** vendiendo al costo; por lo que el único margen de beneficio es para cubrir nuestras tarifas de procesamiento. 4. **No tener ningún bloqueo** al permitirle usarlo con cualquier otro agente de codificación. Y siempre le permitirá utilizar cualquier otro proveedor con OpenCode también. --- # Zen | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/zen#_top) Zen === Liste organisée de modèles fournis par OpenCode. OpenCode Zen est une liste de modèles testés et vérifiés fournie par l’équipe OpenCode. Zen fonctionne comme n’importe quel autre fournisseur dans OpenCode. Vous vous connectez à OpenCode Zen et obtenez votre clé API. C’est **complètement facultatif** et vous n’avez pas besoin de l’utiliser pour utiliser OpenCode. * * * [Arrière-plan](https://opencode.ai/docs/fr/zen#arri%C3%A8re-plan) ------------------------------------------------------------------ Il existe un grand nombre de modèles, mais seulement quelques-uns d’entre eux fonctionnent bien comme agents de codage. De plus, la plupart des fournisseurs sont configurés très différemment; vous obtenez donc des performances et une qualité très différentes. Donc, si vous utilisez un modèle via quelque chose comme OpenRouter, vous ne pourrez jamais être sûr que vous obtenez la meilleure version du modèle que vous souhaitez. Pour résoudre ce problème, nous avons effectué plusieurs opérations : 1. Nous avons testé un groupe sélectionné de modèles et discuté avec leurs équipes de la manière de mieux les exécuter. 2. Nous avons ensuite travaillé avec quelques prestataires pour nous assurer qu’ils étaient servis correctement. 3. Enfin, nous avons comparé la combinaison modèle/fournisseur et sommes arrivés avec une liste que nous nous ferons un plaisir de recommander. OpenCode Zen est une passerelle IA qui vous donne accès à ces modèles. * * * [Comment ça marche](https://opencode.ai/docs/fr/zen#comment-%C3%A7a-marche) ---------------------------------------------------------------------------- OpenCode Zen fonctionne comme n’importe quel autre fournisseur dans OpenCode. 1. Vous vous connectez à **[OpenCode Zen](https://opencode.ai/auth) **, ajoutez vos informations de facturation et copiez votre clé API. 2. Vous exécutez la commande `/connect` dans le TUI, sélectionnez OpenCode Zen et collez votre clé API. 3. Exécutez `/models` dans le TUI pour voir la liste des modèles que nous recommandons. Vous êtes facturé par demande et vous pouvez ajouter des crédits à votre compte. * * * [Points de terminaison](https://opencode.ai/docs/fr/zen#points-de-terminaison) ------------------------------------------------------------------------------- Vous pouvez également accéder à nos modèles via les points de terminaison API suivants. | Modèle | ID du modèle | Point de terminaison | Package SDK IA | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | Le [id du modèle](https://opencode.ai/docs/config/#models) dans votre configuration OpenCode utilise le format `opencode/`. Par exemple, pour GPT 5.2 Codex, vous devez utilisez `opencode/gpt-5.2-codex` dans votre configuration. * * * ### [Modèles](https://opencode.ai/docs/fr/zen#mod%C3%A8les) Vous pouvez récupérer la liste complète des modèles disponibles et leurs métadonnées à partir de : https://opencode.ai/zen/v1/models * * * [Tarifs](https://opencode.ai/docs/fr/zen#tarifs) ------------------------------------------------- Nous soutenons un modèle de paiement à l’utilisation. Vous trouverez ci-dessous les prix **par 1 million de jetons**. | Modèle | Entrée | Sortie | Lecture en cache | Écriture en cache | | --- | --- | --- | --- | --- | | Big Pickle | Gratuit | Gratuit | Gratuit | \- | | MiniMax M2.5 Free | Gratuit | Gratuit | Gratuit | \- | | MiniMax M2.5 | 0,30 $ | 1,20 $ | 0,06 $ | \- | | MiniMax M2.1 | 0,30 $ | 1,20 $ | 0,10 $ | \- | | GLM 5 | 1,00 $ | 3,20 $ | 0,20 $ | \- | | GLM 4.7 | 0,60 $ | 2,20 $ | 0,10 $ | \- | | GLM 4.6 | 0,60 $ | 2,20 $ | 0,10 $ | \- | | Kimi K2.5 | 0,60 $ | 3,00 $ | 0,08 $ | \- | | Kimi K2 Thinking | 0,40 $ | 2,50 $ | \- | \- | | Kimi K2 | 0,40 $ | 2,50 $ | \- | \- | | Qwen3 Coder 480B | 0,45 $ | 1,50 $ | \- | \- | | Claude Opus 4.6 (≤ 200K jetons) | 5,00 $ | 25,00 $ | 0,50 $ | 6,25 $ | | Claude Opus 4.6 (> 200K jetons) | 10,00 $ | 37,50 $ | 1,00 $ | 12,50 $ | | Claude Opus 4.5 | 5,00 $ | 25,00 $ | 0,50 $ | 6,25 $ | | Claude Opus 4.1 | 15,00 $ | 75,00 $ | 1,50 $ | 18,75 $ | | Claude Sonnet 4.6 (≤ 200K jetons) | 3,00 $ | 15,00 $ | 0,30 $ | 3,75 $ | | Claude Sonnet 4.6 (> 200K jetons) | 6,00 $ | 22,50 $ | 0,60 $ | 7,50 $ | | Claude Sonnet 4.5 (≤ 200K jetons) | 3,00 $ | 15,00 $ | 0,30 $ | 3,75 $ | | Claude Sonnet 4.5 (> 200K jetons) | 6,00 $ | 22,50 $ | 0,60 $ | 7,50 $ | | Claude Sonnet 4 (≤ 200K jetons) | 3,00 $ | 15,00 $ | 0,30 $ | 3,75 $ | | Claude Sonnet 4 (> 200K jetons) | 6,00 $ | 22,50 $ | 0,60 $ | 7,50 $ | | Claude Haiku 4.5 | 1,00 $ | 5,00 $ | 0,10 $ | 1,25 $ | | Claude Haiku 3.5 | 0,80 $ | 4,00 $ | 0,08 $ | 1,00 $ | | Gemini 3.1 Pro (≤ 200K jetons) | 2,00 $ | 12,00 $ | 0,20 $ | \- | | Gemini 3.1 Pro (> 200K jetons) | 4,00 $ | 18,00 $ | 0,40 $ | \- | | Gemini 3 Pro (≤ 200K jetons) | 2,00 $ | 12,00 $ | 0,20 $ | \- | | Gemini 3 Pro (> 200K jetons) | 4,00 $ | 18,00 $ | 0,40 $ | \- | | Gemini 3 Flash | 0,50 $ | 3,00 $ | 0,05 $ | \- | | GPT 5.4 | 2,50 $ | 15,00 $ | 0,25 $ | \- | | GPT 5.3 Codex | 1,75 $ | 14,00 $ | 0,175 $ | \- | | GPT 5.2 | 1,75 $ | 14,00 $ | 0,175 $ | \- | | GPT 5.2 Codex | 1,75 $ | 14,00 $ | 0,175 $ | \- | | GPT 5.1 | 1,07 $ | 8,50 $ | 0,107 $ | \- | | GPT 5.1 Codex | 1,07 $ | 8,50 $ | 0,107 $ | \- | | GPT 5.1 Codex Max | 1,25 $ | 10,00 $ | 0,125 $ | \- | | GPT 5.1 Codex Mini | 0,25 $ | 2,00 $ | 0,025 $ | \- | | GPT 5 | 1,07 $ | 8,50 $ | 0,107 $ | \- | | GPT 5 Codex | 1,07 $ | 8,50 $ | 0,107 $ | \- | | GPT 5 Nano | Gratuit | Gratuit | Gratuit | \- | Vous remarquerez peut-être _Claude Haiku 3.5_ dans votre historique d’utilisation. Il s’agit d’un [modèle low cost](https://opencode.ai/docs/config/#models) qui est utilisé pour générer les titres de vos sessions. Les modèles gratuits : * MiniMax M2.5 Free est disponible sur OpenCode pour une durée limitée. L’équipe profite de ce temps pour recueillir des commentaires et améliorer le modèle. * Big Pickle est un modèle furtif gratuit sur OpenCode pour une durée limitée. L’équipe profite de ce temps pour recueillir des commentaires et améliorer le modèle. [Contactez-nous](mailto:contact@anoma.ly) si vous avez des questions. * * * ### [Rechargement automatique](https://opencode.ai/docs/fr/zen#rechargement-automatique) Si votre solde descend en dessous de 5 $, Zen rechargera automatiquement 20 $. Vous pouvez modifier le montant du rechargement automatique. Vous pouvez également désactiver complètement le rechargement automatique. * * * ### [Limites mensuelles](https://opencode.ai/docs/fr/zen#limites-mensuelles) Vous pouvez également définir une limite d’utilisation mensuelle pour l’ensemble de l’espace de travail et pour chaque membre de votre équipe. Par exemple, disons que vous définissez une limite d’utilisation mensuelle à 20 $, Zen n’utilisera pas plus de 20 $ par mois. Mais si le rechargement automatique est activé, Zen pourrait finir par vous facturant plus de 20 $ si votre solde descend en dessous de 5 $. * * * ### [Modèles obsolètes](https://opencode.ai/docs/fr/zen#mod%C3%A8les-obsol%C3%A8tes) | Modèle | Date de dépréciation | | --- | --- | | Qwen3 Coder 480B | 6 février 2026 | | Kimi K2 Thinking | 6 mars 2026 | | Kimi K2 | 6 mars 2026 | | MiniMax M2.1 | 15 mars 2026 | | GLM 4.7 | 15 mars 2026 | | GLM 4.6 | 15 mars 2026 | * * * [Confidentialité](https://opencode.ai/docs/fr/zen#confidentialit%C3%A9) ------------------------------------------------------------------------ Tous nos modèles sont hébergés aux États-Unis. Nos fournisseurs suivent une politique de rétention zéro et n’utilisent pas vos données pour la formation de modèles, avec les exceptions suivantes : * Big Pickle : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle. * MiniMax M2.5 Free : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle. * API OpenAI : Les demandes sont conservées pendant 30 jours conformément aux politiques de données de [OpenAI](https://platform.openai.com/docs/guides/your-data) . * API Anthropic : Les demandes sont conservées pendant 30 jours conformément aux [Politiques de données d’Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [Pour les équipes](https://opencode.ai/docs/fr/zen#pour-les-%C3%A9quipes) -------------------------------------------------------------------------- Zen fonctionne également très bien pour les équipes. Vous pouvez inviter des coéquipiers, attribuer des rôles, organiser les modèles utilisés par votre équipe, et bien plus encore. La gestion de votre espace de travail est actuellement gratuite pour les équipes dans le cadre de la version bêta. Nous partagerons bientôt plus de détails sur les prix. * * * ### [Rôles](https://opencode.ai/docs/fr/zen#r%C3%B4les) Vous pouvez inviter des coéquipiers dans votre espace de travail et attribuer des rôles : * **Administrateur** : gérez les modèles, les membres, les clés API et la facturation. * **Membre** : gérer uniquement ses propres clés API Les administrateurs peuvent également définir des limites de dépenses mensuelles pour chaque membre afin de garder les coûts sous contrôle. * * * ### [Accès au modèle](https://opencode.ai/docs/fr/zen#acc%C3%A8s-au-mod%C3%A8le) Les administrateurs peuvent activer ou désactiver des modèles spécifiques pour l’espace de travail. Les requêtes adressées à un modèle désactivé renverront une erreur. Ceci est utile dans les cas où vous souhaitez désactiver l’utilisation d’un modèle qui collecte des données. * * * ### [Apportez votre propre clé](https://opencode.ai/docs/fr/zen#apportez-votre-propre-cl%C3%A9) Vous pouvez utiliser vos propres clés OpenAI ou Anthropic API tout en accédant à d’autres modèles dans Zen. Lorsque vous utilisez vos propres clés, les tokens sont facturés directement par le fournisseur et non par Zen. Par exemple, votre organisation dispose peut-être déjà d’une clé pour OpenAI ou Anthropic et vous souhaitez l’utiliser à la place de celui fourni par Zen. * * * [Objectifs](https://opencode.ai/docs/fr/zen#objectifs) ------------------------------------------------------- Nous avons créé OpenCode Zen pour : 1. **Benchmark** les meilleurs modèles/fournisseurs d’agents de codage. 2. Ayez accès aux options de **la plus haute qualité** et ne dégradez pas les performances ni ne vous dirigez vers des fournisseurs moins chers. 3. Répercutez toute **baisse de prix** en vendant au prix coûtant ; la seule majoration est donc pour couvrir nos frais de traitement. 4. N’ayez **aucun verrouillage** en vous permettant de l’utiliser avec n’importe quel autre agent de codage. Et laissez-vous toujours utiliser n’importe quel autre fournisseur avec OpenCode également. --- # Zen | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/zen#_top) Zen === Lista curata di modelli fornita da OpenCode. OpenCode Zen e una lista di modelli testati e verificati dal team di OpenCode. Zen funziona come qualunque altro provider in OpenCode. Accedi a OpenCode Zen e ottieni la tua chiave API. E **completamente opzionale**: non devi usarlo per usare OpenCode. * * * [Contesto](https://opencode.ai/docs/it/zen#contesto) ----------------------------------------------------- Ci sono moltissimi modelli, ma solo pochi funzionano bene come agenti di coding. Inoltre, la maggior parte dei provider e configurata in modo molto diverso, quindi prestazioni e qualita possono variare parecchio. Quindi, se usi un modello tramite qualcosa come OpenRouter, non puoi mai essere sicuro di ottenere la migliore versione del modello che vuoi. Per risolvere, abbiamo fatto alcune cose: 1. Abbiamo testato un gruppo selezionato di modelli e parlato coi loro team su come eseguirli al meglio. 2. Poi abbiamo lavorato con alcuni provider per assicurarci che venissero serviti correttamente. 3. Infine, abbiamo fatto benchmark delle combinazioni modello/provider e creato una lista che ci sentiamo di raccomandare. OpenCode Zen e un gateway AI che ti da accesso a questi modelli. * * * [Come funziona](https://opencode.ai/docs/it/zen#come-funziona) --------------------------------------------------------------- OpenCode Zen funziona come qualunque altro provider in OpenCode. 1. Accedi a **[OpenCode Zen](https://opencode.ai/auth) **, aggiungi i dettagli di fatturazione e copia la chiave API. 2. Esegui il comando `/connect` nella TUI, seleziona OpenCode Zen e incolla la chiave API. 3. Esegui `/models` nella TUI per vedere la lista dei modelli che consigliamo. Paghi per richiesta e puoi aggiungere credito al tuo account. * * * [Endpoint](https://opencode.ai/docs/it/zen#endpoint) ----------------------------------------------------- Puoi anche accedere ai nostri modelli tramite i seguenti endpoint API. | Modello | ID modello | Endpoint | Pacchetto AI SDK | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | Il [model id](https://opencode.ai/docs/config/#models) nella config di OpenCode usa il formato `opencode/`. Per esempio, per GPT 5.2 Codex useresti `opencode/gpt-5.2-codex` nella config. * * * ### [Modelli](https://opencode.ai/docs/it/zen#modelli) Puoi recuperare la lista completa dei modelli disponibili e i relativi metadati da: https://opencode.ai/zen/v1/models * * * [Prezzi](https://opencode.ai/docs/it/zen#prezzi) ------------------------------------------------- Supportiamo un modello pay-as-you-go. Qui sotto trovi i prezzi **per 1M token**. | Modello | Input | Output | Lettura in cache | Scrittura in cache | | --- | --- | --- | --- | --- | | Big Pickle | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 Free | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Gratis | Gratis | Gratis | \- | Potresti notare _Claude Haiku 3.5_ nella cronologia d’uso. E un [modello a basso costo](https://opencode.ai/docs/config/#models) usato per generare i titoli delle sessioni. I modelli gratuiti: * MiniMax M2.5 Free e disponibile su OpenCode per un periodo limitato. Il team usa questo tempo per raccogliere feedback e migliorare il modello. * Big Pickle e un modello stealth gratuito su OpenCode per un periodo limitato. Il team usa questo tempo per raccogliere feedback e migliorare il modello. [Contattaci](mailto:contact@anoma.ly) se hai domande. * * * ### [Ricarica automatica](https://opencode.ai/docs/it/zen#ricarica-automatica) Se il saldo scende sotto $5, Zen ricarica automaticamente $20. Puoi cambiare l’importo della ricarica automatica. Puoi anche disabilitare completamente l’auto-reload. * * * ### [Limiti mensili](https://opencode.ai/docs/it/zen#limiti-mensili) Puoi anche impostare un limite mensile di utilizzo per l’intero workspace e per ogni membro del team. Per esempio, se imposti un limite mensile a $20, Zen non usera piu di $20 in un mese. Ma se hai l’auto-reload attivo, Zen potrebbe finire per addebitarti piu di $20 se il saldo scende sotto $5. * * * ### [Modelli deprecati](https://opencode.ai/docs/it/zen#modelli-deprecati) | Modello | Data di deprecazione | | --- | --- | | Qwen3 Coder 480B | 6 feb 2026 | | Kimi K2 Thinking | 6 mar 2026 | | Kimi K2 | 6 mar 2026 | | MiniMax M2.1 | 15 mar 2026 | | GLM 4.7 | 15 mar 2026 | | GLM 4.6 | 15 mar 2026 | * * * [Privacy](https://opencode.ai/docs/it/zen#privacy) --------------------------------------------------- Tutti i nostri modelli sono ospitati negli US. I nostri provider seguono una policy di zero-retention e non usano i tuoi dati per training dei modelli, con le seguenti eccezioni: * Big Pickle: durante il periodo gratuito, i dati raccolti potrebbero essere usati per migliorare il modello. * MiniMax M2.5 Free: durante il periodo gratuito, i dati raccolti potrebbero essere usati per migliorare il modello. * OpenAI APIs: le richieste vengono conservate per 30 giorni in conformita alle [OpenAI’s Data Policies](https://platform.openai.com/docs/guides/your-data) . * Anthropic APIs: le richieste vengono conservate per 30 giorni in conformita alle [Anthropic’s Data Policies](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [Per i team](https://opencode.ai/docs/it/zen#per-i-team) --------------------------------------------------------- Zen funziona benissimo anche per i team. Puoi invitare colleghi, assegnare ruoli, curare i modelli usati dal team e altro. Gestire il workspace e attualmente gratuito per i team come parte della beta. Condivideremo presto piu dettagli sul pricing. * * * ### [Ruoli](https://opencode.ai/docs/it/zen#ruoli) Puoi invitare colleghi nel workspace e assegnare ruoli: * **Admin**: gestisce modelli, membri, chiavi API e fatturazione * **Member**: gestisce solo le proprie chiavi API Gli admin possono anche impostare limiti mensili di spesa per ogni membro per tenere i costi sotto controllo. * * * ### [Accesso ai modelli](https://opencode.ai/docs/it/zen#accesso-ai-modelli) Gli admin possono abilitare o disabilitare modelli specifici per il workspace. Le richieste verso un modello disabilitato restituiscono un errore. Questo e utile quando vuoi disabilitare l’uso di un modello che raccoglie dati. * * * ### [Usa le tue chiavi](https://opencode.ai/docs/it/zen#usa-le-tue-chiavi) Puoi usare le tue chiavi API OpenAI o Anthropic continuando ad accedere agli altri modelli in Zen. Quando usi le tue chiavi, i token vengono fatturati direttamente dal provider, non da Zen. Per esempio, la tua organizzazione potrebbe avere gia una chiave per OpenAI o Anthropic e vuoi usare quella invece di quella fornita da Zen. * * * [Obiettivi](https://opencode.ai/docs/it/zen#obiettivi) ------------------------------------------------------- Abbiamo creato OpenCode Zen per: 1. Fare **benchmark** dei migliori modelli/provider per agenti di coding. 2. Dare accesso alle opzioni di **massima qualita** senza ridurre le prestazioni o instradare verso provider piu economici. 3. Trasferire eventuali **riduzioni di prezzo** vendendo al costo; l’unico markup copre le commissioni di elaborazione. 4. Evitare **lock-in** permettendoti di usarlo con qualunque altro agente di coding e lasciandoti sempre usare anche altri provider con OpenCode. --- # Zen | OpenCode [Gå til indhold](https://opencode.ai/docs/da/zen#_top) Zen === Udvalgt liste over modeller leveret af OpenCode. OpenCode Zen er en liste over testede og verificerede modeller leveret af OpenCode-teamet. Zen fungerer som alle andre udbydere i OpenCode. Du logger på OpenCode Zen og får din API-nøgle. Den er **helt valgfri** og du behøver ikke bruge den for at bruge OpenCode. * * * [Baggrund](https://opencode.ai/docs/da/zen#baggrund) ----------------------------------------------------- Der er et stort antal modeller derude, men kun få af dem fungerer godt som kodeagenter. Derudover er de fleste udbydere konfigureret meget forskelligt, så du får meget forskellig ydeevne og kvalitet. Så hvis du bruger en model gennem noget som OpenRouter, kan du aldrig være sikker på, om du får den bedste version af modellen, du ønsker. For at fikse dette gjorde vi et par ting: 1. Vi testede en udvalgt gruppe modeller og talte med deres teams om, hvordan man bedst kører dem. 2. Vi samarbejdede derefter med nogle få udbydere for at sikre, at disse blev serveret korrekt. 3. Til sidst benchmarkede vi kombinationen af model/udbyder og kom frem til en liste, som vi har lyst til at anbefale. OpenCode Zen er en AI gateway, der giver dig adgang til disse modeller. * * * [Sådan fungerer det](https://opencode.ai/docs/da/zen#s%C3%A5dan-fungerer-det) ------------------------------------------------------------------------------ OpenCode Zen fungerer som alle andre udbydere i OpenCode. 1. Du logger på **[OpenCode Zen](https://opencode.ai/auth) **, tilføjer faktureringsoplysninger og kopierer API-nøglen. 2. Du kører kommandoen `/connect` i TUI, vælger OpenCode Zen og indsætter API-nøglen. 3. Kør `/models` i TUI for at se listen over modeller, vi anbefaler. Du opkræves per anmodning, og du kan tilføje kredit til din konto. * * * [Endpoints](https://opencode.ai/docs/da/zen#endpoints) ------------------------------------------------------- Du kan også få adgang til vores modeller gennem følgende API-endpoints. | Model | Model ID | Endpoint | AI SDK Pakke | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Gratis | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Tenker | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3-koder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Stor sylteagurk | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | [model-id](https://opencode.ai/docs/config/#models) i OpenCode-konfigurationen bruger formatet `opencode/`. For eksempel, for GPT 5.2 Codex, ville du bruge `opencode/gpt-5.2-codex` i din konfiguration. * * * ### [Modeller](https://opencode.ai/docs/da/zen#modeller) Du kan hente hele listen over tilgængelige modeller og deres metadata fra: https://opencode.ai/zen/v1/models * * * [Priser](https://opencode.ai/docs/da/zen#priser) ------------------------------------------------- Vi støtter en pay-as-you-go-model. Nedenfor er priserne **per 1 million tokens**. | Model | Input | Output | Cached Læs | Cached Skriv | | --- | --- | --- | --- | --- | | Stor sylteagurk | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 Gratis | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 | $0,30 | $1,20 | $0,06 | \- | | MiniMax M2.1 | $0,30 | $1,20 | $0,10 | \- | | GLM 5 | $1,00 | $3,20 | $0,20 | \- | | GLM 4.7 | $0,60 | $2,20 | $0,10 | \- | | GLM 4.6 | $0,60 | $2,20 | $0,10 | \- | | Kimi K2.5 | $0,60 | $3,00 | $0,08 | \- | | Kimi K2 Tenker | $0,40 | $2,50 | \- | \- | | Kimi K2 | $0,40 | $2,50 | \- | \- | | Qwen3-koder 480B | $0,45 | $1,50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5,00 | $25,00 | $0,50 | $6,25 | | Claude Opus 4.6 (> 200K tokens) | $10,00 | $37,50 | $1,00 | $12,50 | | Claude Opus 4.5 | $5,00 | $25,00 | $0,50 | $6,25 | | Claude Opus 4.1 | $15,00 | $75,00 | $1,50 | $18,75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | | Claude Sonnet 4.6 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | | Claude Sonnet 4.5 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | | Claude Sonnet 4 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | | Claude Sonnet 4 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | | Claude Haiku 4.5 | $1,00 | $5,00 | $0,10 | $1,25 | | Claude Haiku 3.5 | $0,80 | $4,00 | $0,08 | $1,00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2,00 | $12,00 | $0,20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4,00 | $18,00 | $0,40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2,00 | $12,00 | $0,20 | \- | | Gemini 3 Pro (> 200K tokens) | $4,00 | $18,00 | $0,40 | \- | | Gemini 3 Flash | $0,50 | $3,00 | $0,05 | \- | | GPT 5.4 | $2,50 | $15,00 | $0,25 | \- | | GPT 5.3 Codex | $1,75 | $14,00 | $0,175 | \- | | GPT 5.2 | $1,75 | $14,00 | $0,175 | \- | | GPT 5.2 Codex | $1,75 | $14,00 | $0,175 | \- | | GPT 5.1 | $1,07 | $8,50 | $0,107 | \- | | GPT 5.1 Codex | $1,07 | $8,50 | $0,107 | \- | | GPT 5.1 Codex Max | $1,25 | $10,00 | $0,125 | \- | | GPT 5.1 Codex Mini | $0,25 | $2,00 | $0,025 | \- | | GPT 5 | $1,07 | $8,50 | $0,107 | \- | | GPT 5 Codex | $1,07 | $8,50 | $0,107 | \- | | GPT 5 Nano | Gratis | Gratis | Gratis | \- | Du bemærker måske _Claude Haiku 3.5_ i din brugshistorik. Dette er en [lavprismodel](https://opencode.ai/docs/config/#models) , som bruges til at generere titlerne på dine sessioner. De gratis modeller: * MiniMax M2.5 Gratis er tilgængelig på OpenCode i en begrænset periode. Teamet bruger denne tid til at samle feedback og forbedre modellen. * Stor sylteagurk er en stealth-model som er gratis på OpenCode i en begrænset periode. Teamet bruger denne tid til at samle feedback og forbedre modellen. [Kontakt os](mailto:contact@anoma.ly) hvis du har spørgsmål. * * * ### [Automatisk opfyldning](https://opencode.ai/docs/da/zen#automatisk-opfyldning) Hvis din saldo går under $5, vil Zen automatisk laste $20 ind på nytt. Du kan ændre beløbet for automatisk påfyldning. Du kan også deaktivere automatisk genindlæsning helt. * * * ### [Månedlige grænser](https://opencode.ai/docs/da/zen#m%C3%A5nedlige-gr%C3%A6nser) Du kan også angive en månedlig brugsgrænse for hele arbejdsområdet og for hvert medlem af dit team. Lad os for eksempel sige, at du sætter en månedlig brugsgrænse til $20, Zen vil ikke bruge mere end $20 på en måned. Men hvis du har automatisk genindlæsning aktiveret, kan Zen ende med at opkræve dig mere end $20, hvis din saldo går under $5. * * * ### [Udfasede modeller](https://opencode.ai/docs/da/zen#udfasede-modeller) | Model | Udfasningsdato | | --- | --- | | Qwen3-koder 480B | 6\. feb. 2026 | | Kimi K2 Tenker | 6\. marts 2026 | | Kimi K2 | 6\. marts 2026 | | MiniMax M2.1 | 15\. marts 2026 | | GLM 4.7 | 15\. marts 2026 | | GLM 4.6 | 15\. marts 2026 | * * * [Privatliv](https://opencode.ai/docs/da/zen#privatliv) ------------------------------------------------------- Alle vores modeller er hostet i USA. Vores udbydere følger en nul-opbevaringspolitik og bruger ikke dine data til modeltræning, med følgende undtagelser: * Stor sylteagurk: I løbet af gratisperioden kan indsamlede data bruges til at forbedre modellen. * MiniMax M2.5 Gratis: I løbet af gratisperioden kan indsamlede data bruges til at forbedre modellen. * OpenAI API’er: Anmodninger opbevares i 30 dage i overensstemmelse med [OpenAIs datapolitikker](https://platform.openai.com/docs/guides/your-data) . * Anthropic API’er: Anmodninger opbevares i 30 dage i overensstemmelse med [Anthropics datapolitikker](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [For teams](https://opencode.ai/docs/da/zen#for-teams) ------------------------------------------------------- Zen fungerer også fremragende for teams. Du kan invitere holdkammerater, tildele roller, kuratere de modeller dit hold bruger, og mere. At administrere dit arbejdsområde er i øjeblikket gratis for teams som en del af betaversionen. Vi vil dele mere information om priserne snart. * * * ### [Roller](https://opencode.ai/docs/da/zen#roller) Du kan invitere holdkammerater til dit arbejdsområde og tildele roller: * **Admin**: Administrer modeller, medlemmer, API-nøgler og fakturering * **Medlem**: Administrer kun sine egne API-nøgler Administratorer kan også sætte månedlige forbrugsgrænser for hvert medlem for at holde omkostningerne under kontrol. * * * ### [Modeladgang](https://opencode.ai/docs/da/zen#modeladgang) Administratorer kan aktivere eller deaktivere specifikke modeller for arbejdsområdet. Anmodninger til en deaktiveret model vil returnere en fejl. Dette er nyttigt for tilfælde, hvor du ønsker at deaktivere brugen af en model, som samler ind data. * * * ### [Medbring din egen nøgle](https://opencode.ai/docs/da/zen#medbring-din-egen-n%C3%B8gle) Du kan bruge dine egne OpenAI- eller Anthropic API-nøgler, mens du stadig har adgang til andre modeller i Zen. Når du bruger dine egne nøgler, faktureres tokens direkte af udbyderen, ikke af Zen. For eksempel kan din organisation allerede have en nøgle for OpenAI eller Anthropic og du vil bruge det i stedet for det Zen giver. * * * [Mål](https://opencode.ai/docs/da/zen#m%C3%A5l) ------------------------------------------------ Vi oprettede OpenCode Zen for at: 1. **Benchmarke** de bedste modeller/udbydere for kodningsagenter. 2. Have adgang til mulighederne for **højeste kvalitet** og ikke nedgradere ydeevnen eller rute til billigere udbydere. 3. Give videre eventuelle **prisfald** ved at sælge til kostpris; så den eneste mark-up er for at dække vores behandlingsgebyrer. 4. Have **ingen fastlåsning** ved at lade dig bruge den med en hvilken som helst anden kodeagent. Og lade dig altid bruge en hvilken som helst anden udbyder med OpenCode også. --- # Go | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/go#_top) Go == 針對開放原始碼程式設計模型的低成本訂閱服務。 OpenCode Go 是一項低成本的 **每月 10 美元** 訂閱服務,讓您可以穩定存取熱門的開放原始碼程式設計模型。 Go 的運作方式就像 OpenCode 中的任何其他供應商一樣。您訂閱 OpenCode Go 並取得您的 API key。這是**完全選用**的,您不需要使用它也能使用 OpenCode。 主要是為國際使用者設計,模型託管在美國、歐盟和新加坡,以提供穩定的全球存取。 * * * [背景](https://opencode.ai/docs/zh-tw/go#%E8%83%8C%E6%99%AF) ----------------------------------------------------------- 開放模型已經變得非常優秀。它們現在在程式設計任務上的表現已接近專有模型。而且因為許多供應商都能以具競爭力的方式提供服務,它們通常便宜得多。 然而,要獲得穩定且低延遲的存取可能會很困難。供應商的品質和可用性各不相同。 為了解決這個問題,我們做了幾件事: 1. 我們測試了一組精選的開放模型,並與他們的團隊討論如何最好地運行它們。 2. 接著我們與幾家供應商合作,確保這些模型能正確地提供服務。 3. 最後,我們對模型/供應商的組合進行基準測試,並提出了一份我們覺得值得推薦的清單。 OpenCode Go 讓您能以 **每月 10 美元** 的價格存取這些模型。 * * * [運作方式](https://opencode.ai/docs/zh-tw/go#%E9%81%8B%E4%BD%9C%E6%96%B9%E5%BC%8F) ------------------------------------------------------------------------------- OpenCode Go 的運作方式就像 OpenCode 中的任何其他供應商一樣。 1. 您登入 **[OpenCode Zen](https://opencode.ai/auth) **,訂閱 Go,並複製您的 API key。 2. 您在 TUI 中執行 `/connect` 指令,選擇 `OpenCode Go`,並貼上您的 API key。 3. 在 TUI 中執行 `/models` 以查看透過 Go 可用的模型清單。 目前的模型清單包括: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** 模型清單可能會隨著我們測試和新增模型而變動。 * * * [使用限制](https://opencode.ai/docs/zh-tw/go#%E4%BD%BF%E7%94%A8%E9%99%90%E5%88%B6) ------------------------------------------------------------------------------- OpenCode Go 包含以下限制: * **5 小時限制** — 12 美元的使用量 * **每週限制** — 30 美元的使用量 * **每月限制** — 60 美元的使用量 限制是以美元價值定義的。這意味著您的實際請求次數取決於您使用的模型。較便宜的模型(如 MiniMax M2.5)允許更多請求,而較高成本的模型(如 GLM-5)允許較少請求。 下表根據典型的 Go 使用模式提供估計的請求次數: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | 每 5 小時請求數 | 1,150 | 1,850 | 30,000 | | 每週請求數 | 2,880 | 4,630 | 75,000 | | 每月請求數 | 5,750 | 9,250 | 150,000 | 估計值是根據觀察到的平均請求模式: * GLM-5 — 700 輸入, 52,000 快取, 150 輸出 token (每個請求) * Kimi K2.5 — 870 輸入, 55,000 快取, 200 輸出 token (每個請求) * MiniMax M2.5 — 300 輸入, 55,000 快取, 125 輸出 token (每個請求) 您可以在 **[console](https://opencode.ai/auth) ** 中追蹤目前的使用量。 使用限制可能會隨著我們從早期使用和回饋中學習而變動。 * * * ### [定價](https://opencode.ai/docs/zh-tw/go#%E5%AE%9A%E5%83%B9) OpenCode Go 是一個 **每月 10 美元** 的訂閱方案。以下是 **每 100 萬 token** 的價格。 | 模型 | 輸入 | 輸出 | 快取讀取 | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [超出限制的使用](https://opencode.ai/docs/zh-tw/go#%E8%B6%85%E5%87%BA%E9%99%90%E5%88%B6%E7%9A%84%E4%BD%BF%E7%94%A8) 如果您的 Zen 餘額中也有點數,您可以在 console 中啟用 **Use balance** 選項。啟用後,當您達到使用限制時,Go 將會改用您的 Zen 餘額,而不是封鎖請求。 * * * [端點](https://opencode.ai/docs/zh-tw/go#%E7%AB%AF%E9%BB%9E) ----------------------------------------------------------- 您也可以透過以下 API 端點存取 Go 模型。 | 模型 | Model ID | 端點 | AI SDK 套件 | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | 您 OpenCode 設定中的 [model id](https://opencode.ai/docs/config/#models) 使用 `opencode-go/` 格式。例如,對於 Kimi K2.5,您會在設定中使用 `opencode-go/kimi-k2.5`。 * * * [隱私權](https://opencode.ai/docs/zh-tw/go#%E9%9A%B1%E7%A7%81%E6%AC%8A) --------------------------------------------------------------------- 此方案主要是為國際使用者設計,模型託管在美國、歐盟和新加坡,以提供穩定的全球存取。 如果您有任何問題,請 [聯絡我們](mailto:contact@anoma.ly) 。 * * * [目標](https://opencode.ai/docs/zh-tw/go#%E7%9B%AE%E6%A8%99) ----------------------------------------------------------- 我們建立 OpenCode Go 是為了: 1. 透過低成本訂閱,讓更多人能 **輕易取得** AI 程式設計資源。 2. 提供對最佳開放程式設計模型的 **可靠** 存取。 3. 策劃經過 **測試和基準測試** 的模型,以供程式設計代理使用。 4. **沒有鎖定**,允許您在 OpenCode 中同時使用任何其他供應商。 --- # IDE | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/ide#_top) IDE === 適用於 VS Code、Cursor 及其他 IDE 的 OpenCode 擴充功能 OpenCode 可與 VS Code、Cursor 或任何支援終端機的 IDE 整合。只需在終端機中執行 `opencode` 即可開始使用。 * * * [用法](https://opencode.ai/docs/zh-tw/ide#%E7%94%A8%E6%B3%95) ------------------------------------------------------------ * **快速啟動**:使用 `Cmd+Esc`(Mac)或 `Ctrl+Esc`(Windows/Linux)在分割終端機視圖中開啟 OpenCode,如果已有終端機工作階段正在執行,則會自動聚焦到該工作階段。 * **新建工作階段**:使用 `Cmd+Shift+Esc`(Mac)或 `Ctrl+Shift+Esc`(Windows/Linux)啟動新的 OpenCode 終端機工作階段,即使已有工作階段在執行也會新建。您也可以點選介面中的 OpenCode 按鈕。 * **上下文感知**:自動將當前選取內容或分頁共享給 OpenCode。 * **檔案參照快捷鍵**:使用 `Cmd+Option+K`(Mac)或 `Alt+Ctrl+K`(Linux/Windows)插入檔案參照。例如 `@File#L37-42`。 * * * [安裝](https://opencode.ai/docs/zh-tw/ide#%E5%AE%89%E8%A3%9D) ------------------------------------------------------------ 在 VS Code 及其常見分支(如 Cursor、Windsurf、VSCodium)上安裝 OpenCode: 1. 開啟 VS Code 2. 開啟整合終端機 3. 執行 `opencode`——擴充功能將自動安裝 如果您希望在 TUI 中執行 `/editor` 或 `/export` 時使用自己的 IDE,需要設定 `export EDITOR="code --wait"`。[了解更多](https://opencode.ai/docs/tui/#editor-setup) 。 * * * ### [手動安裝](https://opencode.ai/docs/zh-tw/ide#%E6%89%8B%E5%8B%95%E5%AE%89%E8%A3%9D) 在擴充功能商店中搜尋 **OpenCode**,然後點選 **Install**。 * * * ### [疑難排解](https://opencode.ai/docs/zh-tw/ide#%E7%96%91%E9%9B%A3%E6%8E%92%E8%A7%A3) 如果擴充功能未能自動安裝: * 確保您是在整合終端機中執行的 `opencode`。 * 確認您的 IDE 對應的 CLI 指令已安裝: * VS Code:`code` 指令 * Cursor:`cursor` 指令 * Windsurf:`windsurf` 指令 * VSCodium:`codium` 指令 * 如果未安裝,請按 `Cmd+Shift+P`(Mac)或 `Ctrl+Shift+P`(Windows/Linux),搜尋「Shell Command: Install ‘code’ command in PATH」(或您的 IDE 對應的指令) * 確保 VS Code 有權限安裝擴充功能 --- # IDE | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/ide#_top) IDE === Die OpenCode-Erweiterung für VS Code, Cursor und andere IDEs OpenCode lässt sich in VS Code, Cursor oder jede IDE integrieren, die ein Terminal unterstützt. Führen Sie einfach `opencode` im Terminal aus, um zu beginnen. * * * [Verwendung](https://opencode.ai/docs/de/ide#verwendung) --------------------------------------------------------- * **Schnellstart**: Verwenden Sie `Cmd+Esc` (Mac) oder `Ctrl+Esc` (Windows/Linux), um OpenCode in einer geteilten Terminalansicht zu öffnen, oder fokussieren Sie eine dieser Terminalsitzung, falls bereits eine ausgeführt wird. * **Neue Sitzung**: Verwenden Sie `Cmd+Shift+Esc` (Mac) oder `Ctrl+Shift+Esc` (Windows/Linux), um eine neue OpenCode-Terminalsitzung zu starten, auch wenn eine bereits geöffnet ist. Sie können auch auf die OpenCode-Schaltfläche im UI klicken. * **Kontextbewusstsein**: Teilen Sie Ihre aktuelle Auswahl oder Registerkarte automatisch mit OpenCode. * **Verknüpfungen zu Dateiverweisen**: Verwenden Sie `Cmd+Option+K` (Mac) oder `Alt+Ctrl+K` (Linux/Windows), um Dateiverweisen einzufügen. Beispiel: `@File#L37-42`. * * * [Installation](https://opencode.ai/docs/de/ide#installation) ------------------------------------------------------------- So installieren Sie OpenCode in VS Code und beliebten Forks wie Cursor, Windsurf, VSCodium: 1. Öffnen Sie VS Code 2. Öffnen Sie das integrierte Terminal 3. Führen Sie `opencode` aus – die Erweiterung wird automatisch installiert Wenn Sie andererseits Ihre eigene IDE verwenden möchten, wenn Sie `/editor` oder `/export` von TUI ausführen, müssen Sie `export EDITOR="code --wait"` festlegen. [Learn more](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Manuelle Installation](https://opencode.ai/docs/de/ide#manuelle-installation) Suchen Sie im Extension Marketplace nach **OpenCode** und klicken Sie auf **Installieren**. * * * ### [Fehlerbehebung](https://opencode.ai/docs/de/ide#fehlerbehebung) Wenn die Erweiterung nicht automatisch installiert werden kann: * Stellen Sie sicher, dass Sie `opencode` im integrierten Terminal ausführen. * Bestätigen Sie, dass CLI für Ihre IDE installiert ist: * Für VS Code: `code` Befehl * Für Cursor: Befehl `cursor` * Für Windsurf: Befehl `windsurf` * Für VSCodium: Befehl `codium` * Wenn nicht, führen Sie `Cmd+Shift+P` (Mac) oder `Ctrl+Shift+P` (Windows/Linux) aus und suchen Sie nach „Shell Command: Install ‘code’ command in PATH“ (oder dem Äquivalent für Ihre IDE). * Stellen Sie sicher, dass VS Code über die Berechtigung zum Installieren von Erweiterungen verfügt --- # IDE | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/ide#_top) IDE === L'extension OpenCode pour VS Code, Cursor et autres IDE OpenCode s’intègre à VS Code, Cursor ou tout IDE prenant en charge un terminal. Exécutez simplement `opencode` dans le terminal pour commencer. * * * [Utilisation](https://opencode.ai/docs/fr/ide#utilisation) ----------------------------------------------------------- * **Lancement rapide** : utilisez `Cmd+Esc` (Mac) ou `Ctrl+Esc` (Windows/Linux) pour ouvrir OpenCode dans une vue de terminal divisée, ou focus sur une session de terminal existante si elle est déjà en cours d’exécution. * **Nouvelle session** : utilisez `Cmd+Shift+Esc` (Mac) ou `Ctrl+Shift+Esc` (Windows/Linux) pour démarrer une nouvelle session de terminal OpenCode, même si elle est déjà ouverte. Vous pouvez également cliquer sur le bouton OpenCode dans l’interface utilisateur. * **Contexte** : partagez automatiquement votre sélection ou onglet actuel avec OpenCode. * **Raccourcis de référence de fichier** : utilisez `Cmd+Option+K` (Mac) ou `Alt+Ctrl+K` (Linux/Windows) pour insérer des références de fichier. Par exemple, `@File#L37-42`. * * * [Installation](https://opencode.ai/docs/fr/ide#installation) ------------------------------------------------------------- Pour installer OpenCode sur VS Code et les forks populaires comme Cursor, Windsurf, VSCodium : 1. Ouvrir VS Code 2. Ouvrez le terminal intégré 3. Exécutez `opencode` - l’extension s’installe automatiquement Si, d’un autre côté, vous souhaitez utiliser votre propre IDE lorsque vous exécutez `/editor` ou `/export` à partir du TUI, vous devrez définir `export EDITOR="code --wait"`. [En savoir plus](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Installation manuelle](https://opencode.ai/docs/fr/ide#installation-manuelle) Recherchez **OpenCode** dans Extension Marketplace et cliquez sur **Installer**. * * * ### [Dépannage](https://opencode.ai/docs/fr/ide#d%C3%A9pannage) Si l’extension ne parvient pas à s’installer automatiquement : * Assurez-vous que vous exécutez `opencode` dans le terminal intégré. * Confirmez que la CLI de votre IDE est installée : * Pour VS Code : commande `code` * Pour Cursor : commande `cursor` * Pour Windsurf : commande `windsurf` * Pour VSCodium : commande `codium` * Sinon, exécutez `Cmd+Shift+P` (Mac) ou `Ctrl+Shift+P` (Windows/Linux) et recherchez « Shell Command: Install ‘code’ command in PATH » (ou l’équivalent pour votre IDE) * Assurez-vous que VS Code est autorisé à installer des extensions --- # IDE | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/ide#_top) IDE === VS Code, Cursor 및 기타 IDE용 OpenCode 확장 프로그램 OpenCode는 VS Code, Cursor, 또는 터미널을 지원하는 모든 IDE와 통합됩니다. 시작하려면 터미널에서 `opencode`를 실행하세요. * * * [사용법](https://opencode.ai/docs/ko/ide#%EC%82%AC%EC%9A%A9%EB%B2%95) ------------------------------------------------------------------- * **Quick Launch**: `Cmd+Esc` (Mac) 또는 `Ctrl+Esc` (Windows/Linux)를 사용해 분할 터미널 뷰에서 OpenCode를 열거나, 이미 실행 중인 터미널 세션으로 포커스하세요. * **New Session**: `Cmd+Shift+Esc` (Mac) 또는 `Ctrl+Shift+Esc` (Windows/Linux)를 사용해 기존 세션이 열려 있어도 새 OpenCode 터미널 세션을 시작하세요. UI의 OpenCode 버튼을 클릭해도 됩니다. * **Context Awareness**: 현재 선택 영역이나 탭을 OpenCode와 자동으로 공유합니다. * **File Reference Shortcuts**: `Cmd+Option+K` (Mac) 또는 `Alt+Ctrl+K` (Linux/Windows)를 사용해 파일 참조를 삽입하세요. 예: `@File#L37-42`. * * * [설치](https://opencode.ai/docs/ko/ide#%EC%84%A4%EC%B9%98) --------------------------------------------------------- VS Code와 Cursor, Windsurf, VSCodium 같은 인기 포크에 OpenCode를 설치하려면: 1. VS Code를 여세요.4 2. 통합 터미널을 여세요. 3. `opencode`를 실행하세요. 확장 프로그램이 자동으로 설치됩니다. 반면 TUI에서 `/editor` 또는 `/export`를 실행할 때 자체 IDE를 사용하려면 `export EDITOR="code --wait"`를 설정해야 합니다. [자세히 알아보기](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [수동 설치](https://opencode.ai/docs/ko/ide#%EC%88%98%EB%8F%99-%EC%84%A4%EC%B9%98) Extension Marketplace에서 **OpenCode**를 검색한 다음 **Install**을 클릭하세요. * * * ### [문제 해결](https://opencode.ai/docs/ko/ide#%EB%AC%B8%EC%A0%9C-%ED%95%B4%EA%B2%B0) 확장이 자동으로 설치되지 않는 경우: * 통합 터미널에서 `opencode`를 실행하고 있는지 확인하세요. * IDE용 CLI가 설치되어 있는지 확인하세요. * VS Code: `code` command * Cursor: `cursor` command * Windsurf: `windsurf` command * VSCodium: `codium` command * 설치되어 있지 않다면 `Cmd+Shift+P` (Mac) 또는 `Ctrl+Shift+P` (Windows/Linux)를 실행하고 “Shell Command: Install ‘code’ command in PATH”(또는 IDE에 맞는 동등한 명령)를 검색하세요. * VS Code에 확장 프로그램 설치 권한이 있는지 확인하세요. --- # IDE | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/ide#_top) IDE === A extensão opencode para VS Code, Cursor e outros IDEs O opencode integra-se com VS Code, Cursor ou qualquer IDE que suporte um terminal. Basta executar `opencode` no terminal para começar. * * * [Uso](https://opencode.ai/docs/pt-br/ide#uso) ---------------------------------------------- * **Lançamento Rápido**: Use `Cmd+Esc` (Mac) ou `Ctrl+Esc` (Windows/Linux) para abrir o opencode em uma visualização de terminal dividido, ou focar em uma sessão de terminal existente se uma já estiver em execução. * **Nova Sessão**: Use `Cmd+Shift+Esc` (Mac) ou `Ctrl+Shift+Esc` (Windows/Linux) para iniciar uma nova sessão de terminal opencode, mesmo que uma já esteja aberta. Você também pode clicar no botão opencode na interface. * **Consciência de Contexto**: Compartilhe automaticamente sua seleção ou aba atual com o opencode. * **Atalhos de Referência de Arquivo**: Use `Cmd+Option+K` (Mac) ou `Alt+Ctrl+K` (Linux/Windows) para inserir referências de arquivo. Por exemplo, `@File#L37-42`. * * * [Instalação](https://opencode.ai/docs/pt-br/ide#instala%C3%A7%C3%A3o) ---------------------------------------------------------------------- Para instalar o opencode no VS Code e forks populares como Cursor, Windsurf, VSCodium: 1. Abra o VS Code 2. Abra o terminal integrado 3. Execute `opencode` - a extensão será instalada automaticamente Se, por outro lado, você quiser usar seu próprio IDE ao executar `/editor` ou `/export` a partir do TUI, você precisará definir `export EDITOR="code --wait"`. [Saiba mais](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Instalação Manual](https://opencode.ai/docs/pt-br/ide#instala%C3%A7%C3%A3o-manual) Procure por **opencode** no Marketplace de Extensões e clique em **Instalar**. * * * ### [Solução de Problemas](https://opencode.ai/docs/pt-br/ide#solu%C3%A7%C3%A3o-de-problemas) Se a extensão falhar ao instalar automaticamente: * Certifique-se de que você está executando `opencode` no terminal integrado. * Confirme se a CLI para seu IDE está instalado: * Para VS Code: comando `code` * Para Cursor: comando `cursor` * Para Windsurf: comando `windsurf` * Para VSCodium: comando `codium` * Se não, execute `Cmd+Shift+P` (Mac) ou `Ctrl+Shift+P` (Windows/Linux) e procure por “Shell Command: Install ‘code’ command in PATH” (ou o equivalente para seu IDE) * Certifique-se de que o VS Code tem permissão para instalar extensões --- # Go | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/go#_top) Go == Suscripción de bajo coste para modelos de código abiertos. OpenCode Go es una suscripción de bajo coste de **10 $/mes** que te ofrece acceso fiable a modelos populares de código abierto. Go funciona como cualquier otro proveedor en OpenCode. Te suscribes a OpenCode Go y obtienes tu clave API. Es **completamente opcional** y no necesitas usarlo para utilizar OpenCode. Está diseñado principalmente para usuarios internacionales, con modelos alojados en EE. UU., la UE y Singapur para un acceso global estable. * * * [Contexto](https://opencode.ai/docs/es/go#contexto) ---------------------------------------------------- Los modelos abiertos han mejorado mucho. Ahora alcanzan un rendimiento cercano al de los modelos propietarios para tareas de programación. Y como muchos proveedores pueden servirlos de forma competitiva, suelen ser mucho más baratos. Sin embargo, conseguir un acceso fiable y de baja latencia a ellos puede ser difícil. Los proveedores varían en calidad y disponibilidad. Para solucionar esto, hicimos un par de cosas: 1. Probamos un grupo selecto de modelos abiertos y hablamos con sus equipos sobre la mejor manera de ejecutarlos. 2. Luego trabajamos con algunos proveedores para asegurarnos de que se sirvieran correctamente. 3. Finalmente, evaluamos la combinación de modelo/proveedor y elaboramos una lista que nos sentimos cómodos recomendando. OpenCode Go te da acceso a estos modelos por **10 $/mes**. * * * [Cómo funciona](https://opencode.ai/docs/es/go#c%C3%B3mo-funciona) ------------------------------------------------------------------- OpenCode Go funciona como cualquier otro proveedor en OpenCode. 1. Inicias sesión en **[OpenCode Zen](https://opencode.ai/auth) **, te suscribes a Go y copias tu clave API. 2. Ejecutas el comando `/connect` en la TUI, seleccionas `OpenCode Go` y pegas tu clave API. 3. Ejecuta `/models` en la TUI para ver la lista de modelos disponibles a través de Go. La lista actual de modelos incluye: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** La lista de modelos puede cambiar a medida que probamos y añadimos nuevos. * * * [Límites de uso](https://opencode.ai/docs/es/go#l%C3%ADmites-de-uso) --------------------------------------------------------------------- OpenCode Go incluye los siguientes límites: * **Límite de 5 horas** — 12 $ de uso * **Límite semanal** — 30 $ de uso * **Límite mensual** — 60 $ de uso Los límites se definen en valor monetario. Esto significa que tu recuento real de solicitudes depende del modelo que uses. Los modelos más baratos como MiniMax M2.5 permiten más solicitudes, mientras que los modelos de mayor coste como GLM-5 permiten menos. La siguiente tabla proporciona una estimación del recuento de solicitudes basada en patrones de uso típicos de Go: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | solicitudes por 5 horas | 1.150 | 1.850 | 30.000 | | solicitudes por semana | 2.880 | 4.630 | 75.000 | | solicitudes por mes | 5.750 | 9.250 | 150.000 | Las estimaciones se basan en patrones de solicitud promedio observados: * GLM-5 — 700 de entrada, 52.000 en caché, 150 tokens de salida por solicitud * Kimi K2.5 — 870 de entrada, 55.000 en caché, 200 tokens de salida por solicitud * MiniMax M2.5 — 300 de entrada, 55.000 en caché, 125 tokens de salida por solicitud Puedes realizar un seguimiento de tu uso actual en la **[consola](https://opencode.ai/auth) **. Los límites de uso pueden cambiar a medida que aprendamos del uso temprano y los comentarios. * * * ### [Precios](https://opencode.ai/docs/es/go#precios) OpenCode Go es un plan de suscripción de **10 $/mes**. A continuación se muestran los precios **por 1M de tokens**. | Modelo | Entrada | Salida | Lectura en caché | | --- | --- | --- | --- | | GLM-5 | 1,00 $ | 3,20 $ | 0,20 $ | | Kimi K2.5 | 0,60 $ | 3,00 $ | 0,10 $ | | MiniMax M2.5 | 0,30 $ | 1,20 $ | 0,03 $ | * * * ### [Uso más allá de los límites](https://opencode.ai/docs/es/go#uso-m%C3%A1s-all%C3%A1-de-los-l%C3%ADmites) Si también tienes créditos en tu saldo de Zen, puedes habilitar la opción **Usar saldo** en la consola. Cuando está habilitada, Go recurrirá a tu saldo de Zen después de que hayas alcanzado tus límites de uso en lugar de bloquear las solicitudes. * * * [Endpoints](https://opencode.ai/docs/es/go#endpoints) ------------------------------------------------------ También puedes acceder a los modelos de Go a través de los siguientes endpoints de API. | Modelo | ID del modelo | Endpoint | Paquete AI SDK | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | El [model id](https://opencode.ai/docs/config/#models) en tu configuración de OpenCode usa el formato `opencode-go/`. Por ejemplo, para Kimi K2.5, usarías `opencode-go/kimi-k2.5` en tu configuración. * * * [Privacidad](https://opencode.ai/docs/es/go#privacidad) -------------------------------------------------------- El plan está diseñado principalmente para usuarios internacionales, con modelos alojados en EE. UU., la UE y Singapur para un acceso global estable. [Contáctanos](mailto:contact@anoma.ly) si tienes alguna pregunta. * * * [Objetivos](https://opencode.ai/docs/es/go#objetivos) ------------------------------------------------------ Creamos OpenCode Go para: 1. Hacer que la programación con IA sea **accesible** a más personas con una suscripción de bajo coste. 2. Proporcionar acceso **fiable** a los mejores modelos de código abierto. 3. Seleccionar modelos que han sido **probados y evaluados** para su uso con agentes de programación. 4. **Sin ataduras**, permitiéndote usar cualquier otro proveedor con OpenCode también. --- # Zen | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/zen#_top) Zen === OpenCode가 제공하는 엄선된 모델 목록. OpenCode Zen은 OpenCode 팀이 제공하는, 테스트 및 검증을 완료한 모델 목록입니다. Zen은 OpenCode 내의 다른 공급자와 동일한 방식으로 작동합니다. 사용자는 OpenCode Zen에 로그인하여 API 키를 발급받을 수 있습니다. 본 서비스는 **전적으로 선택 사항**이며, OpenCode를 사용하기 위해 반드시 OpenCode Zen을 이용할 필요는 없습니다. * * * [배경](https://opencode.ai/docs/ko/zen#%EB%B0%B0%EA%B2%BD) --------------------------------------------------------- 현재 다양한 모델이 존재하지만, 이 중 코딩 에이전트로서 우수한 성능을 발휘하는 모델은 일부에 불과합니다. 또한 대부분의 공급자는 각기 다른 방식으로 구성되어 있어, 그에 따라 성능과 품질 또한 크게 달라질 수 있습니다. 따라서 OpenRouter와 같은 서비스를 통해 모델을 사용하는 경우, 사용자가 원하는 모델의 최적 버전을 실제로 사용하고 있는지 확신하기 어렵습니다. 이 문제를 해결하기 위해 다음과 같은 조치를 수행하였습니다. 1. 일부 모델을 선별하여 테스트를 진행하고, 각 모델 팀과 협력하여 최적의 운영 방안을 논의하였습니다. 2. 일부 제공자와 협력하여 해당 모델이 올바르게 제공되도록 구성하였습니다. 3. 마지막으로 모델과 제공자 조합에 대한 벤치마크를 수행하여, 신뢰를 바탕으로 권장할 수 있는 목록을 도출하였습니다. OpenCode Zen은 이러한 모델에 대한 접근을 제공하는 AI 게이트웨이입니다. * * * [어떻게 작동하나요?](https://opencode.ai/docs/ko/zen#%EC%96%B4%EB%96%BB%EA%B2%8C-%EC%9E%91%EB%8F%99%ED%95%98%EB%82%98%EC%9A%94) ------------------------------------------------------------------------------------------------------------------------ OpenCode Zen은 OpenCode의 다른 제공자와 동일한 방식으로 작동합니다. 1. \*\*[OpenCode Zen](https://opencode.ai/auth) \*\*에 로그인한 후, 결제 정보를 추가하고 API 키를 복사합니다. 2. TUI에서 `/connect` 명령어를 실행한 뒤, OpenCode Zen을 선택하고 API 키를 붙여넣습니다. 3. TUI에서 `/models` 명령어를 실행하여, 당사가 권장하는 모델 목록을 확인합니다. 요금은 요청 단위로 부과되며, 계정에 크레딧을 추가하여 사용할 수 있습니다. * * * [엔드포인트](https://opencode.ai/docs/ko/zen#%EC%97%94%EB%93%9C%ED%8F%AC%EC%9D%B8%ED%8A%B8) --------------------------------------------------------------------------------------- 다음 API 엔드포인트를 통해서도 당사의 모델에 접근할 수 있습니다. | 모델 | 모델 ID | 엔드포인트 | AI SDK 패키지 | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | OpenCode 설정 파일에서 사용하는 [모델 ID](https://opencode.ai/docs/config/#models) 는 `opencode/` 형식을 따릅니다. 예를 들어 GPT 5.2 Codex의 경우 설정에서 `opencode/gpt-5.2-codex`와 같이 사용합니다. * * * ### [모델](https://opencode.ai/docs/ko/zen#%EB%AA%A8%EB%8D%B8) 사용 가능한 전체 모델 목록과 해당 메타데이터는 다음 경로에서 확인할 수 있습니다: https://opencode.ai/zen/v1/models * * * [요금제](https://opencode.ai/docs/ko/zen#%EC%9A%94%EA%B8%88%EC%A0%9C) ------------------------------------------------------------------- 당사는 종량제(pay-as-you-go) 요금 모델을 지원합니다. 아래는 **1백만 토큰(1M tokens)당** 요금입니다. | 모델 | 입력 | 출력 | 캐시 읽기 | 캐시 쓰기 | | --- | --- | --- | --- | --- | | Big Pickle | Free | Free | Free | \- | | MiniMax M2.5 Free | Free | Free | Free | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | $0.375 | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Free | Free | Free | \- | 사용 내역에서 _Claude Haiku 3.5_를 확인하실 수 있습니다. 이는 세션 제목을 생성하는 데 사용되는 [저비용 모델](https://opencode.ai/docs/config/#models) 입니다. 무료 모델: * MiniMax M2.5 Free는 한정된 기간 동안 OpenCode에서 제공됩니다. 해당 기간 동안 팀은 사용자 피드백을 수집하고 모델을 개선할 예정입니다. * Big Pickle은 한정된 기간 동안 OpenCode에서 무료로 제공되는 스텔스 모델입니다. 해당 기간 동안 팀은 사용자 피드백을 수집하고 모델을 개선할 예정입니다. 문의 사항이 있으시면 [Contact us](mailto:contact@anoma.ly) 를 통해 연락해 주시기 바랍니다. * * * ### [자동 충전](https://opencode.ai/docs/ko/zen#%EC%9E%90%EB%8F%99-%EC%B6%A9%EC%A0%84) 잔액이 $5 미만으로 내려가면, Zen은 자동으로 $20을 충전합니다. 자동 충전 금액은 변경할 수 있으며, 자동 충전 기능을 완전히 비활성화할 수도 있습니다. * * * ### [월간 사용 한도](https://opencode.ai/docs/ko/zen#%EC%9B%94%EA%B0%84-%EC%82%AC%EC%9A%A9-%ED%95%9C%EB%8F%84) 워크스페이스 전체 및 각 팀 구성원별로 월간 사용 한도를 설정할 수 있습니다. 예를 들어 월간 사용 한도를 $20로 설정한 경우, Zen은 한 달 동안 $20을 초과하여 사용하지 않습니다. 다만 자동 충전이 활성화되어 있는 경우, 잔액이 $5 미만으로 내려가면 자동으로 충전이 이루어질 수 있으므로 실제 청구 금액이 $20을 초과할 수 있습니다. * * * ### [지원 중단 모델](https://opencode.ai/docs/ko/zen#%EC%A7%80%EC%9B%90-%EC%A4%91%EB%8B%A8-%EB%AA%A8%EB%8D%B8) | 모델 | 지원 중단일 | | --- | --- | | Qwen3 Coder 480B | 2026년 2월 6일 | | Kimi K2 Thinking | 2026년 3월 6일 | | Kimi K2 | 2026년 3월 6일 | | MiniMax M2.1 | 2026년 3월 15일 | | GLM 4.7 | 2026년 3월 15일 | | GLM 4.6 | 2026년 3월 15일 | * * * [개인정보 보호](https://opencode.ai/docs/ko/zen#%EA%B0%9C%EC%9D%B8%EC%A0%95%EB%B3%B4-%EB%B3%B4%ED%98%B8) --------------------------------------------------------------------------------------------------- 당사의 모든 모델은 미국에서 호스팅됩니다. 당사 제공자는 데이터 무보존(zero-retention) 정책을 따르며, 아래의 예외를 제외하고는 귀하의 데이터를 모델 학습에 사용하지 않습니다. * Big Pickle: 무료 제공 기간 동안 수집된 데이터는 모델 개선을 위해 사용될 수 있습니다. * MiniMax M2.5 Free: 무료 제공 기간 동안 수집된 데이터는 모델 개선을 위해 사용될 수 있습니다. * OpenAI APIs: 요청 데이터는 [OpenAI의 데이터 정책](https://platform.openai.com/docs/guides/your-data) 에 따라 30일간 보관됩니다. * Anthropic APIs: 요청 데이터는 [Anthropic의 데이터 정책](https://docs.anthropic.com/en/docs/claude-code/data-usage) 에 따라 30일간 보관됩니다. * * * [팀을 위한 기능](https://opencode.ai/docs/ko/zen#%ED%8C%80%EC%9D%84-%EC%9C%84%ED%95%9C-%EA%B8%B0%EB%8A%A5) ----------------------------------------------------------------------------------------------------- Zen은 팀 환경에서도 효과적으로 활용할 수 있습니다. 팀원을 초대하고, 역할을 지정하며, 팀에서 사용할 모델을 선별하는 등 다양한 기능을 제공합니다. 현재 베타 기간 동안 팀의 워크스페이스 관리 기능은 무료로 제공됩니다. 요금 정책에 대한 보다 자세한 내용은 추후 안내될 예정입니다. * * * ### [역할](https://opencode.ai/docs/ko/zen#%EC%97%AD%ED%95%A0) 워크스페이스에 팀원을 초대하고 다음과 같은 역할을 부여할 수 있습니다. * **Admin**: 모델, 구성원, API 키 및 결제를 관리 * **Member**: 본인의 API 키만 관리 관리자는 비용 통제를 위해 각 구성원별 월간 지출 한도를 설정할 수 있습니다. * * * ### [모델 접근 권한](https://opencode.ai/docs/ko/zen#%EB%AA%A8%EB%8D%B8-%EC%A0%91%EA%B7%BC-%EA%B6%8C%ED%95%9C) 관리자는 워크스페이스에서 특정 모델의 사용을 활성화하거나 비활성화할 수 있습니다. 비활성화된 모델에 대한 요청은 오류를 반환합니다. 이는 데이터 수집이 이루어지는 모델의 사용을 제한하려는 경우에 유용합니다. * * * [BYOK (Bring Your Own Key)](https://opencode.ai/docs/ko/zen#byok-bring-your-own-key) ------------------------------------------------------------------------------------- Zen에서 다른 모델을 계속 이용하면서도, OpenAI 또는 Anthropic의 자체 API 키를 사용할 수 있습니다. 자체 키를 사용하는 경우, 토큰 사용 요금은 Zen이 아닌 해당 제공자가 직접 청구합니다. 예를 들어, 귀하의 조직이 이미 OpenAI 또는 Anthropic의 API 키를 보유하고 있는 경우, Zen에서 제공하는 키 대신 해당 키를 사용할 수 있습니다. * * * [목표](https://opencode.ai/docs/ko/zen#%EB%AA%A9%ED%91%9C) --------------------------------------------------------- OpenCode Zen은 다음과 같은 목표를 바탕으로 개발되었습니다. 1. 코딩 에이전트에 적합한 최상의 모델 및 제공자를 **벤치마킹**합니다. 2. 성능을 저하시키거나 더 저렴한 제공자로 우회하지 않고, **최고 품질의 옵션**에 접근할 수 있도록 합니다. 3. 가격 인하가 있을 경우 이를 원가로 반영하여 제공하며, 당사의 마진은 처리 수수료를 충당하기 위한 최소 수준으로 제한합니다. 4. 특정 서비스에 종속되지 않도록 하여, 다른 코딩 에이전트와도 자유롭게 함께 사용할 수 있도록 하며, OpenCode 내에서 다른 제공자 역시 언제든지 사용할 수 있도록 합니다. --- # Zen | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/zen#_top) Zen === Utvalgt liste over modeller levert av OpenCode. OpenCode Zen er en liste over testede og verifiserte modeller levert av OpenCode-teamet. Zen fungerer som alle andre leverandører i OpenCode. Du logger på OpenCode Zen og får din API nøkkel. Den er **helt valgfri** og du trenger ikke bruke den for å bruke OpenCode. * * * [Bakgrunn](https://opencode.ai/docs/nb/zen#bakgrunn) ----------------------------------------------------- Det er et stort antall modeller der ute, men bare noen få av dem disse modellene fungerer godt som kodeagenter. I tillegg er de fleste tilbydere konfigurert veldig annerledes; slik at du får veldig forskjellig ytelse og kvalitet. Så hvis du bruker en modell gjennom noe som OpenRouter, kan du aldri bli det sikker på om du får den beste versjonen av modellen du ønsker. For å fikse dette gjorde vi et par ting: 1. Vi testet en utvalgt gruppe modeller og snakket med teamene deres om hvordan best kjøre dem. 2. Vi samarbeidet deretter med noen få leverandører for å sikre at disse ble servert riktig. 3. Til slutt benchmarket vi kombinasjonen av modell/leverandør og kom frem med en liste som vi har lyst til å anbefale. OpenCode Zen er en AI gateway som gir deg tilgang til disse modellene. * * * [Slik fungerer det](https://opencode.ai/docs/nb/zen#slik-fungerer-det) ----------------------------------------------------------------------- OpenCode Zen fungerer som alle andre leverandører i OpenCode. 1. Du logger på **[OpenCode Zen](https://opencode.ai/auth) **, legg til fakturering detaljer, og kopier API-nøkkelen. 2. Du kjører kommandoen `/connect` i TUI, velger OpenCode Zen og limer inn API-nøkkelen. 3. Kjør `/models` i TUI for å se listen over modeller vi anbefaler. Du belastes per forespørsel, og du kan legge til kreditt på kontoen din. * * * [Endepunkter](https://opencode.ai/docs/nb/zen#endepunkter) ----------------------------------------------------------- Du kan også få tilgang til modellene våre gjennom følgende API-endepunkter. | Modell | Modell ID | Endepunkt | AI SDK Pakke | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | [modell-id](https://opencode.ai/docs/config/#models) i OpenCode-konfigurasjonen bruker formatet `opencode/`. For eksempel, for GPT 5.2 Codex, ville du bruk `opencode/gpt-5.2-codex` i konfigurasjonen din. * * * ### [Modeller](https://opencode.ai/docs/nb/zen#modeller) Du kan hente hele listen over tilgjengelige modeller og deres metadata fra: https://opencode.ai/zen/v1/models * * * [Priser](https://opencode.ai/docs/nb/zen#priser) ------------------------------------------------- Vi støtter en pay-as-you-go-modell. Nedenfor er prisene **per 1 million tokens**. | Modell | Inndata | Utdata | Bufret lesing | Bufret skriving | | --- | --- | --- | --- | --- | | Big Pickle | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 Free | Gratis | Gratis | Gratis | \- | | MiniMax M2.5 | $0,30 | $1,20 | $0,06 | $0,375 | | MiniMax M2.1 | $0,30 | $1,20 | $0,10 | \- | | GLM 5 | $1,00 | $3,20 | $0,20 | \- | | GLM 4.7 | $0,60 | $2,20 | $0,10 | \- | | GLM 4.6 | $0,60 | $2,20 | $0,10 | \- | | Kimi K2.5 | $0,60 | $3,00 | $0,08 | \- | | Kimi K2 Thinking | $0,40 | $2,50 | \- | \- | | Kimi K2 | $0,40 | $2,50 | \- | \- | | Qwen3 Coder 480B | $0,45 | $1,50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5,00 | $25,00 | $0,50 | $6,25 | | Claude Opus 4.6 (> 200K tokens) | $10,00 | $37,50 | $1,00 | $12,50 | | Claude Opus 4.5 | $5,00 | $25,00 | $0,50 | $6,25 | | Claude Opus 4.1 | $15,00 | $75,00 | $1,50 | $18,75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | | Claude Sonnet 4.6 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | | Claude Sonnet 4.5 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | | Claude Sonnet 4 (≤ 200K tokens) | $3,00 | $15,00 | $0,30 | $3,75 | | Claude Sonnet 4 (> 200K tokens) | $6,00 | $22,50 | $0,60 | $7,50 | | Claude Haiku 4.5 | $1,00 | $5,00 | $0,10 | $1,25 | | Claude Haiku 3.5 | $0,80 | $4,00 | $0,08 | $1,00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2,00 | $12,00 | $0,20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4,00 | $18,00 | $0,40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2,00 | $12,00 | $0,20 | \- | | Gemini 3 Pro (> 200K tokens) | $4,00 | $18,00 | $0,40 | \- | | Gemini 3 Flash | $0,50 | $3,00 | $0,05 | \- | | GPT 5.4 | $2,50 | $15,00 | $0,25 | \- | | GPT 5.3 Codex | $1,75 | $14,00 | $0,175 | \- | | GPT 5.2 | $1,75 | $14,00 | $0,175 | \- | | GPT 5.2 Codex | $1,75 | $14,00 | $0,175 | \- | | GPT 5.1 | $1,07 | $8,50 | $0,107 | \- | | GPT 5.1 Codex | $1,07 | $8,50 | $0,107 | \- | | GPT 5.1 Codex Max | $1,25 | $10,00 | $0,125 | \- | | GPT 5.1 Codex Mini | $0,25 | $2,00 | $0,025 | \- | | GPT 5 | $1,07 | $8,50 | $0,107 | \- | | GPT 5 Codex | $1,07 | $8,50 | $0,107 | \- | | GPT 5 Nano | Gratis | Gratis | Gratis | \- | Du legger kanskje merke til _Claude Haiku 3.5_ i brukshistorikken din. Dette er en [lavprismodell](https://opencode.ai/docs/config/#models) som brukes til å generere titlene på øktene dine. De gratis modellene: * MiniMax M2.5 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. * Big Pickle er en stealth-modell som er gratis på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle tilbakemeldinger og forbedre modellen. [Kontakt oss](mailto:contact@anoma.ly) hvis du har spørsmål. * * * ### [Automatisk påfylling](https://opencode.ai/docs/nb/zen#automatisk-p%C3%A5fylling) Hvis saldoen din går under $5, vil Zen automatisk fylle på med $20. Du kan endre beløpet for automatisk påfylling. Du kan også deaktivere automatisk påfylling helt. * * * ### [Månedlige grenser](https://opencode.ai/docs/nb/zen#m%C3%A5nedlige-grenser) Du kan også angi en månedlig bruksgrense for hele arbeidsområdet og for hver medlem av teamet ditt. La oss for eksempel si at du setter en månedlig bruksgrense til $20, Zen vil ikke bruke mer enn $20 på en måned. Men hvis du har automatisk påfylling aktivert, kan Zen ende opp belaster deg mer enn $20 hvis saldoen din går under $5. * * * ### [Utfasede modeller](https://opencode.ai/docs/nb/zen#utfasede-modeller) | Modell | Utfasingdato | | --- | --- | | Qwen3 Coder 480B | 6\. feb. 2026 | | Kimi K2 Thinking | 6\. mars 2026 | | Kimi K2 | 6\. mars 2026 | | MiniMax M2.1 | 15\. mars 2026 | | GLM 4.7 | 15\. mars 2026 | | GLM 4.6 | 15\. mars 2026 | * * * [Personvern](https://opencode.ai/docs/nb/zen#personvern) --------------------------------------------------------- Alle våre modeller er hostet i USA. Leverandørene våre følger retningslinjer om ingen datalagring og bruker ikke dataene dine til modellopplæring, med følgende unntak: * Big Pickle: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. * MiniMax M2.5 Free: I løpet av gratisperioden kan innsamlede data brukes til å forbedre modellen. * OpenAI APIer: Forespørsler oppbevares i 30 dager i samsvar med [OpenAIs datapolicyer](https://platform.openai.com/docs/guides/your-data) . * Anthropic APIer: Forespørsler oppbevares i 30 dager i samsvar med [Anthropics datapolicyer](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [For lag](https://opencode.ai/docs/nb/zen#for-lag) --------------------------------------------------- Zen fungerer også utmerket for team. Du kan invitere lagkamerater, tildele roller, kuratere modellene laget ditt bruker, og mer. Å administrere arbeidsområdet ditt er for øyeblikket gratis for team som en del av betaversjonen. Det blir vi deler mer informasjon om prisene snart. * * * ### [Roller](https://opencode.ai/docs/nb/zen#roller) Du kan invitere lagkamerater til arbeidsområdet ditt og tildele roller: * **Admin**: Administrer modeller, medlemmer, API-nøkler og fakturering * **Medlem**: Administrer kun sine egne API-nøkler Administratorer kan også sette månedlige forbruksgrenser for hvert medlem for å holde kostnadene under kontroll. * * * ### [Modelltilgang](https://opencode.ai/docs/nb/zen#modelltilgang) Administratorer kan aktivere eller deaktivere spesifikke modeller for arbeidsområdet. Forespørsler til en deaktivert modell vil returnere en feil. Dette er nyttig for tilfeller der du ønsker å deaktivere bruken av en modell som samler inn data. * * * ### [Ta med egen nøkkel](https://opencode.ai/docs/nb/zen#ta-med-egen-n%C3%B8kkel) Du kan bruke dine egne OpenAI- eller Anthropic API-nøkler mens du fortsatt har tilgang til andre modeller i Zen. Når du bruker dine egne nøkler, faktureres tokens direkte av leverandøren, ikke av Zen. For eksempel kan organisasjonen din allerede ha en nøkkel for OpenAI eller Anthropic og du vil bruke det i stedet for det Zen gir. * * * [Mål](https://opencode.ai/docs/nb/zen#m%C3%A5l) ------------------------------------------------ Vi opprettet OpenCode Zen for å: 1. **Benchmark** de beste modellene/leverandørene for kodingsagenter. 2. Ha tilgang til alternativene for **høyeste kvalitet** og ikke nedgrader ytelsen eller rute trafikk til billigere leverandører. 3. Gi videre eventuelle **prisfall** ved å selge til kostpris; så det eneste påslaget er å dekke behandlingsgebyrene våre. 4. Ha **ingen låsing** ved å la deg bruke den med en hvilken som helst annen kodeagent. Og la deg alltid bruke en hvilken som helst annen leverandør med OpenCode også. --- # Zen | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/zen#_top) Zen === Lista selecionada de modelos fornecidos pelo OpenCode. O OpenCode Zen é uma lista de modelos testados e verificados fornecidos pela equipe do OpenCode. O Zen funciona como qualquer outro provedor no OpenCode. Você faz login no OpenCode Zen e obtém sua chave de API. É **completamente opcional** e você não precisa usá-lo para utilizar o OpenCode. * * * [Contexto](https://opencode.ai/docs/pt-br/zen#contexto) -------------------------------------------------------- Existe um grande número de modelos disponíveis, mas apenas alguns desses modelos funcionam bem como agentes de codificação. Além disso, a maioria dos provedores é configurada de maneira muito diferente; portanto, você obtém desempenhos e qualidades muito diferentes. Portanto, se você estiver usando um modelo através de algo como OpenRouter, você nunca pode ter certeza se está obtendo a melhor versão do modelo que deseja. Para resolver isso, fizemos algumas coisas: 1. Testamos um grupo selecionado de modelos e conversamos com suas equipes sobre como executá-los da melhor forma. 2. Trabalhamos com alguns provedores para garantir que esses modelos estivessem sendo servidos corretamente. 3. Finalmente, realizamos benchmarks da combinação modelo/provedor e elaboramos uma lista que nos sentimos bem em recomendar. O OpenCode Zen é um gateway de IA que lhe dá acesso a esses modelos. * * * [Como funciona](https://opencode.ai/docs/pt-br/zen#como-funciona) ------------------------------------------------------------------ O OpenCode Zen funciona como qualquer outro provedor no OpenCode. 1. Você faz login no **[OpenCode Zen](https://opencode.ai/auth) **, adiciona seus dados de cobrança e copia sua chave de API. 2. Você executa o comando `/connect` no TUI, seleciona OpenCode Zen e cola sua chave de API. 3. Execute `/models` no TUI para ver a lista de modelos que recomendamos. Você é cobrado por solicitação e pode adicionar créditos à sua conta. * * * [Endpoints](https://opencode.ai/docs/pt-br/zen#endpoints) ---------------------------------------------------------- Você também pode acessar nossos modelos através dos seguintes endpoints da API. | Modelo | ID do Modelo | Endpoint | Pacote AI SDK | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | O [id do modelo](https://opencode.ai/docs/config/#models) na sua configuração do OpenCode usa o formato `opencode/`. Por exemplo, para GPT 5.2 Codex, você usaria `opencode/gpt-5.2-codex` na sua configuração. * * * ### [Modelos](https://opencode.ai/docs/pt-br/zen#modelos) Você pode buscar a lista completa de modelos disponíveis e seus metadados em: https://opencode.ai/zen/v1/models * * * [Preços](https://opencode.ai/docs/pt-br/zen#pre%C3%A7os) --------------------------------------------------------- Nós suportamos um modelo de pagamento conforme o uso. Abaixo estão os preços **por 1M de tokens**. | Modelo | Entrada | Saída | Leitura em Cache | Escrita em Cache | | --- | --- | --- | --- | --- | | Big Pickle | Grátis | Grátis | Grátis | \- | | MiniMax M2.5 Free | Grátis | Grátis | Grátis | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Grátis | Grátis | Grátis | \- | Você pode notar _Claude Haiku 3.5_ em seu histórico de uso. Este é um [modelo de baixo custo](https://opencode.ai/docs/config/#models) que é usado para gerar os títulos de suas sessões. Os modelos gratuitos: * MiniMax M2.5 Free está disponível no OpenCode por tempo limitado. A equipe está usando esse tempo para coletar feedback e melhorar o modelo. * Big Pickle é um modelo oculto que está gratuito no OpenCode por tempo limitado. A equipe está usando esse tempo para coletar feedback e melhorar o modelo. [Entre em contato conosco](mailto:contact@anoma.ly) se você tiver alguma dúvida. * * * ### [Recarga automática](https://opencode.ai/docs/pt-br/zen#recarga-autom%C3%A1tica) Se seu saldo cair abaixo de $5, o Zen recarregará automaticamente $20. Você pode alterar o valor da recarga automática. Você também pode desativar a recarga automática completamente. * * * ### [Limites mensais](https://opencode.ai/docs/pt-br/zen#limites-mensais) Você também pode definir um limite de uso mensal para todo o espaço de trabalho e para cada membro de sua equipe. Por exemplo, digamos que você defina um limite de uso mensal de $20, o Zen não usará mais de $20 em um mês. Mas se você tiver a recarga automática ativada, o Zen pode acabar cobrando mais de $20 se seu saldo cair abaixo de $5. * * * ### [Modelos obsoletos](https://opencode.ai/docs/pt-br/zen#modelos-obsoletos) | Modelo | Data de descontinuação | | --- | --- | | Qwen3 Coder 480B | 6 de fev. de 2026 | | Kimi K2 Thinking | 6 de mar. de 2026 | | Kimi K2 | 6 de mar. de 2026 | | MiniMax M2.1 | 15 de mar. de 2026 | | GLM 4.7 | 15 de mar. de 2026 | | GLM 4.6 | 15 de mar. de 2026 | * * * [Privacidade](https://opencode.ai/docs/pt-br/zen#privacidade) -------------------------------------------------------------- Todos os nossos modelos estão hospedados nos EUA. Nossos provedores seguem uma política de zero retenção e não usam seus dados para treinamento de modelos, com as seguintes exceções: * Big Pickle: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo. * MiniMax M2.5 Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo. * APIs da OpenAI: As solicitações são retidas por 30 dias de acordo com as [Políticas de Dados da OpenAI](https://platform.openai.com/docs/guides/your-data) . * APIs da Anthropic: As solicitações são retidas por 30 dias de acordo com as [Políticas de Dados da Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [Para Equipes](https://opencode.ai/docs/pt-br/zen#para-equipes) ---------------------------------------------------------------- O Zen também funciona muito bem para equipes. Você pode convidar colegas de equipe, atribuir funções, selecionar os modelos que sua equipe usa e muito mais. Gerenciar seu espaço de trabalho é atualmente gratuito para equipes como parte do beta. Em breve, compartilharemos mais detalhes sobre os preços. * * * ### [Funções](https://opencode.ai/docs/pt-br/zen#fun%C3%A7%C3%B5es) Você pode convidar colegas de equipe para seu espaço de trabalho e atribuir funções: * **Admin**: Gerenciar modelos, membros, chaves de API e cobrança * **Membro**: Gerenciar apenas suas próprias chaves de API Os administradores também podem definir limites de gastos mensais para cada membro para manter os custos sob controle. * * * ### [Acesso ao modelo](https://opencode.ai/docs/pt-br/zen#acesso-ao-modelo) Os administradores podem habilitar ou desabilitar modelos específicos para o espaço de trabalho. Solicitações feitas a um modelo desabilitado retornarão um erro. Isso é útil para casos em que você deseja desabilitar o uso de um modelo que coleta dados. * * * ### [Traga sua própria chave](https://opencode.ai/docs/pt-br/zen#traga-sua-pr%C3%B3pria-chave) Você pode usar suas próprias chaves de API da OpenAI ou Anthropic enquanto ainda acessa outros modelos no Zen. Quando você usa suas próprias chaves, os tokens são cobrados diretamente pelo provedor, não pelo Zen. Por exemplo, sua organização pode já ter uma chave para OpenAI ou Anthropic e você deseja usar essa em vez da que o Zen fornece. * * * [Objetivos](https://opencode.ai/docs/pt-br/zen#objetivos) ---------------------------------------------------------- Criamos o OpenCode Zen para: 1. **Benchmark** os melhores modelos/provedores para agentes de codificação. 2. Ter acesso às opções de **mais alta qualidade** e não degradar o desempenho ou redirecionar para provedores mais baratos. 3. Repassar quaisquer **reduções de preço** vendendo ao custo; assim, a única margem é para cobrir nossas taxas de processamento. 4. Não ter **vinculação** permitindo que você o use com qualquer outro agente de codificação. E sempre permitir que você use qualquer outro provedor com o OpenCode também. --- # Go | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/go#_top) Go == 低成本的开源编程模型订阅服务。 OpenCode Go 是一项低成本的订阅服务(**$10/月**),为您提供对流行开源编程模型的可靠访问。 Go 的工作方式与 OpenCode 中的其他提供商一样。您订阅 OpenCode Go 并获取 API 密钥。这是**完全可选的**,您不需要它也能使用 OpenCode。 它主要为国际用户设计,模型托管在美国、欧盟和新加坡,以确保稳定的全球访问。 * * * [背景](https://opencode.ai/docs/zh-cn/go#%E8%83%8C%E6%99%AF) ----------------------------------------------------------- 开源模型已经变得非常出色。它们现在在编程任务上的表现接近专有模型。而且因为许多提供商可以竞争性地提供服务,它们通常要便宜得多。 然而,获得可靠、低延迟的访问可能很困难。提供商的质量和可用性各不相同。 为了解决这个问题,我们做了一些事情: 1. 我们测试了一组精选的开源模型,并与他们的团队讨论了如何最好地运行它们。 2. 然后,我们与几家提供商合作,确保这些模型得到正确的服务。 3. 最后,我们对模型/提供商的组合进行了基准测试,并得出了一个我们乐于推荐的列表。 OpenCode Go 让您可以以 **$10/月** 的价格访问这些模型。 * * * [工作原理](https://opencode.ai/docs/zh-cn/go#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) ------------------------------------------------------------------------------- OpenCode Go 的工作方式与 OpenCode 中的其他提供商一样。 1. 登录 **[OpenCode Zen](https://opencode.ai/auth) **,订阅 Go,并复制您的 API 密钥。 2. 在 TUI 中运行 `/connect` 命令,选择 `OpenCode Go`,然后粘贴您的 API 密钥。 3. 在 TUI 中运行 `/models` 以查看通过 Go 可用的模型列表。 目前的模型列表包括: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** 随着我们测试和添加新模型,模型列表可能会发生变化。 * * * [使用限制](https://opencode.ai/docs/zh-cn/go#%E4%BD%BF%E7%94%A8%E9%99%90%E5%88%B6) ------------------------------------------------------------------------------- OpenCode Go 包含以下限制: * **5 小时限制** — $12 的使用量 * **每周限制** — $30 的使用量 * **每月限制** — $60 的使用量 限制是以美元价值定义的。这意味着您的实际请求数量取决于您使用的模型。像 MiniMax M2.5 这样更便宜的模型允许更多的请求,而像 GLM-5 这样成本更高的模型允许的请求较少。 下表提供了基于典型 Go 使用模式的估计请求数: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | 每 5 小时请求数 | 1,150 | 1,850 | 30,000 | | 每周请求数 | 2,880 | 4,630 | 75,000 | | 每月请求数 | 5,750 | 9,250 | 150,000 | 估计值基于观察到的平均请求模式: * GLM-5 — 每次请求 700 输入,52,000 缓存,150 输出 token * Kimi K2.5 — 每次请求 870 输入,55,000 缓存,200 输出 token * MiniMax M2.5 — 每次请求 300 输入,55,000 缓存,125 输出 token 您可以在 **[console](https://opencode.ai/auth) ** 中跟踪当前的用量。 随着我们从早期使用和反馈中学习,使用限制可能会发生变化。 * * * ### [定价](https://opencode.ai/docs/zh-cn/go#%E5%AE%9A%E4%BB%B7) OpenCode Go 是一个 **$10/月** 的订阅计划。以下是**每 1M token** 的价格。 | Model | Input | Output | Cached Read | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [超出限制的使用](https://opencode.ai/docs/zh-cn/go#%E8%B6%85%E5%87%BA%E9%99%90%E5%88%B6%E7%9A%84%E4%BD%BF%E7%94%A8) 如果您的 Zen 余额中还有信用点数,您可以在控制台中启用 **Use balance**(使用余额)选项。启用后,当您达到使用限制时,Go 将回退到您的 Zen 余额,而不是阻止请求。 * * * [端点](https://opencode.ai/docs/zh-cn/go#%E7%AB%AF%E7%82%B9) ----------------------------------------------------------- 您也可以通过以下 API 端点访问 Go 模型。 | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | OpenCode 配置中的 [model id](https://opencode.ai/docs/config/#models) 使用 `opencode-go/` 格式。例如,对于 Kimi K2.5,您将在配置中使用 `opencode-go/kimi-k2.5`。 * * * [隐私](https://opencode.ai/docs/zh-cn/go#%E9%9A%90%E7%A7%81) ----------------------------------------------------------- 该计划主要为国际用户设计,模型托管在美国、欧盟和新加坡,以确保稳定的全球访问。 如有任何问题,请 [联系我们](mailto:contact@anoma.ly) 。 * * * [目标](https://opencode.ai/docs/zh-cn/go#%E7%9B%AE%E6%A0%87) ----------------------------------------------------------- 我们要创建 OpenCode Go 以: 1. 通过低成本订阅让更多人**获得** AI 编程能力。 2. 提供对最佳开源编程模型的**可靠**访问。 3. 策划经过**测试和基准测试**的、适合编程代理使用的模型。 4. **无锁定**,允许您在 OpenCode 中使用任何其他提供商。 --- # IDE | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/ide#_top) IDE === La extensión OpenCode para VS Code, Cursor y otros IDE OpenCode se integra con VS Code, Cursor o cualquier IDE que admita un terminal. Simplemente ejecute `opencode` en la terminal para comenzar. * * * [Uso](https://opencode.ai/docs/es/ide#uso) ------------------------------------------- * **Inicio rápido**: use `Cmd+Esc` (Mac) o `Ctrl+Esc` (Windows/Linux) para abrir OpenCode en una vista de terminal dividida, o enfoque una sesión de terminal existente si ya se está ejecutando una. * **Nueva sesión**: use `Cmd+Shift+Esc` (Mac) o `Ctrl+Shift+Esc` (Windows/Linux) para iniciar una nueva sesión de terminal OpenCode, incluso si ya hay una abierta. También puede hacer clic en el botón OpenCode en la interfaz de usuario. * **Conciencia del contexto**: comparte automáticamente tu selección o pestaña actual con OpenCode. * **Atajos de referencia de archivos**: utilice `Cmd+Option+K` (Mac) o `Alt+Ctrl+K` (Linux/Windows) para insertar referencias de archivos. Por ejemplo, `@File#L37-42`. * * * [Instalación](https://opencode.ai/docs/es/ide#instalaci%C3%B3n) ---------------------------------------------------------------- Para instalar OpenCode en VS Code y bifurcaciones populares como Cursor, Windsurf, VSCodium: 1. Abra VS Code 2. Abra el terminal integrado 3. Ejecute `opencode`: la extensión se instala automáticamente Si, por otro lado, desea utilizar su propio IDE cuando ejecuta `/editor` o `/export` desde TUI, deberá configurar `export EDITOR="code --wait"`. [Más información](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Instalación manual](https://opencode.ai/docs/es/ide#instalaci%C3%B3n-manual) Busque **OpenCode** en Extension Marketplace y haga clic en **Instalar**. * * * ### [Solución de problemas](https://opencode.ai/docs/es/ide#soluci%C3%B3n-de-problemas) Si la extensión no se instala automáticamente: * Asegúrese de estar ejecutando `opencode` en el terminal integrado. * Confirme que el CLI para su IDE esté instalado: * Para VS Code: comando `code` * Para cursor: comando `cursor` * Para Windsurf: comando `windsurf` * Para VSCodium: comando `codium` * Si no, ejecute `Cmd+Shift+P` (Mac) o `Ctrl+Shift+P` (Windows/Linux) y busque “Shell Command: Install ‘code’ command in PATH” (o el equivalente para su IDE) * Asegúrese de que VS Code tenga permiso para instalar extensiones. --- # Go | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/go#_top) Go == 오픈 코딩 모델을 위한 저렴한 구독 서비스입니다. OpenCode Go는 인기 있는 오픈 코딩 모델에 안정적으로 액세스할 수 있는 저렴한 **월 $10** 구독 서비스입니다. Go는 OpenCode의 다른 제공자처럼 작동합니다. OpenCode Go를 구독하고 API 키를 받으세요. 이는 **완전히 선택 사항**이며 OpenCode를 사용하기 위해 반드시 사용할 필요는 없습니다. 주로 해외 사용자를 위해 설계되었으며, 안정적인 글로벌 액세스를 위해 미국, EU, 싱가포르에서 모델이 호스팅됩니다. * * * [배경](https://opencode.ai/docs/ko/go#%EB%B0%B0%EA%B2%BD) -------------------------------------------------------- 오픈 모델은 정말 좋아졌습니다. 이제 코딩 작업에서 독점 모델에 가까운 성능을 발휘합니다. 그리고 많은 제공자가 경쟁적으로 서비스할 수 있기 때문에 일반적으로 훨씬 저렴합니다. 하지만 안정적이고 지연 시간이 짧은 액세스를 얻기는 어려울 수 있습니다. 제공자마다 품질과 가용성이 다릅니다. 이를 해결하기 위해 몇 가지 작업을 수행했습니다. 1. 엄선된 오픈 모델 그룹을 테스트하고 해당 팀과 최적의 실행 방법에 대해 논의했습니다. 2. 그런 다음 몇몇 제공자와 협력하여 이것들이 올바르게 서비스되고 있는지 확인했습니다. 3. 마지막으로 모델/제공자 조합을 벤치마킹하여 추천할 만한 목록을 만들었습니다. OpenCode Go를 사용하면 **월 $10**에 이러한 모델에 액세스할 수 있습니다. * * * [작동 방식](https://opencode.ai/docs/ko/go#%EC%9E%91%EB%8F%99-%EB%B0%A9%EC%8B%9D) ------------------------------------------------------------------------------ OpenCode Go는 OpenCode의 다른 제공자처럼 작동합니다. 1. \*\*[OpenCode Zen](https://opencode.ai/auth) \*\*에 로그인하고 Go를 구독한 다음 API 키를 복사합니다. 2. TUI에서 `/connect` 명령을 실행하고 `OpenCode Go`를 선택한 다음 API 키를 붙여넣습니다. 3. TUI에서 `/models`를 실행하여 Go를 통해 사용할 수 있는 모델 목록을 확인합니다. 현재 모델 목록은 다음과 같습니다. * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** 모델 목록은 테스트하고 새로운 모델을 추가함에 따라 변경될 수 있습니다. * * * [사용 한도](https://opencode.ai/docs/ko/go#%EC%82%AC%EC%9A%A9-%ED%95%9C%EB%8F%84) ------------------------------------------------------------------------------ OpenCode Go에는 다음과 같은 한도가 포함됩니다. * **5시간 한도** — $12 사용량 * **주간 한도** — $30 사용량 * **월간 한도** — $60 사용량 한도는 달러 가치로 정의됩니다. 즉, 실제 요청 수는 사용하는 모델에 따라 다릅니다. MiniMax M2.5와 같은 저렴한 모델은 더 많은 요청을 허용하는 반면, GLM-5와 같은 고비용 모델은 더 적은 요청을 허용합니다. 아래 표는 일반적인 Go 사용 패턴을 기반으로 한 예상 요청 수를 제공합니다. | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | 5시간당 요청 수 | 1,150 | 1,850 | 30,000 | | 주당 요청 수 | 2,880 | 4,630 | 75,000 | | 월당 요청 수 | 5,750 | 9,250 | 150,000 | 추정치는 관찰된 평균 요청 패턴을 기반으로 합니다. * GLM-5 — 요청당 입력 700, 캐시 52,000, 출력 150 토큰 * Kimi K2.5 — 요청당 입력 870, 캐시 55,000, 출력 200 토큰 * MiniMax M2.5 — 요청당 입력 300, 캐시 55,000, 출력 125 토큰 \*\*[콘솔](https://opencode.ai/auth) \*\*에서 현재 사용량을 추적할 수 있습니다. 사용 한도는 초기 사용 및 피드백을 통해 학습함에 따라 변경될 수 있습니다. * * * ### [가격](https://opencode.ai/docs/ko/go#%EA%B0%80%EA%B2%A9) OpenCode Go는 **월 $10** 구독 요금제입니다. 아래는 **100만 토큰당** 가격입니다. | Model | Input | Output | Cached Read | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [한도 초과 사용](https://opencode.ai/docs/ko/go#%ED%95%9C%EB%8F%84-%EC%B4%88%EA%B3%BC-%EC%82%AC%EC%9A%A9) Zen 잔액에 크레딧이 있는 경우 콘솔에서 **잔액 사용(Use balance)** 옵션을 활성화할 수 있습니다. 활성화하면 사용 한도에 도달했을 때 요청을 차단하는 대신 Zen 잔액을 사용하게 됩니다. * * * [엔드포인트](https://opencode.ai/docs/ko/go#%EC%97%94%EB%93%9C%ED%8F%AC%EC%9D%B8%ED%8A%B8) -------------------------------------------------------------------------------------- 다음 API 엔드포인트를 통해 Go 모델에 액세스할 수도 있습니다. | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | OpenCode 설정의 [모델 ID](https://opencode.ai/docs/config/#models) 는 `opencode-go/` 형식을 사용합니다. 예를 들어 Kimi K2.5의 경우 설정에서 `opencode-go/kimi-k2.5`를 사용합니다. * * * [개인정보 보호](https://opencode.ai/docs/ko/go#%EA%B0%9C%EC%9D%B8%EC%A0%95%EB%B3%B4-%EB%B3%B4%ED%98%B8) -------------------------------------------------------------------------------------------------- 이 플랜은 주로 해외 사용자를 위해 설계되었으며, 안정적인 글로벌 액세스를 위해 미국, EU, 싱가포르에서 모델이 호스팅됩니다. 질문이 있으시면 [문의해 주세요](mailto:contact@anoma.ly) . * * * [목표](https://opencode.ai/docs/ko/go#%EB%AA%A9%ED%91%9C) -------------------------------------------------------- 우리는 다음을 위해 OpenCode Go를 만들었습니다. 1. 저렴한 구독으로 더 많은 사람들이 AI 코딩에 **접근할 수 있도록** 합니다. 2. 최고의 오픈 코딩 모델에 **안정적으로** 액세스할 수 있도록 합니다. 3. 코딩 에이전트 사용을 위해 **테스트 및 벤치마킹된** 모델을 큐레이팅합니다. 4. OpenCode와 함께 다른 제공자도 사용할 수 있도록 하여 **락인(lock-in)이 없도록** 합니다. --- # IDE | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/ide#_top) IDE === VS Code、Cursor、およびその他の IDE 用の OpenCode 拡張機能 OpenCode は、VS Code、Cursor、またはターミナルをサポートする任意の IDE と統合します。開始するには、ターミナルで `opencode` を実行するだけです。 * * * [使用法](https://opencode.ai/docs/ja/ide#%E4%BD%BF%E7%94%A8%E6%B3%95) ------------------------------------------------------------------- * **クイック起動**: `Cmd+Esc` (Mac) または `Ctrl+Esc` (Windows/Linux) を使用して、分割ターミナルビューで OpenCode を開くか、既存のターミナルセッションが既に実行されている場合はそれにフォーカスします。 * **新しいセッション**: すでに開いている場合でも、`Cmd+Shift+Esc` (Mac) または `Ctrl+Shift+Esc` (Windows/Linux) を使用して、新しい OpenCode ターミナルセッションを開始します。 UI の \[OpenCode\] ボタンをクリックすることもできます。 * **コンテキスト認識**: 現在の選択またはタブを OpenCode と自動的に共有します。 * **ファイル参照のショートカット**: ファイル参照を挿入するには、`Cmd+Option+K` (Mac) または `Alt+Ctrl+K` (Linux/Windows) を使用します。たとえば、`@File#L37-42`。 * * * [インストール](https://opencode.ai/docs/ja/ide#%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB) ------------------------------------------------------------------------------------------------- OpenCode を VS Code および Cursor、Windsurf、VSCodium などの一般的なフォークにインストールするには: 1. VS Code を開く 2. 統合ターミナルを開きます 3. `opencode` を実行します - 拡張機能は自動的にインストールされます 一方、TUI から `/editor` または `/export` を実行するときに独自の IDE を使用したい場合は、`export EDITOR="code --wait"` を設定する必要があります。 [詳細はこちら](https://opencode.ai/docs/tui/#editor-setup) 。 * * * ### [手動インストール](https://opencode.ai/docs/ja/ide#%E6%89%8B%E5%8B%95%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB) Extension Marketplace で **OpenCode** を検索し、**インストール** をクリックします。 * * * ### [トラブルシューティング](https://opencode.ai/docs/ja/ide#%E3%83%88%E3%83%A9%E3%83%96%E3%83%AB%E3%82%B7%E3%83%A5%E3%83%BC%E3%83%86%E3%82%A3%E3%83%B3%E3%82%B0) 拡張機能が自動的にインストールされない場合: * 統合ターミナルで `opencode` を実行していることを確認してください。 * IDE の CLI がインストールされていることを確認します。 * VS Code の場合: `code` コマンド * Cursor の場合: `cursor` コマンド * Windsurf の場合: `windsurf` コマンド * VSCodium の場合: `codium` コマンド * そうでない場合は、`Cmd+Shift+P` (Mac) または `Ctrl+Shift+P` (Windows/Linux) を実行し、「Shell Command: Install ‘code’ command in PATH」(または IDE の同等のコマンド) を検索します。 * VS Code に拡張機能をインストールする権限があることを確認してください --- # IDE | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/ide#_top) IDE === امتداد OpenCode لـ VS Code و Cursor وغيرها من بيئات التطوير يتكامل OpenCode مع VS Code و Cursor أو أي IDE يدعم terminal. ما عليك سوى تشغيل `opencode` في terminal للبدء. * * * [الاستخدام](https://opencode.ai/docs/ar/ide#%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85) ---------------------------------------------------------------------------------------------------- * **تشغيل سريع**: استخدم `Cmd+Esc` (Mac) أو `Ctrl+Esc` (Windows/Linux) لفتح OpenCode في عرض terminal مقسّم، أو للتركيز على جلسة terminal موجودة إذا كانت قيد التشغيل بالفعل. * **جلسة جديدة**: استخدم `Cmd+Shift+Esc` (Mac) أو `Ctrl+Shift+Esc` (Windows/Linux) لبدء جلسة terminal جديدة لـ OpenCode حتى لو كانت هناك جلسة مفتوحة. يمكنك أيضا النقر على زر OpenCode في واجهة المستخدم. * **وعي بالسياق**: شارك تلقائيا تحديدك الحالي أو تبويبك مع OpenCode. * **اختصارات الإشارة إلى الملفات**: استخدم `Cmd+Option+K` (Mac) أو `Alt+Ctrl+K` (Linux/Windows) لإدراج مراجع الملفات. مثلا: `@File#L37-42`. * * * [التثبيت](https://opencode.ai/docs/ar/ide#%D8%A7%D9%84%D8%AA%D8%AB%D8%A8%D9%8A%D8%AA) -------------------------------------------------------------------------------------- لتثبيت OpenCode على VS Code والتفرعات الشائعة مثل Cursor و Windsurf و VSCodium: 1. افتح VS Code 2. افتح terminal المدمجة 3. شغّل `opencode` - سيتم تثبيت الامتداد تلقائيا أما إذا كنت تريد استخدام IDE الخاص بك عند تشغيل `/editor` أو `/export` من واجهة TUI، فستحتاج إلى ضبط `export EDITOR="code --wait"`. [اعرف المزيد](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [التثبيت اليدوي](https://opencode.ai/docs/ar/ide#%D8%A7%D9%84%D8%AA%D8%AB%D8%A8%D9%8A%D8%AA-%D8%A7%D9%84%D9%8A%D8%AF%D9%88%D9%8A) ابحث عن **OpenCode** في Extension Marketplace وانقر **Install**. * * * ### [استكشاف الأخطاء وإصلاحها](https://opencode.ai/docs/ar/ide#%D8%A7%D8%B3%D8%AA%D9%83%D8%B4%D8%A7%D9%81-%D8%A7%D9%84%D8%A3%D8%AE%D8%B7%D8%A7%D8%A1-%D9%88%D8%A5%D8%B5%D9%84%D8%A7%D8%AD%D9%87%D8%A7) إذا فشل تثبيت الامتداد تلقائيا: * تأكد من أنك تشغّل `opencode` داخل terminal المدمجة. * تأكد من تثبيت CLI الخاصة بـ IDE لديك: * لـ VS Code: أمر `code` * لـ Cursor: أمر `cursor` * لـ Windsurf: أمر `windsurf` * لـ VSCodium: أمر `codium` * إذا لم تكن مثبتة، شغّل `Cmd+Shift+P` (Mac) أو `Ctrl+Shift+P` (Windows/Linux) وابحث عن “Shell Command: Install ‘code’ command in PATH” (أو ما يعادله في IDE لديك) * تأكد من أن VS Code لديه الصلاحية لتثبيت الامتدادات --- # IDE | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/ide#_top) IDE === L'estensione OpenCode per VS Code, Cursor e altri IDE OpenCode si integra con VS Code, Cursor o qualunque IDE che supporti un terminale. Basta eseguire `opencode` nel terminale per iniziare. * * * [Utilizzo](https://opencode.ai/docs/it/ide#utilizzo) ----------------------------------------------------- * **Avvio rapido**: usa `Cmd+Esc` (Mac) o `Ctrl+Esc` (Windows/Linux) per aprire OpenCode in una vista terminale divisa, oppure per mettere a fuoco una sessione esistente se e gia in esecuzione. * **Nuova sessione**: usa `Cmd+Shift+Esc` (Mac) o `Ctrl+Shift+Esc` (Windows/Linux) per avviare una nuova sessione di OpenCode, anche se ne esiste gia una aperta. Puoi anche cliccare il pulsante OpenCode nell’interfaccia. * **Consapevolezza del contesto**: condividi automaticamente con OpenCode la selezione corrente o la scheda attiva. * **Scorciatoie per riferimenti file**: usa `Cmd+Option+K` (Mac) o `Alt+Ctrl+K` (Linux/Windows) per inserire riferimenti a file. Per esempio, `@File#L37-42`. * * * [Installazione](https://opencode.ai/docs/it/ide#installazione) --------------------------------------------------------------- Per installare OpenCode su VS Code e fork popolari come Cursor, Windsurf, VSCodium: 1. Apri VS Code 2. Apri il terminale integrato 3. Esegui `opencode` - l’estensione si installa automaticamente Se invece vuoi usare il tuo IDE quando esegui `/editor` o `/export` dalla TUI, devi impostare `export EDITOR="code --wait"`. [Scopri di piu](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Installazione manuale](https://opencode.ai/docs/it/ide#installazione-manuale) Cerca **OpenCode** nel Marketplace delle estensioni e clicca **Install**. * * * ### [Risoluzione dei problemi](https://opencode.ai/docs/it/ide#risoluzione-dei-problemi) Se l’estensione non si installa automaticamente: * Assicurati di eseguire `opencode` nel terminale integrato. * Verifica che la CLI del tuo IDE sia installata: * Per VS Code: comando `code` * Per Cursor: comando `cursor` * Per Windsurf: comando `windsurf` * Per VSCodium: comando `codium` * In caso contrario, esegui `Cmd+Shift+P` (Mac) o `Ctrl+Shift+P` (Windows/Linux) e cerca “Shell Command: Install ‘code’ command in PATH” (o l’equivalente per il tuo IDE) * Assicurati che VS Code abbia i permessi per installare estensioni --- # IDE | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/ide#_top) IDE === Rozszerzenie opencode dla VS Code, Cursor i innych IDE opencode integruje się z VS Code, Cursorem lub obsługującym terminal IDE. Aby uruchomić, po prostu uruchom `opencode` w terminalu. * * * [Stosowanie](https://opencode.ai/docs/pl/ide#stosowanie) --------------------------------------------------------- * **Szybkie uruchomienie**: użycie `Cmd+Esc` (Mac) lub `Ctrl+Esc` (Windows/Linux), aby uruchomić opencode w uruchamianiu terminala lub skoncentruj się na uruchamianiu terminala, jeśli jest już uruchomiony. * **Nowa sesja**: `Cmd+Shift+Esc` (Mac) lub `Ctrl+Shift+Esc` (Windows/Linux), aby została nowa konfiguracja terminala opencode, nawet jeśli jest już otwarta. Możesz także kliknąć przycisk opencode w interfejsie użytkownika. * **Świadomość kontekstu**: Automatycznie udostępnia wybór lub kartę za pomocą opencode. * **Skróty do odwołania do plików**: `Cmd+Option+K` (Mac) lub `Alt+Ctrl+K` (Linux/Windows), aby wstawić odnośnik do plików. Na przykład `@File#L37-42`. * * * [Instalacja](https://opencode.ai/docs/pl/ide#instalacja) --------------------------------------------------------- Aby poznać opencode na VS Code w forkach, takich jak Cursor, Windsurf, VSCodium: 1. Otwórz kod VS 2. Otwórz innowacyjny terminal 3. Uruchom `opencode` — rozszerzenie instaluje się automatycznie Jeśli z drugiej strony chcesz zainstalować własne IDE po uruchomieniu `/editor` lub `/export` z TUI, należy zainstalować `export EDITOR="code --wait"`. [Dowiedz się więcej](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Instalacja ręczna](https://opencode.ai/docs/pl/ide#instalacja-r%C4%99czna) Wyszukaj **opencode** na rynku rozszerzonym i kliknij **Zainstaluj**. * * * ### [Rozwiązywanie problemów](https://opencode.ai/docs/pl/ide#rozwi%C4%85zywanie-problem%C3%B3w) Jeśli rozwiązanie nie zostanie zainstalowane automatycznie: * zastosowanie się, że użycie `opencode` w terminalu. * zadziałanie, że CLI dla Twojego IDE jest zainstalowane: * Dla kodu VS: polecenie `code` * Dla kura: polecenie `cursor` * Dla windsurfingu: decyzja `windsurf` * Dla VSCodium: decyzja `codium` * Jeśli nie, uruchom `Cmd+Shift+P` (Mac) lub `Ctrl+Shift+P` (Windows/Linux) i wyszukaj „Polecenie: zastosowanie decyzji„ kod ”w PATH” (lub właściwyk dla twojego IDE) * zadziałanie, że VS Code ma pozwolenie na instalację rozszerzoną --- # IDE | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/ide#_top) IDE === OpenCode-utvidelsen for VS Code, Cursor og andre IDE-er OpenCode integreres med VS Code, Cursor eller en hvilken som helst IDE som støtter en terminal. Bare kjør `opencode` i terminalen for å komme i gang. * * * [Bruk](https://opencode.ai/docs/nb/ide#bruk) --------------------------------------------- * **Hurtigstart**: Bruk `Cmd+Esc` (Mac) eller `Ctrl+Esc` (Windows/Linux) for å åpne OpenCode i en delt terminalvisning, eller fokuser en eksisterende terminaløkt hvis en allerede kjører. * **Ny økt**: Bruk `Cmd+Shift+Esc` (Mac) eller `Ctrl+Shift+Esc` (Windows/Linux) for å starte en ny OpenCode-terminaløkt, selv om en allerede er åpen. Du kan også klikke på OpenCode-knappen i UI. * **Kontekstbevissthet**: Del automatisk ditt nåværende valg eller fane med OpenCode. * **Snarveier for filreferanser**: Bruk `Cmd+Option+K` (Mac) eller `Alt+Ctrl+K` (Linux/Windows) for å sette inn filreferanser. For eksempel `@File#L37-42`. * * * [Installasjon](https://opencode.ai/docs/nb/ide#installasjon) ------------------------------------------------------------- For å installere OpenCode på VS Code og populære varianter som Cursor, Windsurf, VSCodium: 1. Åpne VS Code 2. Åpne den integrerte terminalen 3. Kjør `opencode` - utvidelsen installeres automatisk Hvis du derimot vil bruke din egen IDE når du kjører `/editor` eller `/export` fra TUI, må du angi `export EDITOR="code --wait"`. [Finn ut mer](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Manuell installasjon](https://opencode.ai/docs/nb/ide#manuell-installasjon) Søk etter **OpenCode** i Extension Marketplace og klikk på **Install**. * * * ### [Feilsøking](https://opencode.ai/docs/nb/ide#feils%C3%B8king) Hvis utvidelsen ikke kan installeres automatisk: * Sørg for at du kjører `opencode` i den integrerte terminalen. * Bekreft at CLI for IDE er installert: * For VS Code: `code` kommando * For Cursor: `cursor` kommando * For Windsurf: `windsurf` kommando * For VSCodium: `codium` kommando * Hvis ikke, kjør `Cmd+Shift+P` (Mac) eller `Ctrl+Shift+P` (Windows/Linux) og søk etter “Shell Command: Install ‘code’ command in PATH” (eller tilsvarende for din IDE) * Sørg for at VS Code har tillatelse til å installere utvidelser --- # Go | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/go#_top) Go == Abbonamento a basso costo per modelli di coding open source. OpenCode Go è un abbonamento a basso costo di **$10/mese** che ti offre un accesso affidabile ai modelli di coding open source più popolari. Go funziona come qualsiasi altro provider in OpenCode. Ti abboni a OpenCode Go e ottieni la tua chiave API. È **completamente opzionale** e non è necessario utilizzarlo per usare OpenCode. È progettato principalmente per utenti internazionali, con modelli ospitati negli Stati Uniti, UE e Singapore per un accesso globale stabile. * * * [Contesto](https://opencode.ai/docs/it/go#contesto) ---------------------------------------------------- I modelli open source sono diventati davvero validi. Ora raggiungono prestazioni vicine ai modelli proprietari per le attività di coding. E poiché molti provider possono servirli in modo competitivo, sono solitamente molto più economici. Tuttavia, ottenere un accesso affidabile e a bassa latenza può essere difficile. I provider variano in termini di qualità e disponibilità. Per risolvere questo problema, abbiamo fatto un paio di cose: 1. Abbiamo testato un gruppo selezionato di modelli open source e parlato con i loro team su come eseguirli al meglio. 2. Abbiamo poi lavorato con alcuni provider per assicurarci che questi venissero serviti correttamente. 3. Infine, abbiamo effettuato benchmark sulla combinazione modello/provider e abbiamo stilato un elenco che ci sentiamo di raccomandare. OpenCode Go ti dà accesso a questi modelli per **$10/mese**. * * * [Come funziona](https://opencode.ai/docs/it/go#come-funziona) -------------------------------------------------------------- OpenCode Go funziona come qualsiasi altro provider in OpenCode. 1. Accedi a **[OpenCode Zen](https://opencode.ai/auth) **, abbonati a Go e copia la tua chiave API. 2. Esegui il comando `/connect` nella TUI, seleziona `OpenCode Go` e incolla la tua chiave API. 3. Esegui `/models` nella TUI per vedere l’elenco dei modelli disponibili tramite Go. L’elenco attuale dei modelli include: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** L’elenco dei modelli potrebbe cambiare man mano che ne testiamo e aggiungiamo di nuovi. * * * [Limiti di utilizzo](https://opencode.ai/docs/it/go#limiti-di-utilizzo) ------------------------------------------------------------------------ OpenCode Go include i seguenti limiti: * **Limite di 5 ore** — $12 di utilizzo * **Limite settimanale** — $30 di utilizzo * **Limite mensile** — $60 di utilizzo I limiti sono definiti in valore monetario. Ciò significa che il conteggio effettivo delle richieste dipende dal modello utilizzato. Modelli più economici come MiniMax M2.5 consentono più richieste, mentre modelli più costosi come GLM-5 ne consentono meno. La tabella seguente fornisce una stima del conteggio delle richieste basata su tipici modelli di utilizzo di Go: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | richieste ogni 5 ore | 1.150 | 1.850 | 30.000 | | richieste a settimana | 2.880 | 4.630 | 75.000 | | richieste al mese | 5.750 | 9.250 | 150.000 | Le stime si basano sui modelli di richiesta medi osservati: * GLM-5 — 700 input, 52.000 cached, 150 output tokens per richiesta * Kimi K2.5 — 870 input, 55.000 cached, 200 output tokens per richiesta * MiniMax M2.5 — 300 input, 55.000 cached, 125 output tokens per richiesta Puoi monitorare il tuo utilizzo attuale nella **[console](https://opencode.ai/auth) **. I limiti di utilizzo potrebbero cambiare man mano che impariamo dall’utilizzo iniziale e dai feedback. * * * ### [Prezzi](https://opencode.ai/docs/it/go#prezzi) OpenCode Go è un piano di abbonamento da **$10/mese**. Di seguito sono riportati i prezzi **per 1M di token**. | Modello | Input | Output | Lettura Cached | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [Utilizzo oltre i limiti](https://opencode.ai/docs/it/go#utilizzo-oltre-i-limiti) Se hai anche crediti sul tuo saldo Zen, puoi abilitare l’opzione **Use balance** nella console. Quando abilitata, Go utilizzerà il tuo saldo Zen dopo aver raggiunto i limiti di utilizzo invece di bloccare le richieste. * * * [Endpoint](https://opencode.ai/docs/it/go#endpoint) ---------------------------------------------------- Puoi anche accedere ai modelli Go tramite i seguenti endpoint API. | Modello | ID Modello | Endpoint | Pacchetto AI SDK | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | Il [model id](https://opencode.ai/docs/config/#models) nella tua configurazione OpenCode utilizza il formato `opencode-go/`. Ad esempio, per Kimi K2.5, useresti `opencode-go/kimi-k2.5` nella tua configurazione. * * * [Privacy](https://opencode.ai/docs/it/go#privacy) -------------------------------------------------- Il piano è progettato principalmente per utenti internazionali, con modelli ospitati negli Stati Uniti, UE e Singapore per un accesso globale stabile. [Contattaci](mailto:contact@anoma.ly) se hai domande. * * * [Obiettivi](https://opencode.ai/docs/it/go#obiettivi) ------------------------------------------------------ Abbiamo creato OpenCode Go per: 1. Rendere l’AI per il coding **accessibile** a più persone con un abbonamento a basso costo. 2. Fornire un accesso **affidabile** ai migliori modelli di coding open source. 3. Curare modelli che sono **testati e benchmarked** per l’uso con agenti di coding. 4. Non avere **alcun lock-in** permettendoti di utilizzare qualsiasi altro provider con OpenCode. --- # Go | OpenCode [Gå til indhold](https://opencode.ai/docs/da/go#_top) Go == Lavprisabonnement for åbne kodningsmodeller. OpenCode Go er et billigt **$10/måned** abonnement, der giver dig pålidelig adgang til populære åbne kodningsmodeller. Go fungerer ligesom enhver anden udbyder i OpenCode. Du abonnerer på OpenCode Go og får din API-nøgle. Det er **helt valgfrit**, og du behøver ikke at bruge det for at bruge OpenCode. Det er primært designet til internationale brugere, med modeller hostet i USA, EU og Singapore for stabil global adgang. * * * [Baggrund](https://opencode.ai/docs/da/go#baggrund) ---------------------------------------------------- Åbne modeller er blevet virkelig gode. De når nu en ydeevne tæt på proprietære modeller til kodningsopgaver. Og fordi mange udbydere kan tilbyde dem konkurrencedygtigt, er de normalt langt billigere. Det kan dog være svært at få pålidelig adgang med lav latenstid til dem. Udbydere varierer i kvalitet og tilgængelighed. For at løse dette gjorde vi et par ting: 1. Vi testede en udvalgt gruppe af åbne modeller og talte med deres teams om, hvordan man bedst kører dem. 2. Vi arbejdede derefter sammen med nogle få udbydere for at sikre, at disse blev leveret korrekt. 3. Endelig benchmarkede vi kombinationen af model/udbyder og kom frem til en liste, som vi har det godt med at anbefale. OpenCode Go giver dig adgang til disse modeller for **$10/måned**. * * * [Sådan fungerer det](https://opencode.ai/docs/da/go#s%C3%A5dan-fungerer-det) ----------------------------------------------------------------------------- OpenCode Go fungerer ligesom enhver anden udbyder i OpenCode. 1. Du logger ind på **[OpenCode Zen](https://opencode.ai/auth) **, abonnerer på Go, og kopierer din API-nøgle. 2. Du kører kommandoen `/connect` i TUI’en, vælger `OpenCode Go`, og indsætter din API-nøgle. 3. Kør `/models` i TUI’en for at se listen over modeller, der er tilgængelige gennem Go. Den nuværende liste over modeller inkluderer: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** Listen over modeller kan ændre sig, efterhånden som vi tester og tilføjer nye. * * * [Forbrugsgrænser](https://opencode.ai/docs/da/go#forbrugsgr%C3%A6nser) ----------------------------------------------------------------------- OpenCode Go inkluderer følgende grænser: * **5 timers grænse** — $12 forbrug * **Ugentlig grænse** — $30 forbrug * **Månedlig grænse** — $60 forbrug Grænser er defineret i dollarværdi. Det betyder, at dit faktiske antal forespørgsler afhænger af den model, du bruger. Billigere modeller som MiniMax M2.5 tillader flere forespørgsler, mens dyrere modeller som GLM-5 tillader færre. Tabellen nedenfor giver et estimeret antal forespørgsler baseret på typiske Go-brugsmønstre: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | forespørgsler pr. 5 timer | 1.150 | 1.850 | 30.000 | | forespørgsler pr. uge | 2.880 | 4.630 | 75.000 | | forespørgsler pr. måned | 5.750 | 9.250 | 150.000 | Estimater er baseret på observerede gennemsnitlige forespørgselsmønstre: * GLM-5 — 700 input, 52.000 cached, 150 output tokens pr. forespørgsel * Kimi K2.5 — 870 input, 55.000 cached, 200 output tokens pr. forespørgsel * MiniMax M2.5 — 300 input, 55.000 cached, 125 output tokens pr. forespørgsel Du kan spore dit nuværende forbrug i **[konsollen](https://opencode.ai/auth) **. Forbrugsgrænser kan ændre sig, efterhånden som vi lærer fra tidlig brug og feedback. * * * ### [Priser](https://opencode.ai/docs/da/go#priser) OpenCode Go er en **$10/måned** abonnementsplan. Nedenfor er priserne **pr. 1M tokens**. | Model | Input | Output | Cached Læsning | | --- | --- | --- | --- | | GLM-5 | $1,00 | $3,20 | $0,20 | | Kimi K2.5 | $0,60 | $3,00 | $0,10 | | MiniMax M2.5 | $0,30 | $1,20 | $0,03 | * * * ### [Forbrug ud over grænser](https://opencode.ai/docs/da/go#forbrug-ud-over-gr%C3%A6nser) Hvis du også har kreditter på din Zen-saldo, kan du aktivere **Brug saldo**\-indstillingen i konsollen. Når den er aktiveret, vil Go falde tilbage på din Zen-saldo, efter du har nået dine forbrugsgrænser, i stedet for at blokere forespørgsler. * * * [Endepunkter](https://opencode.ai/docs/da/go#endepunkter) ---------------------------------------------------------- Du kan også få adgang til Go-modeller gennem følgende API-endepunkter. | Model | Model ID | Endpoint | AI SDK Pakke | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | [Model-id’et](https://opencode.ai/docs/config/#models) i din OpenCode-konfiguration bruger formatet `opencode-go/`. For eksempel, for Kimi K2.5, ville du bruge `opencode-go/kimi-k2.5` i din konfiguration. * * * [Privatliv](https://opencode.ai/docs/da/go#privatliv) ------------------------------------------------------ Planen er primært designet til internationale brugere, med modeller hostet i USA, EU og Singapore for stabil global adgang. [Kontakt os](mailto:contact@anoma.ly) hvis du har spørgsmål. * * * [Mål](https://opencode.ai/docs/da/go#m%C3%A5l) ----------------------------------------------- Vi skabte OpenCode Go for at: 1. Gøre AI-kodning **tilgængelig** for flere mennesker med et billigt abonnement. 2. Tilbyde **pålidelig** adgang til de bedste åbne kodningsmodeller. 3. Udvælge modeller, der er **testet og benchmarked** til brug med kodningsagenter. 4. Have **ingen lock-in** ved at tillade dig også at bruge enhver anden udbyder med OpenCode. --- # Go | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/go#_top) Go == Tani abonament na otwarte modele kodowania. OpenCode Go to tania subskrypcja za **10 USD miesięcznie**, która zapewnia niezawodny dostęp do popularnych otwartych modeli kodowania. Go działa jak każdy inny dostawca w OpenCode. Subskrybujesz OpenCode Go i otrzymujesz swój klucz API. Jest to **całkowicie opcjonalne** i nie musisz z tego korzystać, aby używać OpenCode. Jest przeznaczony głównie dla użytkowników międzynarodowych, z modelami hostowanymi w USA, UE i Singapurze dla stabilnego dostępu globalnego. * * * [Tło](https://opencode.ai/docs/pl/go#t%C5%82o) ----------------------------------------------- Otwarte modele stały się naprawdę dobre. Osiągają teraz wydajność zbliżoną do modeli komercyjnych w zadaniach związanych z kodowaniem. A ponieważ wielu dostawców może je obsługiwać konkurencyjnie, są zazwyczaj znacznie tańsze. Jednak uzyskanie niezawodnego dostępu o niskim opóźnieniu może być trudne. Dostawcy różnią się jakością i dostępnością. Aby to naprawić, zrobiliśmy kilka rzeczy: 1. Przetestowaliśmy wybraną grupę otwartych modeli i rozmawialiśmy z ich zespołami o tym, jak najlepiej je uruchamiać. 2. Następnie współpracowaliśmy z kilkoma dostawcami, aby upewnić się, że są one obsługiwane poprawnie. 3. Na koniec przeprowadziliśmy testy porównawcze kombinacji modelu/dostawcy i stworzyliśmy listę, którą z czystym sumieniem polecamy. OpenCode Go daje dostęp do tych modeli za **10 USD miesięcznie**. * * * [Jak to działa](https://opencode.ai/docs/pl/go#jak-to-dzia%C5%82a) ------------------------------------------------------------------- OpenCode Go działa jak każdy inny dostawca w OpenCode. 1. Logujesz się do **[OpenCode Zen](https://opencode.ai/auth) **, subskrybujesz Go i kopiujesz swój klucz API. 2. Uruchamiasz polecenie `/connect` w TUI, wybierasz `OpenCode Go` i wklejasz swój klucz API. 3. Uruchom `/models` w TUI, aby zobaczyć listę modeli dostępnych przez Go. Obecna lista modeli obejmuje: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** Lista modeli może ulec zmianie w miarę testowania i dodawania nowych. * * * [Limity użycia](https://opencode.ai/docs/pl/go#limity-u%C5%BCycia) ------------------------------------------------------------------- OpenCode Go obejmuje następujące limity: * **Limit 5-godzinny** — zużycie o wartości 12 USD * **Limit tygodniowy** — zużycie o wartości 30 USD * **Limit miesięczny** — zużycie o wartości 60 USD Limity są definiowane w wartości dolarowej. Oznacza to, że rzeczywista liczba żądań zależy od używanego modelu. Tańsze modele, takie jak MiniMax M2.5, pozwalają na więcej żądań, podczas gdy droższe modele, takie jak GLM-5, na mniej. Poniższa tabela przedstawia szacunkową liczbę żądań w oparciu o typowe wzorce użytkowania Go: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | żądania na 5 godzin | 1 150 | 1 850 | 30 000 | | żądania na tydzień | 2 880 | 4 630 | 75 000 | | żądania na miesiąc | 5 750 | 9 250 | 150 000 | Szacunki opierają się na zaobserwowanych średnich wzorcach żądań: * GLM-5 — 700 wejściowych, 52 000 zbuforowanych, 150 wyjściowych tokenów na żądanie * Kimi K2.5 — 870 wejściowych, 55 000 zbuforowanych, 200 wyjściowych tokenów na żądanie * MiniMax M2.5 — 300 wejściowych, 55 000 zbuforowanych, 125 wyjściowych tokenów na żądanie Możesz śledzić swoje bieżące zużycie w **[konsoli](https://opencode.ai/auth) **. Limity użycia mogą ulec zmianie, gdy będziemy uczyć się na podstawie wczesnego użytkowania i opinii. * * * ### [Cennik](https://opencode.ai/docs/pl/go#cennik) OpenCode Go to plan subskrypcji za **10 USD miesięcznie**. Poniżej znajdują się ceny **za 1 mln tokenów**. | Model | Wejście | Wyjście | Odczyt cache | | --- | --- | --- | --- | | GLM-5 | 1,00 $ | 3,20 $ | 0,20 $ | | Kimi K2.5 | 0,60 $ | 3,00 $ | 0,10 $ | | MiniMax M2.5 | 0,30 $ | 1,20 $ | 0,03 $ | * * * ### [Użycie poza limitami](https://opencode.ai/docs/pl/go#u%C5%BCycie-poza-limitami) Jeśli posiadasz również środki na swoim saldzie Zen, możesz włączyć opcję **Use balance** (Użyj salda) w konsoli. Po włączeniu, Go przełączy się na twoje saldo Zen po osiągnięciu limitów użycia, zamiast blokować żądania. * * * [Punkty końcowe](https://opencode.ai/docs/pl/go#punkty-ko%C5%84cowe) --------------------------------------------------------------------- Możesz również uzyskać dostęp do modeli Go poprzez następujące punkty końcowe API. | Model | Identyfikator modelu | Endpoint | Pakiet AI SDK | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | [Identyfikator modelu](https://opencode.ai/docs/config/#models) w twojej konfiguracji OpenCode używa formatu `opencode-go/`. Na przykład dla Kimi K2.5 użyłbyś `opencode-go/kimi-k2.5` w swojej konfiguracji. * * * [Prywatność](https://opencode.ai/docs/pl/go#prywatno%C5%9B%C4%87) ------------------------------------------------------------------ Plan jest przeznaczony głównie dla użytkowników międzynarodowych, z modelami hostowanymi w USA, UE i Singapurze dla stabilnego dostępu globalnego. [Skontaktuj się z nami](mailto:contact@anoma.ly) , jeśli masz jakiekolwiek pytania. * * * [Cele](https://opencode.ai/docs/pl/go#cele) -------------------------------------------- Stworzyliśmy OpenCode Go, aby: 1. Uczynić kodowanie z AI **dostępnym** dla większej liczby osób dzięki taniej subskrypcji. 2. Zapewnić **niezawodny** dostęp do najlepszych otwartych modeli kodowania. 3. Wyselekcjonować modele, które są **przetestowane i sprawdzone** pod kątem użycia z agentami kodującymi. 4. Nie wprowadzać **żadnych blokad (lock-in)**, pozwalając na korzystanie z dowolnego innego dostawcy w OpenCode. --- # Zen | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/zen#_top) Zen === opencode tarafından sağlanan seçilmiş modeller listesi. OpenCode Zen, opencode ekibi tarafından test edilip doğrulanmış modellerin bir listesidir. Zen, opencode’daki diğer sağlayıcılar gibi çalışır. OpenCode Zen’e giriş yapar ve API anahtarınızı alırsınız. Tamamen isteğe bağlıdır ve opencode kullanmak için bunu kullanmanıza gerek yoktur. * * * [Arka plan](https://opencode.ai/docs/tr/zen#arka-plan) ------------------------------------------------------- Piyasada çok sayıda model var ancak bu modellerden sadece birkaçı kodlama ajanı olarak iyi çalışır. Ayrıca çoğu sağlayıcı çok farklı şekilde yapılandırılmıştır; bu nedenle çok farklı performans ve kalite elde edersiniz. Bu nedenle, OpenRouter gibi bir şey üzerinden bir model kullanıyorsanız, istediğiniz modelin en iyi sürümünü alıp almadığınızdan asla emin olamazsınız. Bunu düzeltmek için birkaç şey yaptık: 1. Seçkin bir grup modeli test ettik ve ekipleriyle bunları en iyi nasıl çalıştıracakları hakkında konuştuk. 2. Daha sonra bunların doğru şekilde sunulduğundan emin olmak için birkaç sağlayıcıyla çalıştık. 3. Son olarak model/sağlayıcı kombinasyonunu karşılaştırdık ve önermekten memnuniyet duyduğumuz bir liste oluşturduk. OpenCode Zen, bu modellere erişmenizi sağlayan bir AI ağ geçididir. * * * [Nasıl çalışır](https://opencode.ai/docs/tr/zen#nas%C4%B1l-%C3%A7al%C4%B1%C5%9F%C4%B1r) ---------------------------------------------------------------------------------------- OpenCode Zen, opencode’daki diğer sağlayıcılar gibi çalışır. 1. **[OpenCode Zen](https://opencode.ai/auth) **’de oturum açın, fatura ayrıntılarınızı ekleyin ve API anahtarınızı kopyalayın. 2. TUI’de `/connect` komutunu çalıştırın, OpenCode Zen’i seçin ve API anahtarınızı yapıştırın. 3. Önerdiğimiz modellerin listesini görmek için TUI’de `/models` komutunu çalıştırın. İstek başına ücretlendirilirsiniz ve hesabınıza kredi ekleyebilirsiniz. * * * [Uç Noktalar](https://opencode.ai/docs/tr/zen#u%C3%A7-noktalar) ---------------------------------------------------------------- Modellerimize aşağıdaki API uç noktaları aracılığıyla da erişebilirsiniz. | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | opencode yapılandırmanızdaki [model kimliği](https://opencode.ai/docs/config/#models) `opencode/` biçimini kullanır. Örneğin, GPT 5.2 Codex için yapılandırmanızda `opencode/gpt-5.2-codex` kullanırsınız. * * * ### [Modeller](https://opencode.ai/docs/tr/zen#modeller) Mevcut modellerin tam listesini ve meta verilerini şuradan alabilirsiniz: https://opencode.ai/zen/v1/models * * * [Fiyatlandırma](https://opencode.ai/docs/tr/zen#fiyatland%C4%B1rma) -------------------------------------------------------------------- Kullandıkça öde modelini destekliyoruz. Aşağıda **1 milyon token başına** fiyatlar verilmiştir. | Model | Input | Output | Cached Read | Cached Write | | --- | --- | --- | --- | --- | | Big Pickle | Free | Free | Free | \- | | MiniMax M2.5 Free | Free | Free | Free | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Free | Free | Free | \- | Kullanım geçmişinizde _Claude Haiku 3.5_ fark edebilirsiniz. Bu, oturumlarınızın başlıklarını oluşturmak için kullanılan [düşük maliyetli bir modeldir](https://opencode.ai/docs/config/#models) . Ücretsiz modeller: * MiniMax M2.5 Free, sınırlı bir süre için OpenCode’da ücretsizdir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor. * Big Pickle, sınırlı bir süre için OpenCode’da ücretsiz olan gizli bir modeldir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor. Sorularınız varsa [bizimle iletişime geçin](mailto:contact@anoma.ly) . * * * ### [Otomatik yükleme](https://opencode.ai/docs/tr/zen#otomatik-y%C3%BCkleme) Bakiyeniz 5$‘ın altına düşerse, Zen otomatik olarak 20$ yükler. Otomatik yükleme tutarını değiştirebilirsiniz. Otomatik yüklemeyi tamamen devre dışı da bırakabilirsiniz. * * * ### [Aylık limitler](https://opencode.ai/docs/tr/zen#ayl%C4%B1k-limitler) Ayrıca tüm çalışma alanı ve ekibinizin her üyesi için aylık kullanım limiti belirleyebilirsiniz. Örneğin, aylık kullanım limitini 20$ olarak ayarladığınızı varsayalım, Zen bir ayda 20$‘dan fazla kullanmaz. Ancak otomatik yüklemeyi etkinleştirdiyseniz, bakiyeniz 5$‘ın altına düşerse Zen sizden 20$‘dan fazla ücret alabilir. * * * ### [Kullanımdan kaldırılan modeller](https://opencode.ai/docs/tr/zen#kullan%C4%B1mdan-kald%C4%B1r%C4%B1lan-modeller) | Model | Kullanımdan kaldırılma tarihi | | --- | --- | | Qwen3 Coder 480B | 6 Şub 2026 | | Kimi K2 Thinking | 6 Mar 2026 | | Kimi K2 | 6 Mar 2026 | | MiniMax M2.1 | 15 Mar 2026 | | GLM 4.7 | 15 Mar 2026 | | GLM 4.6 | 15 Mar 2026 | * * * [Gizlilik](https://opencode.ai/docs/tr/zen#gizlilik) ----------------------------------------------------- Tüm modellerimiz ABD’de barındırılmaktadır. Sağlayıcılarımız sıfır saklama politikasını izler ve aşağıdaki istisnalar dışında verilerinizi model eğitimi için kullanmaz: * Big Pickle: Ücretsiz döneminde toplanan veriler modeli iyileştirmek için kullanılabilir. * MiniMax M2.5 Free: Ücretsiz döneminde toplanan veriler modeli iyileştirmek için kullanılabilir. * OpenAI API’leri: İstekler [OpenAI’nin Veri Politikaları](https://platform.openai.com/docs/guides/your-data) uyarınca 30 gün boyunca saklanır. * Anthropic API’leri: İstekler [Anthropic’in Veri Politikaları](https://docs.anthropic.com/en/docs/claude-code/data-usage) uyarınca 30 gün boyunca saklanır. * * * [Ekipler İçin](https://opencode.ai/docs/tr/zen#ekipler-i%CC%87%C3%A7in) ------------------------------------------------------------------------ Zen ekipler için de harika çalışır. Ekip arkadaşlarınızı davet edebilir, roller atayabilir, ekibinizin kullandığı modelleri düzenleyebilir ve daha fazlasını yapabilirsiniz. Çalışma alanınızı yönetmek şu anda beta’nın bir parçası olarak ekipler için ücretsizdir. Yakında fiyatlandırma hakkında daha fazla ayrıntı paylaşacağız. * * * ### [Roller](https://opencode.ai/docs/tr/zen#roller) Ekip arkadaşlarınızı çalışma alanınıza davet edebilir ve roller atayabilirsiniz: * **Admin**: Modelleri, üyeleri, API anahtarlarını ve faturalandırmayı yönetin * **Member**: Yalnızca kendi API anahtarlarını yönetin Yöneticiler, maliyetleri kontrol altında tutmak için her üye için aylık harcama limitleri de belirleyebilir. * * * ### [Model erişimi](https://opencode.ai/docs/tr/zen#model-eri%C5%9Fimi) Yöneticiler çalışma alanı için belirli modelleri etkinleştirebilir veya devre dışı bırakabilir. Devre dışı bırakılmış bir modele yapılan istekler bir hata döndürür. Bu, veri toplayan bir modelin kullanımını devre dışı bırakmak istediğiniz durumlarda kullanışlıdır. * * * ### [Kendi anahtarınızı getirin](https://opencode.ai/docs/tr/zen#kendi-anahtar%C4%B1n%C4%B1z%C4%B1-getirin) Zen’deki diğer modellere erişmeye devam ederken kendi OpenAI veya Anthropic API anahtarlarınızı kullanabilirsiniz. Kendi anahtarlarınızı kullandığınızda, tokenler Zen tarafından değil, doğrudan sağlayıcı tarafından faturalandırılır. Örneğin, kuruluşunuzun halihazırda OpenAI veya Anthropic için bir anahtarı olabilir ve Zen’in sağladığı anahtar yerine onu kullanmak isteyebilirsiniz. * * * [Hedefler](https://opencode.ai/docs/tr/zen#hedefler) ----------------------------------------------------- OpenCode Zen’i şu amaçlarla oluşturduk: 1. Kodlama ajanları için en iyi modelleri/sağlayıcıları **kıyaslamak**. 2. **En yüksek kaliteli** seçeneklere erişmek ve performansı düşürmemek veya daha ucuz sağlayıcılara yönlendirmemek. 3. Maliyetine satış yaparak herhangi bir **fiyat düşüşünü** yansıtmak; böylece tek kâr marjı işlem ücretlerimizi karşılamaktır. 4. Başka bir kodlama ajanıyla kullanmanıza izin vererek **kilitlenmeyi önlemek**. Ve her zaman OpenCode ile başka bir sağlayıcıyı kullanmanıza izin vermek. --- # Go | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/go#_top) Go == Açık kodlama modelleri için düşük maliyetli abonelik. OpenCode Go, popüler açık kodlama modellerine güvenilir erişim sağlayan **aylık 10$** tutarında düşük maliyetli bir aboneliktir. Go, OpenCode içindeki diğer sağlayıcılar gibi çalışır. OpenCode Go’ya abone olur ve API anahtarınızı alırsınız. Bu **tamamen isteğe bağlıdır** ve OpenCode’u kullanmak için buna ihtiyacınız yoktur. Kararlı küresel erişim için ABD, AB ve Singapur’da barındırılan modellerle, öncelikli olarak uluslararası kullanıcılar için tasarlanmıştır. * * * [Arka Plan](https://opencode.ai/docs/tr/go#arka-plan) ------------------------------------------------------ Açık modeller gerçekten iyi hale geldi. Artık kodlama görevleri için tescilli modellere yakın performans sunuyorlar. Ve birçok sağlayıcı bunları rekabetçi bir şekilde sunabildiği için genellikle çok daha ucuzlar. Ancak, bunlara güvenilir ve düşük gecikmeli erişim sağlamak zor olabilir. Sağlayıcılar kalite ve kullanılabilirlik açısından farklılık gösterir. Bunu düzeltmek için birkaç şey yaptık: 1. Seçkin bir açık model grubunu test ettik ve bunları en iyi nasıl çalıştıracakları konusunda ekipleriyle görüştük. 2. Daha sonra bunların doğru şekilde sunulduğundan emin olmak için birkaç sağlayıcıyla çalıştık. 3. Son olarak, model/sağlayıcı kombinasyonunu kıyasladık ve önermekten memnuniyet duyduğumuz bir liste oluşturduk. OpenCode Go, bu modellere **aylık 10$** karşılığında erişmenizi sağlar. * * * [Nasıl çalışır](https://opencode.ai/docs/tr/go#nas%C4%B1l-%C3%A7al%C4%B1%C5%9F%C4%B1r) --------------------------------------------------------------------------------------- OpenCode Go, OpenCode’daki diğer herhangi bir sağlayıcı gibi çalışır. 1. **[OpenCode Zen](https://opencode.ai/auth) **’de oturum açın, Go’ya abone olun ve API anahtarınızı kopyalayın. 2. TUI’de `/connect` komutunu çalıştırın, `OpenCode Go`yu seçin ve API anahtarınızı yapıştırın. 3. Go üzerinden kullanılabilen modellerin listesini görmek için TUI’de `/models` komutunu çalıştırın. Mevcut model listesi şunları içerir: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** Test ettikçe ve yenilerini ekledikçe model listesi değişebilir. * * * [Kullanım sınırları](https://opencode.ai/docs/tr/go#kullan%C4%B1m-s%C4%B1n%C4%B1rlar%C4%B1) -------------------------------------------------------------------------------------------- OpenCode Go aşağıdaki sınırları içerir: * **5 saatlik sınır** — 12$ kullanım * **Haftalık sınır** — 30$ kullanım * **Aylık sınır** — 60$ kullanım Sınırlar dolar değeri üzerinden tanımlanmıştır. Bu, gerçek istek sayınızın kullandığınız modele bağlı olduğu anlamına gelir. MiniMax M2.5 gibi daha ucuz modeller daha fazla isteğe izin verirken, GLM-5 gibi daha yüksek maliyetli modeller daha azına izin verir. Aşağıdaki tablo, tipik Go kullanım modellerine dayalı tahmini bir istek sayısı sunmaktadır: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | 5 saat başına istek | 1.150 | 1.850 | 30.000 | | haftalık istek | 2.880 | 4.630 | 75.000 | | aylık istek | 5.750 | 9.250 | 150.000 | Tahminler gözlemlenen ortalama istek modellerine dayanmaktadır: * GLM-5 — İstek başına 700 girdi, 52.000 önbelleğe alınmış, 150 çıktı token’ı * Kimi K2.5 — İstek başına 870 girdi, 55.000 önbelleğe alınmış, 200 çıktı token’ı * MiniMax M2.5 — İstek başına 300 girdi, 55.000 önbelleğe alınmış, 125 çıktı token’ı Mevcut kullanımınızı **[konsoldan](https://opencode.ai/auth) ** takip edebilirsiniz. Erken kullanım ve geri bildirimlerden öğrendiklerimize göre kullanım sınırları değişebilir. * * * ### [Fiyatlandırma](https://opencode.ai/docs/tr/go#fiyatland%C4%B1rma) OpenCode Go, **aylık 10$** tutarında bir abonelik planıdır. Aşağıda **1M token başına** fiyatlar yer almaktadır. | Model | Girdi | Çıktı | Önbelleğe Alınmış Okuma | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [Sınırların ötesinde kullanım](https://opencode.ai/docs/tr/go#s%C4%B1n%C4%B1rlar%C4%B1n-%C3%B6tesinde-kullan%C4%B1m) Zen bakiyenizde krediniz de varsa, konsoldaki **Bakiyeyi kullan** (Use balance) seçeneğini etkinleştirebilirsiniz. Etkinleştirildiğinde, kullanım sınırlarınıza ulaştıktan sonra Go, istekleri engellemek yerine Zen bakiyenize geri dönecektir. * * * [Uç Noktalar](https://opencode.ai/docs/tr/go#u%C3%A7-noktalar) --------------------------------------------------------------- Go modellerine aşağıdaki API uç noktaları üzerinden de erişebilirsiniz. | Model | Model ID | Endpoint | AI SDK Paketi | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | OpenCode yapılandırmanızdaki [model kimliği](https://opencode.ai/docs/config/#models) , `opencode-go/` biçimini kullanır. Örneğin, Kimi K2.5 için yapılandırmanızda `opencode-go/kimi-k2.5` kullanırsınız. * * * [Gizlilik](https://opencode.ai/docs/tr/go#gizlilik) ---------------------------------------------------- Plan öncelikli olarak uluslararası kullanıcılar için tasarlanmıştır; modeller kararlı küresel erişim için ABD, AB ve Singapur’da barındırılmaktadır. Herhangi bir sorunuz varsa [bizimle iletişime geçin](mailto:contact@anoma.ly) . * * * [Hedefler](https://opencode.ai/docs/tr/go#hedefler) ---------------------------------------------------- OpenCode Go’yu şu amaçlarla oluşturduk: 1. Düşük maliyetli bir abonelikle yapay zeka kodlamasını daha fazla insan için **erişilebilir** kılmak. 2. En iyi açık kodlama modellerine **güvenilir** erişim sağlamak. 3. Kodlama ajanı kullanımı için **test edilmiş ve kıyaslanmış** modelleri seçmek. 4. OpenCode ile başka herhangi bir sağlayıcıyı kullanmanıza da izin vererek **kilitlenmeyi önlemek**. --- # Go | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/go#_top) Go == Kostengünstiges Abonnement für Open-Coding-Modelle. OpenCode Go ist ein kostengünstiges Abonnement für **10 $/Monat**, das dir zuverlässigen Zugriff auf beliebte Open-Coding-Modelle bietet. Go funktioniert wie jeder andere Anbieter in OpenCode. Du abonnierst OpenCode Go und erhältst deinen API-Schlüssel. Es ist **völlig optional** und du musst es nicht nutzen, um OpenCode zu verwenden. Es wurde primär für internationale Nutzer entwickelt, mit Modellen, die in den USA, der EU und Singapur gehostet werden, um einen stabilen weltweiten Zugriff zu gewährleisten. * * * [Hintergrund](https://opencode.ai/docs/de/go#hintergrund) ---------------------------------------------------------- Offene Modelle sind wirklich gut geworden. Sie erreichen bei Coding-Aufgaben mittlerweile eine Leistung, die der von proprietären Modellen nahekommt. Und da viele Anbieter sie wettbewerbsfähig bereitstellen können, sind sie in der Regel deutlich günstiger. Es kann jedoch schwierig sein, einen zuverlässigen Zugang mit niedriger Latenz zu erhalten. Die Anbieter variieren in Qualität und Verfügbarkeit. Um dies zu lösen, haben wir einige Dinge getan: 1. Wir haben eine ausgewählte Gruppe offener Modelle getestet und mit deren Teams darüber gesprochen, wie man sie am besten betreibt. 2. Anschließend haben wir mit einigen Anbietern zusammengearbeitet, um sicherzustellen, dass diese korrekt bereitgestellt werden. 3. Schließlich haben wir die Kombination aus Modell und Anbieter einem Benchmark unterzogen und eine Liste erstellt, die wir guten Gewissens empfehlen können. OpenCode Go gibt dir Zugriff auf diese Modelle für **10 $/Monat**. * * * [Wie es funktioniert](https://opencode.ai/docs/de/go#wie-es-funktioniert) -------------------------------------------------------------------------- OpenCode Go funktioniert wie jeder andere Anbieter in OpenCode. 1. Du meldest dich bei **[OpenCode Zen](https://opencode.ai/auth) ** an, abonnierst Go und kopierst deinen API-Schlüssel. 2. Du führst den Befehl `/connect` in der TUI aus, wählst `OpenCode Go` und fügst deinen API-Schlüssel ein. 3. Führe `/models` in der TUI aus, um die Liste der über Go verfügbaren Modelle zu sehen. Die aktuelle Liste der Modelle umfasst: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** Die Liste der Modelle kann sich ändern, wenn wir neue testen und hinzufügen. * * * [Nutzungslimits](https://opencode.ai/docs/de/go#nutzungslimits) ---------------------------------------------------------------- OpenCode Go beinhaltet die folgenden Limits: * **5-Stunden-Limit** — 12 $ Nutzung * **Wöchentliches Limit** — 30 $ Nutzung * **Monatliches Limit** — 60 $ Nutzung Die Limits sind in Dollarwerten definiert. Das bedeutet, dass deine tatsächliche Anzahl an Anfragen von dem verwendeten Modell abhängt. Günstigere Modelle wie MiniMax M2.5 ermöglichen mehr Anfragen, während kostenintensivere Modelle wie GLM-5 weniger zulassen. Die untenstehende Tabelle bietet eine geschätzte Anzahl an Anfragen basierend auf typischen Go-Nutzungsmustern: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | Anfragen pro 5 Std. | 1.150 | 1.850 | 30.000 | | Anfragen pro Woche | 2.880 | 4.630 | 75.000 | | Anfragen pro Monat | 5.750 | 9.250 | 150.000 | Die Schätzungen basieren auf beobachteten durchschnittlichen Nutzungsmustern: * GLM-5 — 700 Input-, 52.000 Cached-, 150 Output-Token pro Anfrage * Kimi K2.5 — 870 Input-, 55.000 Cached-, 200 Output-Token pro Anfrage * MiniMax M2.5 — 300 Input-, 55.000 Cached-, 125 Output-Token pro Anfrage Du kannst deine aktuelle Nutzung in der **[Konsole](https://opencode.ai/auth) ** verfolgen. Nutzungslimits können sich ändern, da wir aus der frühen Nutzung und dem Feedback lernen. * * * ### [Preise](https://opencode.ai/docs/de/go#preise) OpenCode Go ist ein Abonnementplan für **10 $/Monat**. Unten stehen die Preise **pro 1 Mio. Token**. | Modell | Input | Output | Cached Read | | --- | --- | --- | --- | | GLM-5 | 1,00 $ | 3,20 $ | 0,20 $ | | Kimi K2.5 | 0,60 $ | 3,00 $ | 0,10 $ | | MiniMax M2.5 | 0,30 $ | 1,20 $ | 0,03 $ | * * * ### [Nutzung über Limits hinaus](https://opencode.ai/docs/de/go#nutzung-%C3%BCber-limits-hinaus) Wenn du auch Guthaben auf deinem Zen-Konto hast, kannst du die Option **Use balance** in der Konsole aktivieren. Wenn aktiviert, greift Go auf dein Zen-Guthaben zurück, nachdem du deine Nutzungslimits erreicht hast, anstatt Anfragen zu blockieren. * * * [Endpunkte](https://opencode.ai/docs/de/go#endpunkte) ------------------------------------------------------ Du kannst auch über die folgenden API-Endpunkte auf Go-Modelle zugreifen. | Modell | Modell-ID | Endpunkt | AI SDK Paket | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | Die [Modell-ID](https://opencode.ai/docs/config/#models) in deiner OpenCode-Konfiguration verwendet das Format `opencode-go/`. Zum Beispiel würdest du für Kimi K2.5 `opencode-go/kimi-k2.5` in deiner Konfiguration verwenden. * * * [Datenschutz](https://opencode.ai/docs/de/go#datenschutz) ---------------------------------------------------------- Der Plan wurde primär für internationale Nutzer entwickelt, mit Modellen, die in den USA, der EU und Singapur gehostet werden, um einen stabilen weltweiten Zugriff zu gewährleisten. [Kontaktiere uns](mailto:contact@anoma.ly) , wenn du Fragen hast. * * * [Ziele](https://opencode.ai/docs/de/go#ziele) ---------------------------------------------- Wir haben OpenCode Go erstellt, um: 1. AI-Coding für mehr Menschen durch ein kostengünstiges Abonnement **zugänglich** zu machen. 2. **Zuverlässigen** Zugriff auf die besten Open-Coding-Modelle zu bieten. 3. Modelle zu kuratieren, die für den Einsatz von Coding-Agents **getestet und gebenchmarkt** sind. 4. **Keinen Lock-in** zu haben, indem wir dir ermöglichen, jeden anderen Anbieter ebenfalls mit OpenCode zu nutzen. --- # Go | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/go#_top) Go == Abonnement à bas coût pour les modèles de code ouverts. OpenCode Go est un abonnement à bas coût de **10 $/mois** qui vous donne un accès fiable aux modèles de code ouverts populaires. Go fonctionne comme tout autre fournisseur dans OpenCode. Vous vous abonnez à OpenCode Go et obtenez votre clé API. C’est **complètement optionnel** et vous n’avez pas besoin de l’utiliser pour utiliser OpenCode. Il est conçu principalement pour les utilisateurs internationaux, avec des modèles hébergés aux États-Unis, en UE et à Singapour pour un accès mondial stable. * * * [Contexte](https://opencode.ai/docs/fr/go#contexte) ---------------------------------------------------- Les modèles ouverts sont devenus vraiment bons. Ils atteignent maintenant des performances proches des modèles propriétaires pour les tâches de codage. Et parce que de nombreux fournisseurs peuvent les servir de manière compétitive, ils sont généralement beaucoup moins chers. Cependant, obtenir un accès fiable et à faible latence à ces modèles peut être difficile. Les fournisseurs varient en qualité et en disponibilité. Pour remédier à cela, nous avons fait plusieurs choses : 1. Nous avons testé un groupe sélectionné de modèles ouverts et discuté avec leurs équipes de la meilleure façon de les exécuter. 2. Nous avons ensuite travaillé avec quelques fournisseurs pour nous assurer qu’ils étaient servis correctement. 3. Enfin, nous avons évalué la combinaison modèle/fournisseur et établi une liste que nous nous sentons à l’aise de recommander. OpenCode Go vous donne accès à ces modèles pour **10 $/mois**. * * * [Comment ça marche](https://opencode.ai/docs/fr/go#comment-%C3%A7a-marche) --------------------------------------------------------------------------- OpenCode Go fonctionne comme tout autre fournisseur dans OpenCode. 1. Vous vous connectez à **[OpenCode Zen](https://opencode.ai/auth) **, vous vous abonnez à Go et copiez votre clé API. 2. Vous exécutez la commande `/connect` dans la TUI, sélectionnez `OpenCode Go`, et collez votre clé API. 3. Exécutez `/models` dans la TUI pour voir la liste des modèles disponibles via Go. La liste actuelle des modèles inclut : * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** La liste des modèles peut changer à mesure que nous testons et ajoutons de nouveaux modèles. * * * [Limites d’utilisation](https://opencode.ai/docs/fr/go#limites-dutilisation) ----------------------------------------------------------------------------- OpenCode Go inclut les limites suivantes : * **Limite de 5 heures** — 12 $ d’utilisation * **Limite hebdomadaire** — 30 $ d’utilisation * **Limite mensuelle** — 60 $ d’utilisation Les limites sont définies en valeur monétaire. Cela signifie que votre nombre réel de requêtes dépend du modèle que vous utilisez. Les modèles moins chers comme MiniMax M2.5 permettent plus de requêtes, tandis que les modèles plus coûteux comme GLM-5 en permettent moins. Le tableau ci-dessous fournit une estimation du nombre de requêtes basée sur des modèles d’utilisation typiques de Go : | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | requêtes par 5 heures | 1 150 | 1 850 | 30 000 | | requêtes par semaine | 2 880 | 4 630 | 75 000 | | requêtes par mois | 5 750 | 9 250 | 150 000 | Les estimations sont basées sur des modèles de requêtes moyens observés : * GLM-5 — 700 tokens d’entrée, 52 000 en cache, 150 de sortie par requête * Kimi K2.5 — 870 tokens d’entrée, 55 000 en cache, 200 de sortie par requête * MiniMax M2.5 — 300 tokens d’entrée, 55 000 en cache, 125 de sortie par requête Vous pouvez suivre votre utilisation actuelle dans la **[console](https://opencode.ai/auth) **. Les limites d’utilisation peuvent changer à mesure que nous apprenons des premiers usages et retours. * * * ### [Tarification](https://opencode.ai/docs/fr/go#tarification) OpenCode Go est un plan d’abonnement à **10 $/mois**. Ci-dessous se trouvent les prix **par 1M de tokens**. | Modèle | Entrée | Sortie | Lecture en cache | | --- | --- | --- | --- | | GLM-5 | 1,00 $ | 3,20 $ | 0,20 $ | | Kimi K2.5 | 0,60 $ | 3,00 $ | 0,10 $ | | MiniMax M2.5 | 0,30 $ | 1,20 $ | 0,03 $ | * * * ### [Utilisation au-delà des limites](https://opencode.ai/docs/fr/go#utilisation-au-del%C3%A0-des-limites) Si vous avez aussi des crédits sur votre solde Zen, vous pouvez activer l’option **Use balance** dans la console. Lorsqu’elle est activée, Go basculera sur votre solde Zen après que vous ayez atteint vos limites d’utilisation au lieu de bloquer les requêtes. * * * [Endpoints](https://opencode.ai/docs/fr/go#endpoints) ------------------------------------------------------ Vous pouvez également accéder aux modèles Go via les endpoints API suivants. | Modèle | ID du modèle | Endpoint | Package AI SDK | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | L’[ID du modèle](https://opencode.ai/docs/config/#models) dans votre configuration OpenCode utilise le format `opencode-go/`. Par exemple, pour Kimi K2.5, vous utiliseriez `opencode-go/kimi-k2.5` dans votre configuration. * * * [Confidentialité](https://opencode.ai/docs/fr/go#confidentialit%C3%A9) ----------------------------------------------------------------------- Le plan est conçu principalement pour les utilisateurs internationaux, avec des modèles hébergés aux États-Unis, en UE et à Singapour pour un accès mondial stable. [Contactez-nous](mailto:contact@anoma.ly) si vous avez des questions. * * * [Objectifs](https://opencode.ai/docs/fr/go#objectifs) ------------------------------------------------------ Nous avons créé OpenCode Go pour : 1. Rendre le codage par IA **accessible** à plus de personnes avec un abonnement à bas coût. 2. Fournir un accès **fiable** aux meilleurs modèles de code ouverts. 3. Sélectionner des modèles qui sont **testés et évalués** pour l’utilisation d’agents de codage. 4. N’avoir **aucun verrouillage** en vous permettant d’utiliser tout autre fournisseur avec OpenCode également. --- # Go | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/go#_top) Go == オープンコーディングモデル向けの低価格サブスクリプション。 OpenCode Goは、人気のあるオープンコーディングモデルへの信頼性の高いアクセスを提供する、低価格な**月額10ドル**のサブスクリプションです。 GoはOpenCodeの他のプロバイダーと同様に機能します。OpenCode Goに登録してAPIキーを取得します。これは**完全にオプション**であり、OpenCodeを使用するために必須ではありません。 主に海外ユーザー向けに設計されており、安定したグローバルアクセスのためにモデルは米国、EU、シンガポールでホストされています。 * * * [背景](https://opencode.ai/docs/ja/go#%E8%83%8C%E6%99%AF) -------------------------------------------------------- オープンモデルは非常に高性能になりました。現在では、コーディングタスクにおいてプロプライエタリモデルに近いパフォーマンスを発揮します。また、多くのプロバイダーが競争力のある価格で提供できるため、通常はずっと安価です。 しかし、信頼性が高く低遅延なアクセスを得ることは難しい場合があります。プロバイダーによって品質や可用性が異なるためです。 これを解決するために、私たちはいくつかのことを行いました。 1. 厳選されたオープンモデルをテストし、それらを最適に実行する方法についてチームと話し合いました。 2. 次に、いくつかのプロバイダーと協力して、これらが正しく提供されていることを確認しました。 3. 最後に、モデルとプロバイダーの組み合わせをベンチマークし、自信を持って推奨できるリストを作成しました。 OpenCode Goでは、これらのモデルに**月額10ドル**でアクセスできます。 * * * [仕組み](https://opencode.ai/docs/ja/go#%E4%BB%95%E7%B5%84%E3%81%BF) ------------------------------------------------------------------ OpenCode GoはOpenCodeの他のプロバイダーと同様に機能します。 1. \*\*[OpenCode Zen](https://opencode.ai/auth) \*\*にサインインし、Goに登録してAPIキーをコピーします。 2. TUIで`/connect`コマンドを実行し、`OpenCode Go`を選択してAPIキーを貼り付けます。 3. TUIで`/models`を実行して、Go経由で利用可能なモデルのリストを確認します。 現在のモデルリストには以下が含まれます: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** モデルのリストは、テストや新しいモデルの追加に伴い変更される可能性があります。 * * * [利用制限](https://opencode.ai/docs/ja/go#%E5%88%A9%E7%94%A8%E5%88%B6%E9%99%90) ---------------------------------------------------------------------------- OpenCode Goには以下の制限が含まれます: * **5時間制限** — 12ドル分の利用 * **週間制限** — 30ドル分の利用 * **月間制限** — 60ドル分の利用 制限は金額で定義されています。つまり、実際のリクエスト数は使用するモデルによって異なります。MiniMax M2.5のような安価なモデルではより多くのリクエストが可能ですが、GLM-5のような高価なモデルでは少なくなります。 下の表は、典型的なGoの使用パターンに基づいた推定リクエスト数を示しています: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | 5時間あたりのリクエスト数 | 1,150 | 1,850 | 30,000 | | 週間リクエスト数 | 2,880 | 4,630 | 75,000 | | 月間リクエスト数 | 5,750 | 9,250 | 150,000 | 推定値は、観測された平均的なリクエストパターンに基づいています: * GLM-5 — 1リクエストあたり入力700、キャッシュ52,000、出力150トークン * Kimi K2.5 — 1リクエストあたり入力870、キャッシュ55,000、出力200トークン * MiniMax M2.5 — 1リクエストあたり入力300、キャッシュ55,000、出力125トークン 現在の使用状況は\*\*[コンソール](https://opencode.ai/auth) \*\*で確認できます。 利用制限は、初期の使用状況やフィードバックに基づいて変更される可能性があります。 * * * ### [価格](https://opencode.ai/docs/ja/go#%E4%BE%A1%E6%A0%BC) OpenCode Goは**月額10ドル**のサブスクリプションプランです。以下は**100万トークンあたり**の価格です。 | モデル | 入力 | 出力 | キャッシュ読み込み | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [制限を超えた利用](https://opencode.ai/docs/ja/go#%E5%88%B6%E9%99%90%E3%82%92%E8%B6%85%E3%81%88%E3%81%9F%E5%88%A9%E7%94%A8) Zen残高にクレジットがある場合、コンソールで\*\*残高を使用 (Use balance)\*\*オプションを有効にできます。有効にすると、利用制限に達した後、リクエストをブロックする代わりにZen残高が使用されます。 * * * [エンドポイント](https://opencode.ai/docs/ja/go#%E3%82%A8%E3%83%B3%E3%83%89%E3%83%9D%E3%82%A4%E3%83%B3%E3%83%88) ---------------------------------------------------------------------------------------------------------- 以下のAPIエンドポイントを通じてGoモデルにアクセスすることもできます。 | モデル | モデルID | エンドポイント | AI SDKパッケージ | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | OpenCode設定の[モデルID](https://opencode.ai/docs/config/#models) は、`opencode-go/`という形式を使用します。たとえば、Kimi K2.5の場合、設定で`opencode-go/kimi-k2.5`を使用します。 * * * [プライバシー](https://opencode.ai/docs/ja/go#%E3%83%97%E3%83%A9%E3%82%A4%E3%83%90%E3%82%B7%E3%83%BC) ------------------------------------------------------------------------------------------------ このプランは主に海外ユーザー向けに設計されており、安定したグローバルアクセスのためにモデルは米国、EU、シンガポールでホストされています。 ご質問がある場合は[お問い合わせください](mailto:contact@anoma.ly) 。 * * * [目標](https://opencode.ai/docs/ja/go#%E7%9B%AE%E6%A8%99) -------------------------------------------------------- OpenCode Goを作成した目的は以下の通りです: 1. 低価格のサブスクリプションで、より多くの人々がAIコーディングに**アクセス**できるようにすること。 2. 最高のオープンコーディングモデルへの**信頼性の高い**アクセスを提供すること。 3. コーディングエージェントでの使用向けに**テストおよびベンチマーク**されたモデルを厳選すること。 4. OpenCodeで他のプロバイダーも使用できるようにすることで、**ロックインを排除**すること。 --- # IDE | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/ide#_top) IDE === Расширение opencode для VS Code, Cursor и других IDE. opencode интегрируется с VS Code, Cursor или любой IDE, поддерживающей терминал. Просто запустите `opencode` в терминале, чтобы начать. * * * [Использование](https://opencode.ai/docs/ru/ide#%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) -------------------------------------------------------------------------------------------------------------------------------- * **Быстрый запуск**: используйте `Cmd+Esc` (Mac) или `Ctrl+Esc` (Windows/Linux), чтобы открыть opencode в разделенном представлении терминала, или сфокусируйтесь на существующем сеансе терминала, если он уже запущен. * **Новый сеанс**: используйте `Cmd+Shift+Esc` (Mac) или `Ctrl+Shift+Esc` (Windows/Linux), чтобы начать новый сеанс терминала opencode, даже если он уже открыт. Вы также можете нажать кнопку opencode в пользовательском интерфейсе. * **Осведомленность о контексте**: автоматически делитесь своим текущим выбором или вкладкой с помощью opencode. * **Шорткаты ссылок на файлы**: Используйте `Cmd+Option+K` (Mac) или `Alt+Ctrl+K` (Linux/Windows) для вставки ссылок на файлы. Например, `@File#L37-42`. * * * [Установка](https://opencode.ai/docs/ru/ide#%D1%83%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0) ---------------------------------------------------------------------------------------------------- Чтобы установить opencode на VS Code и популярные форки, такие как Cursor, Windsurf, VSCodium: 1. Откройте VS Code 2. Откройте встроенный терминал 3. Запустите `opencode` — расширение установится автоматически. С другой стороны, если вы хотите использовать собственную IDE при запуске `/editor` или `/export` из TUI, вам необходимо установить `export EDITOR="code --wait"`. [Подробнее](https://opencode.ai/docs/tui/#editor-setup) . * * * ### [Ручная установка](https://opencode.ai/docs/ru/ide#%D1%80%D1%83%D1%87%D0%BD%D0%B0%D1%8F-%D1%83%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0) Найдите **opencode** в магазине расширений и нажмите **Установить**. * * * ### [Устранение неполадок](https://opencode.ai/docs/ru/ide#%D1%83%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BD%D0%B5%D0%BF%D0%BE%D0%BB%D0%B0%D0%B4%D0%BE%D0%BA) Если расширение не устанавливается автоматически: * Убедитесь, что вы используете `opencode` во встроенном терминале. * Убедитесь, что CLI для вашей IDE установлен: * Для Code: команда `code`. * Для Cursor: команда `cursor`. * Для Windsurf: команда `windsurf`. * Для VSCodium: команда `codium`. * Если нет, запустите `Cmd+Shift+P` (Mac) или `Ctrl+Shift+P` (Windows/Linux) и найдите “Shell Command: Install ‘code’ command in PATH” (или эквивалент для вашей IDE). * Убедитесь, что у VS Code есть разрешение на установку расширений. --- # OpenCode Zen | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/zen#_top) OpenCode Zen ============ OpenCode によって提供されるモデルの厳選されたリスト。 OpenCode Zen は、OpenCode チームによって提供される、テストおよび検証されたモデルのリストです。 Zen は OpenCode の他のプロバイダーと同様に機能します。 OpenCode Zen にログインすると、API キーを取得できます。これは **完全にオプション** であり、OpenCode を使用するために使用する必要はありません。 * * * [背景](https://opencode.ai/docs/ja/zen#%E8%83%8C%E6%99%AF) --------------------------------------------------------- 世の中には多数のモデルがありますが、コーディングエージェントとしてうまく機能するのはごく一部です。さらに、ほとんどのプロバイダーは構成が大きく異なるため、パフォーマンスと品質も大きく異なります。 OpenRouter などを通じてモデルを使用している場合、必要なモデルの最高のバージョンを取得できているか確信が持てません。 これを修正するために、いくつかのことを行いました。 1. 選抜したモデルグループをテストし、それらを最適に実行する方法についてチームと話し合いました。 2. その後、いくつかのプロバイダーと協力して、これらが確実に提供されるようにしました。 3. 最後に、モデルとプロバイダーの組み合わせをベンチマークし、自信を持ってお勧めできるリストを作成しました。 OpenCode Zen は、これらのモデルへのアクセスを可能にする AI ゲートウェイです。 * * * [仕組み](https://opencode.ai/docs/ja/zen#%E4%BB%95%E7%B5%84%E3%81%BF) ------------------------------------------------------------------- OpenCode Zen は、OpenCode の他のプロバイダーと同様に機能します。 1. **[OpenCode Zen](https://opencode.ai/auth) ** にサインインし、請求情報を追加して、API キーをコピーします。 2. TUI で `/connect` コマンドを実行し、OpenCode Zen を選択して API キーを貼り付けます。 3. TUI で `/models` を実行すると、推奨されるモデルのリストが表示されます。 リクエストごとに料金が請求され、アカウントにクレジットを追加できます。 * * * [エンドポイント](https://opencode.ai/docs/ja/zen#%E3%82%A8%E3%83%B3%E3%83%89%E3%83%9D%E3%82%A4%E3%83%B3%E3%83%88) ----------------------------------------------------------------------------------------------------------- 次の API エンドポイントを通じてモデルにアクセスすることもできます。 | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | OpenCode 設定の [model id](https://opencode.ai/docs/config/#models) `opencode/` 形式を使用します。たとえば、GPT 5.2 Codex の場合は、 設定で `opencode/gpt-5.2-codex` を使用してください。 * * * ### [モデル](https://opencode.ai/docs/ja/zen#%E3%83%A2%E3%83%87%E3%83%AB) 利用可能なモデルとそのメタデータの完全なリストは、次から取得できます。 https://opencode.ai/zen/v1/models * * * [価格](https://opencode.ai/docs/ja/zen#%E4%BE%A1%E6%A0%BC) --------------------------------------------------------- 当社は従量課金制モデルをサポートしています。以下は **100 万トークンあたりの価格**です。 | Model | Input | Output | Cached Read | Cached Write | | --- | --- | --- | --- | --- | | Big Pickle | Free | Free | Free | \- | | MiniMax M2.5 Free | Free | Free | Free | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Free | Free | Free | \- | 使用履歴に _Claude Haiku 3.5_ が表示されるかもしれません。これは [セッションのタイトルを生成するために使用される低コストモデル](https://opencode.ai/docs/config/#models) です。 無料のモデル: * MiniMax M2.5 Free は期間限定で OpenCode で利用可能です。チームはこの期間を利用してフィードバックを収集し、モデルを改善します。 * Big Pickle は、期間限定で OpenCode で無料で利用できるステルスモデルです。チームはこの期間を利用してフィードバックを収集し、モデルを改善します。 ご質問がございましたら、[お問い合わせ](mailto:contact@anoma.ly) ください。 * * * ### [自動リロード](https://opencode.ai/docs/ja/zen#%E8%87%AA%E5%8B%95%E3%83%AA%E3%83%AD%E3%83%BC%E3%83%89) 残高が 5 ドルを下回ると、Zen は自動的に 20 ドルをリロードします。 自動リロード量を変更できます。自動リロードを完全に無効にすることもできます。 * * * ### [月ごとの制限](https://opencode.ai/docs/ja/zen#%E6%9C%88%E3%81%94%E3%81%A8%E3%81%AE%E5%88%B6%E9%99%90) ワークスペース全体およびチームの各メンバーの月ごとの使用制限を設定することもできます。 たとえば、毎月の使用制限を 20 ドルに設定したとします。Zen は月に 20 ドル以上を使用しません。ただし、自動リロードを有効にしている場合、残高が 5 ドルを下回ると、Zen が 20 ドル以上の請求を行う可能性があります。 * * * ### [非推奨モデル](https://opencode.ai/docs/ja/zen#%E9%9D%9E%E6%8E%A8%E5%A5%A8%E3%83%A2%E3%83%87%E3%83%AB) | Model | Deprecation date | | --- | --- | | Qwen3 Coder 480B | 2026年2月6日 | | Kimi K2 Thinking | 2026年3月6日 | | Kimi K2 | 2026年3月6日 | | MiniMax M2.1 | 2026年3月15日 | | GLM 4.7 | 2026年3月15日 | | GLM 4.6 | 2026年3月15日 | * * * [プライバシー](https://opencode.ai/docs/ja/zen#%E3%83%97%E3%83%A9%E3%82%A4%E3%83%90%E3%82%B7%E3%83%BC) ------------------------------------------------------------------------------------------------- すべてのモデルは米国でホストされています。当社のプロバイダーはゼロ保持ポリシーに従い、次の例外を除いて、モデルのトレーニングにデータを使用しません。 * Big Pickle: 無料期間中、収集されたデータはモデルの改善に使用される場合があります。 * MiniMax M2.5 Free: 無料期間中、収集されたデータはモデルの改善に使用される場合があります。 * OpenAI API: リクエストは [OpenAI のデータポリシー](https://platform.openai.com/docs/guides/your-data) に従い、30 日間保持されます。 * Anthropic API: リクエストは [Anthropic のデータポリシー](https://docs.anthropic.com/en/docs/claude-code/data-usage) に従い、30 日間保持されます。 * * * [チーム向け](https://opencode.ai/docs/ja/zen#%E3%83%81%E3%83%BC%E3%83%A0%E5%90%91%E3%81%91) --------------------------------------------------------------------------------------- Zen はチームにも効果的です。チームメイトを招待し、役割を割り当て、チームが使用するモデルをキュレートすることなどができます。 ワークスペースの管理は現在、ベータ版の一部としてチームに無料で提供されています。価格の詳細については近日中にお知らせします。 * * * ### [ロール](https://opencode.ai/docs/ja/zen#%E3%83%AD%E3%83%BC%E3%83%AB) チームメイトをワークスペースに招待し、役割を割り当てることができます。 * **管理者**: モデル、メンバー、API キー、請求を管理します。 * **メンバー**: 自分の API キーのみを管理します 管理者は、コストを管理するために各メンバーの毎月の支出制限を設定することもできます。 * * * ### [モデルアクセス](https://opencode.ai/docs/ja/zen#%E3%83%A2%E3%83%87%E3%83%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9) 管理者は、ワークスペースの特定のモデルを有効または無効にすることができます。無効なモデルに対してリクエストを行うと、エラーが返されます。 これは、モデルの使用を無効にしたい場合に便利です。 データを収集します。 * * * ### [自分のキーを持ち込む](https://opencode.ai/docs/ja/zen#%E8%87%AA%E5%88%86%E3%81%AE%E3%82%AD%E3%83%BC%E3%82%92%E6%8C%81%E3%81%A1%E8%BE%BC%E3%82%80) Zen の他のモデルにアクセスしながら、独自の OpenAI または Anthropic API キーを使用できます。 独自のキーを使用する場合、トークンは Zen ではなくプロバイダーによって直接請求されます。 たとえば、組織はすでに OpenAI または Anthropic のキーを持っている可能性があります。 Zen が提供するものの代わりにそれを使用したいとします。 * * * [目標](https://opencode.ai/docs/ja/zen#%E7%9B%AE%E6%A8%99) --------------------------------------------------------- 私たちは次の目的で OpenCode Zen を作成しました。 1. **ベンチマーク** コーディングエージェントに最適なモデル/プロバイダー。 2. **最高品質**のオプションにアクセスでき、パフォーマンスをダウングレードしたり、より安価なプロバイダーにルートしたりする必要はありません。 3. 原価で販売することで**価格下落**を転嫁します。したがって、唯一のマークアップは処理手数料をカバーすることです。 4. 他のコーディングエージェントとの併用を許可することで、**ロックイン**がなくなります。また、常に OpenCode で他のプロバイダーも使用できるようにします。 --- # เซน | OpenCode [Skip to content](https://opencode.ai/docs/th/zen#_top) เซน === รายการโมเดลที่คัดสรรโดย OpenCode OpenCode Zen คือรายการโมเดลที่ได้รับการทดสอบและตรวจสอบแล้วโดยทีมงาน OpenCode Zen ทำงานเหมือนกับผู้ให้บริการรายอื่นๆ ใน OpenCode คุณเข้าสู่ระบบ OpenCode Zen และรับ รหัส API ของคุณ มันเป็น **ทางเลือกโดยสมบูรณ์** และคุณไม่จำเป็นต้องใช้มันเพื่อใช้งาน โอเพ่นโค้ด * * * [ภูมิหลัง](https://opencode.ai/docs/th/zen#%E0%B8%A0%E0%B8%B9%E0%B8%A1%E0%B8%B4%E0%B8%AB%E0%B8%A5%E0%B8%B1%E0%B8%87) --------------------------------------------------------------------------------------------------------------------- มีหลายรุ่นครับ แต่มีเพียงไม่กี่รุ่นเท่านั้น โมเดลเหล่านี้ทำงานได้ดีในฐานะตัวแทนการเข้ารหัส นอกจากนี้ผู้ให้บริการส่วนใหญ่ก็มี กำหนดค่าแตกต่างกันมาก ดังนั้นคุณจึงได้รับประสิทธิภาพและคุณภาพที่แตกต่างกันมาก ดังนั้นหากคุณใช้โมเดลผ่าน OpenRouter คุณจะไม่มีวันเป็นเช่นนั้น แน่ใจว่าคุณได้รับรุ่นที่ดีที่สุดของรุ่นที่คุณต้องการหรือไม่ เพื่อแก้ไขปัญหานี้ เราได้ทำสองสิ่ง: 1. เราได้ทดสอบกลุ่มโมเดลที่ได้รับการคัดเลือกและพูดคุยกับทีมของพวกเขาเกี่ยวกับวิธีการ ดีที่สุดเรียกใช้พวกเขา 2. จากนั้นเราทำงานร่วมกับผู้ให้บริการบางรายเพื่อให้แน่ใจว่าผู้ให้บริการเหล่านี้ได้รับบริการแล้ว อย่างถูกต้อง 3. ในที่สุด เราก็เปรียบเทียบการรวมกันของ model/provider และได้ผลลัพธ์ออกมา กับรายการที่เรารู้สึกดีมาแนะนำ OpenCode Zen เป็นเกตเวย์ AI ที่ให้คุณเข้าถึงโมเดลเหล่านี้ * * * [มันทำงานอย่างไร](https://opencode.ai/docs/th/zen#%E0%B8%A1%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B9%84%E0%B8%A3) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode Zen ทำงานเหมือนกับผู้ให้บริการรายอื่นๆ ใน OpenCode 1. คุณลงชื่อเข้าใช้ **[OpenCode Zen](https://opencode.ai/auth) ** เพิ่มการเรียกเก็บเงินของคุณ รายละเอียดและคัดลอกรหัส API ของคุณ 2. คุณรันคำสั่ง `/connect` ใน TUI เลือก OpenCode Zen และวางคีย์ API ของคุณ 3. เรียกใช้ `/models` ใน TUI เพื่อดูรายการรุ่นที่เราแนะนำ คุณจะถูกเรียกเก็บเงินตามคำขอและคุณสามารถเพิ่มเครดิตให้กับบัญชีของคุณได้ * * * [จุดสิ้นสุด](https://opencode.ai/docs/th/zen#%E0%B8%88%E0%B8%B8%E0%B8%94%E0%B8%AA%E0%B8%B4%E0%B9%89%E0%B8%99%E0%B8%AA%E0%B8%B8%E0%B8%94) ----------------------------------------------------------------------------------------------------------------------------------------- คุณยังสามารถเข้าถึงโมเดลของเราผ่านทางจุดสิ้นสุด API ต่อไปนี้ | Model | Model ID | Endpoint | แพ็คเกจ AI SDK | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | [model id](https://opencode.ai/docs/config/#models) ในการกำหนดค่า OpenCode ของคุณ ใช้รูปแบบ `opencode/` ตัวอย่างเช่น สำหรับ GPT 5.2 Codex คุณจะต้อง ใช้ `opencode/gpt-5.2-codex` ในการกำหนดค่าของคุณ * * * ### [โมเดล](https://opencode.ai/docs/th/zen#%E0%B9%82%E0%B8%A1%E0%B9%80%E0%B8%94%E0%B8%A5) คุณสามารถดึงรายชื่อรุ่นที่มีจำหน่ายและข้อมูลเมตาทั้งหมดได้จาก: https://opencode.ai/zen/v1/models * * * [ราคา](https://opencode.ai/docs/th/zen#%E0%B8%A3%E0%B8%B2%E0%B8%84%E0%B8%B2) ----------------------------------------------------------------------------- เราสนับสนุนรูปแบบการจ่ายเงินตามการใช้งาน ด้านล่างนี้คือราคา **ต่อtokens 1M** | Model | ป้อนข้อมูล | เอาท์พุต | แคชอ่าน | เขียนในแคช | | --- | --- | --- | --- | --- | | Big Pickle | ฟรี | ฟรี | ฟรี | \- | | MiniMax M2.5 Free | ฟรี | ฟรี | ฟรี | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | $0.375 | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | ฟรี | ฟรี | ฟรี | \- | คุณอาจสังเกตเห็น _Claude Haiku 3.5_ ในประวัติการใช้งานของคุณ นี่คือ [โมเดลราคาประหยัด](https://opencode.ai/docs/config/#models) ที่ใช้ในการสร้างชื่อเซสชันของคุณ รุ่นฟรี: * MiniMax M2.5 Free พร้อมใช้งานบน OpenCode ในระยะเวลาจำกัด ทีมงานใช้เวลานี้เพื่อรวบรวมคำติชมและปรับปรุงโมเดล * Big Pickle เป็นโมเดลล่องหนที่ให้บริการฟรีบน OpenCode ในระยะเวลาจำกัด ทีมงานใช้เวลานี้เพื่อรวบรวมคำติชมและปรับปรุงโมเดล [Contact us](mailto:contact@anoma.ly) if you have any questions. * * * ### [โหลดซ้ำอัตโนมัติ](https://opencode.ai/docs/th/zen#%E0%B9%82%E0%B8%AB%E0%B8%A5%E0%B8%94%E0%B8%8B%E0%B9%89%E0%B8%B3%E0%B8%AD%E0%B8%B1%E0%B8%95%E0%B9%82%E0%B8%99%E0%B8%A1%E0%B8%B1%E0%B8%95%E0%B8%B4) หากยอดคงเหลือของคุณต่ำกว่า $5 Zen จะโหลด $20 อีกครั้งโดยอัตโนมัติ คุณสามารถเปลี่ยนจำนวนการโหลดอัตโนมัติได้ คุณยังสามารถปิดการโหลดอัตโนมัติทั้งหมดได้อีกด้วย * * * ### [ขีดจำกัดรายเดือน](https://opencode.ai/docs/th/zen#%E0%B8%82%E0%B8%B5%E0%B8%94%E0%B8%88%E0%B8%B3%E0%B8%81%E0%B8%B1%E0%B8%94%E0%B8%A3%E0%B8%B2%E0%B8%A2%E0%B9%80%E0%B8%94%E0%B8%B7%E0%B8%AD%E0%B8%99) คุณยังสามารถกำหนดขีดจำกัดการใช้งานรายเดือนสำหรับพื้นที่ทำงานทั้งหมดและสำหรับแต่ละรายการได้ สมาชิกในทีมของคุณ ตัวอย่างเช่น สมมติว่าคุณกำหนดขีดจำกัดการใช้งานรายเดือนไว้ที่ 20 ดอลลาร์ Zen จะไม่ใช้ มากกว่า $20 ในหนึ่งเดือน แต่ถ้าคุณเปิดใช้งานการโหลดซ้ำอัตโนมัติ Zen อาจจะจบลง เรียกเก็บเงินคุณมากกว่า $20 หากยอดคงเหลือของคุณต่ำกว่า $5 * * * ### [โมเดลที่เลิกใช้แล้ว](https://opencode.ai/docs/th/zen#%E0%B9%82%E0%B8%A1%E0%B9%80%E0%B8%94%E0%B8%A5%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%80%E0%B8%A5%E0%B8%B4%E0%B8%81%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B9%81%E0%B8%A5%E0%B9%89%E0%B8%A7) | Model | วันที่เลิกใช้ | | --- | --- | | Qwen3 Coder 480B | 6 ก.พ. 2026 | | Kimi K2 Thinking | 6 มี.ค. 2026 | | Kimi K2 | 6 มี.ค. 2026 | | MiniMax M2.1 | 15 มี.ค. 2026 | | GLM 4.7 | 15 มี.ค. 2026 | | GLM 4.6 | 15 มี.ค. 2026 | * * * [ความเป็นส่วนตัว](https://opencode.ai/docs/th/zen#%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B9%80%E0%B8%9B%E0%B9%87%E0%B8%99%E0%B8%AA%E0%B9%88%E0%B8%A7%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- โมเดลทั้งหมดของเราโฮสต์ในสหรัฐอเมริกา ผู้ให้บริการของเราปฏิบัติตามนโยบายการเก็บรักษาเป็นศูนย์ และไม่ใช้ข้อมูลของคุณสำหรับการฝึกโมเดล โดยมีข้อยกเว้นต่อไปนี้: * Big Pickle: ในช่วงระยะเวลาฟรี ข้อมูลที่รวบรวมอาจนำไปใช้ในการปรับปรุงโมเดลได้ * MiniMax M2.5 Free: ในช่วงระยะเวลาฟรี ข้อมูลที่รวบรวมอาจนำไปใช้ในการปรับปรุงโมเดล * OpenAI API: คำขอจะถูกเก็บไว้เป็นเวลา 30 วันตาม [นโยบายข้อมูลของ OpenAI](https://platform.openai.com/docs/guides/your-data) * Anthropic API: คำขอจะถูกเก็บไว้เป็นเวลา 30 วันตาม [นโยบายข้อมูลของ Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) * * * [สำหรับทีม](https://opencode.ai/docs/th/zen#%E0%B8%AA%E0%B8%B3%E0%B8%AB%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%97%E0%B8%B5%E0%B8%A1) ------------------------------------------------------------------------------------------------------------------------------- Zen ยังใช้งานได้ดีกับทีมอีกด้วย คุณสามารถเชิญเพื่อนร่วมทีม กำหนดบทบาท ดูแลจัดการได้ โมเดลที่ทีมของคุณใช้ และอื่นๆ ขณะนี้การจัดการพื้นที่ทำงานของคุณให้บริการฟรีสำหรับทีมโดยเป็นส่วนหนึ่งของเวอร์ชันเบต้า เราจะเป็น แบ่งปันรายละเอียดเพิ่มเติมเกี่ยวกับราคาเร็ว ๆ นี้ * * * ### [บทบาท](https://opencode.ai/docs/th/zen#%E0%B8%9A%E0%B8%97%E0%B8%9A%E0%B8%B2%E0%B8%97) คุณสามารถเชิญเพื่อนร่วมทีมเข้ามาในพื้นที่ทำงานของคุณและมอบหมายบทบาทได้: * **ผู้ดูแลระบบ**: จัดการโมเดล สมาชิก คีย์ API และการเรียกเก็บเงิน * **สมาชิก**: จัดการเฉพาะคีย์ API ของตนเองเท่านั้น ผู้ดูแลระบบยังสามารถกำหนดวงเงินการใช้จ่ายรายเดือนสำหรับสมาชิกแต่ละคนเพื่อควบคุมค่าใช้จ่ายได้ * * * ### [การเข้าถึงโมเดล](https://opencode.ai/docs/th/zen#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B8%96%E0%B8%B6%E0%B8%87%E0%B9%82%E0%B8%A1%E0%B9%80%E0%B8%94%E0%B8%A5) ผู้ดูแลระบบสามารถเปิดหรือปิดใช้งานโมเดลเฉพาะสำหรับพื้นที่ทำงานได้ คำขอที่ทำกับโมเดลที่ถูกปิดใช้งานจะส่งคืนข้อผิดพลาด สิ่งนี้มีประโยชน์สำหรับกรณีที่คุณต้องการปิดการใช้งานโมเดลนั้น รวบรวมข้อมูล * * * ### [นำคีย์ของคุณมาเอง](https://opencode.ai/docs/th/zen#%E0%B8%99%E0%B8%B3%E0%B8%84%E0%B8%B5%E0%B8%A2%E0%B9%8C%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%84%E0%B8%B8%E0%B8%93%E0%B8%A1%E0%B8%B2%E0%B9%80%E0%B8%AD%E0%B8%87) คุณสามารถใช้คีย์ OpenAI หรือ Anthropic API ของคุณเองในขณะที่ยังเข้าถึงรุ่นอื่นๆ ใน Zen ได้ เมื่อคุณใช้คีย์ของคุณเอง tokensจะถูกเรียกเก็บเงินโดยตรงจากผู้ให้บริการ ไม่ใช่โดย Zen ตัวอย่างเช่น องค์กรของคุณอาจมีคีย์สำหรับ OpenAI หรือ Anthropic อยู่แล้ว และคุณต้องการใช้สิ่งนั้นแทนอันที่ Zen มอบให้ * * * [เป้าหมาย](https://opencode.ai/docs/th/zen#%E0%B9%80%E0%B8%9B%E0%B9%89%E0%B8%B2%E0%B8%AB%E0%B8%A1%E0%B8%B2%E0%B8%A2) --------------------------------------------------------------------------------------------------------------------- เราสร้าง OpenCode Zen เพื่อ: 1. **เกณฑ์มาตรฐาน** โมเดลที่ดีที่สุด/providers สำหรับตัวแทนการเข้ารหัส 2. เข้าถึงตัวเลือก **คุณภาพMax** และไม่ดาวน์เกรดประสิทธิภาพหรือเปลี่ยนเส้นทางไปยังผู้ให้บริการที่ราคาถูกกว่า 3. ส่งต่อ **ราคาที่ลดลง** โดยการขายในราคาต้นทุน ดังนั้นมาร์กอัปเพียงอย่างเดียวคือครอบคลุมค่าธรรมเนียมการดำเนินการของเรา 4. **ไม่มีการล็อคอิน** โดยอนุญาตให้คุณใช้กับเอเจนต์การเขียนโค้ดอื่นๆ และให้คุณใช้ผู้ให้บริการรายอื่นกับ OpenCode ได้เช่นกัน --- # Zen | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/zen#_top) Zen === Wyselekcjonowana lista modeli dostarczonych przez OpenCode. OpenCode Zen to lista przetestowanych i zweryfikowanych modeli udostępniona przez zespół OpenCode. Zen działa jak każdy inny dostawca w OpenCode. Logujesz się do OpenCode Zen i otrzymujesz swój klucz API. Jest to **całkowicie opcjonalne** i nie musisz tego używać, aby korzystać z OpenCode. * * * [Tło](https://opencode.ai/docs/pl/zen#t%C5%82o) ------------------------------------------------ Istnieje ogromna liczba modeli, ale tylko kilka z nich działa dobrze jako agenci kodujący. Dodatkowo większość dostawców jest skonfigurowana bardzo różnie, więc otrzymujesz bardzo różną wydajność i jakość. Jeśli więc używasz modelu za pośrednictwem czegoś takiego jak OpenRouter, nigdy nie możesz być pewien, czy otrzymujesz najlepszą wersję modelu, jaki chcesz. Aby to naprawić, zrobiliśmy kilka rzeczy: 1. Przetestowaliśmy wybraną grupę modeli i rozmawialiśmy z ich zespołami o tym, jak najlepiej je uruchamiać. 2. Następnie współpracowaliśmy z kilkoma dostawcami, aby upewnić się, że są one obsługiwane poprawnie. 3. Na koniec sprawdziliśmy wydajność kombinacji modelu/dostawcy i stworzyliśmy listę, którą z czystym sumieniem polecamy. OpenCode Zen to brama AI, która zapewnia dostęp do tych modeli. * * * [Jak to działa](https://opencode.ai/docs/pl/zen#jak-to-dzia%C5%82a) -------------------------------------------------------------------- OpenCode Zen działa jak każdy inny dostawca w OpenCode. 1. Logujesz się do **[OpenCode Zen](https://opencode.ai/auth) **, dodajesz dane rozliczeniowe i kopiujesz swój klucz API. 2. Uruchamiasz polecenie `/connect` w TUI, wybierasz OpenCode Zen i wklejasz klucz API. 3. Uruchom `/models` w TUI, aby zobaczyć listę zalecanych przez nas modeli. Opłata jest pobierana za każde żądanie i możesz dodać środki do swojego konta. * * * [Punkty końcowe](https://opencode.ai/docs/pl/zen#punkty-ko%C5%84cowe) ---------------------------------------------------------------------- Dostęp do naszych modeli można również uzyskać za pośrednictwem następujących punktów końcowych API. | Model | Identyfikator modelu | Punkt końcowy | Pakiet SDK AI | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | [Identyfikator modelu](https://opencode.ai/docs/config/#models) w konfiguracji OpenCode używa formatu `opencode/`. Na przykład w przypadku GPT 5.2 Codex użyłbyś `opencode/gpt-5.2-codex` w swojej konfiguracji. * * * ### [Modele](https://opencode.ai/docs/pl/zen#modele) Pełną listę dostępnych modeli i ich metadane możesz pobrać z: https://opencode.ai/zen/v1/models * * * [Cennik](https://opencode.ai/docs/pl/zen#cennik) ------------------------------------------------- Wspieramy model pay-as-you-go. Poniżej znajdują się ceny **za 1M tokenów**. | Model | Wejście | Wyjście | Odczyt w pamięci podręcznej | Zapis w pamięci podręcznej | | --- | --- | --- | --- | --- | | Big Pickle | Free | Free | Free | \- | | MiniMax M2.5 Free | Free | Free | Free | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | $0.375 | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Free | Free | Free | \- | Możesz zauważyć _Claude Haiku 3.5_ w swojej historii użytkowania. Jest to [tani model](https://opencode.ai/docs/config/#models) , który jest używany do generowania tytułów Twoich sesji. Darmowe modele: * MiniMax M2.5 Free jest dostępny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas na zbieranie opinii i ulepszanie modelu. * Big Pickle to ukryty model, który jest bezpłatny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas na zbieranie opinii i ulepszanie modelu. [Skontaktuj się z nami](mailto:contact@anoma.ly) , jeśli masz jakieś pytania. * * * ### [Automatyczne doładowanie](https://opencode.ai/docs/pl/zen#automatyczne-do%C5%82adowanie) Jeśli Twoje saldo spadnie poniżej 5 USD, Zen automatycznie doładuje 20 USD. Możesz zmienić kwotę automatycznego doładowania. Możesz także całkowicie wyłączyć automatyczne doładowanie. * * * ### [Limity miesięczne](https://opencode.ai/docs/pl/zen#limity-miesi%C4%99czne) Możesz także ustawić miesięczny limit użytkowania dla całego obszaru roboczego i dla każdego członka Twojego zespołu. Na przykład, jeśli ustawisz miesięczny limit użytkowania na 20 USD, Zen nie zużyje więcej niż 20 dolarów w miesiącu. Ale jeśli masz włączone automatyczne doładowanie, Zen może obciążyć Cię kwotą wyższą niż 20 USD, jeśli saldo spadnie poniżej 5 USD. * * * ### [Przestarzałe modele](https://opencode.ai/docs/pl/zen#przestarza%C5%82e-modele) | Model | Data wycofania | | --- | --- | | Qwen3 Coder 480B | 6 lutego 2026 | | Kimi K2 Thinking | 6 marca 2026 | | Kimi K2 | 6 marca 2026 | | MiniMax M2.1 | 15 marca 2026 | | GLM 4.7 | 15 marca 2026 | | GLM 4.6 | 15 marca 2026 | * * * [Prywatność](https://opencode.ai/docs/pl/zen#prywatno%C5%9B%C4%87) ------------------------------------------------------------------- Wszystkie nasze modele są hostowane w USA. Nasi dostawcy przestrzegają polityki zerowego przechowywania i nie wykorzystują Twoich danych do szkolenia modeli, z następującymi wyjątkami: * Big Pickle: W okresie bezpłatnym zebrane dane mogą zostać wykorzystane do udoskonalenia modelu. * MiniMax M2.5 Free: W okresie bezpłatnym zebrane dane mogą zostać wykorzystane do udoskonalenia modelu. * API OpenAI: Żądania są przechowywane przez 30 dni zgodnie z [Zasadami dotyczącymi danych OpenAI](https://platform.openai.com/docs/guides/your-data) . * API Anthropic: Żądania są przechowywane przez 30 dni zgodnie z [Zasadami dotyczącymi danych Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [Dla zespołów](https://opencode.ai/docs/pl/zen#dla-zespo%C5%82%C3%B3w) ----------------------------------------------------------------------- Zen działa świetnie także dla zespołów. Możesz zapraszać członków zespołu, przypisywać role, dobierać modele, z których korzysta Twój zespół i nie tylko. Zarządzanie obszarem roboczym jest obecnie bezpłatne dla zespołów w ramach wersji beta. Wkrótce udostępnimy więcej szczegółów na temat cen. * * * ### [Role](https://opencode.ai/docs/pl/zen#role) Możesz zapraszać członków zespołu do swojego obszaru roboczego i przypisywać role: * **Admin**: Zarządzanie modelami, członkami, kluczami API i rozliczeniami * **Członek**: Zarządzanie tylko własnymi kluczami API Administratorzy mogą także ustawić miesięczne limity wydatków dla każdego członka, aby utrzymać koszty pod kontrolą. * * * ### [Dostęp do modelu](https://opencode.ai/docs/pl/zen#dost%C4%99p-do-modelu) Administratorzy mogą włączać i wyłączać określone modele w obszarze roboczym. Żądania skierowane do wyłączonego modelu zwrócą błąd. Jest to przydatne w przypadkach, gdy chcesz wyłączyć korzystanie z modelu, który zbiera dane. * * * ### [Przynieś swój własny klucz](https://opencode.ai/docs/pl/zen#przynie%C5%9B-sw%C3%B3j-w%C5%82asny-klucz) Możesz używać własnych kluczy OpenAI lub Anthropic API, jednocześnie uzyskując dostęp do innych modeli w Zen. Kiedy używasz własnych kluczy, tokeny są rozliczane bezpośrednio przez dostawcę, a nie przez Zen. Na przykład Twoja organizacja może już mieć klucz do OpenAI lub Anthropic i chcesz go używać zamiast tego, który zapewnia Zen. * * * [Cele](https://opencode.ai/docs/pl/zen#cele) --------------------------------------------- Stworzyliśmy OpenCode Zen, aby: 1. **Testować** (Benchmark) najlepsze modele/dostawców dla agentów kodujących. 2. Mieć dostęp do opcji **najwyższej jakości**, a nie obniżać wydajności ani nie kierować do tańszych dostawców. 3. Przekazywać wszelkie **obniżki cen**, sprzedając po kosztach; więc jedyną marżą jest pokrycie naszych opłat manipulacyjnych. 4. Nie **mieć blokady** (no lock-in), umożliwiając używanie go z dowolnym innym agentem kodującym. I zawsze pozwalać na korzystanie z dowolnego innego dostawcy w OpenCode. --- # Go | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/go#_top) Go == Lavkostnadsabonnement for åpne kodemodeller. OpenCode Go er et lavkostnadsabonnement til **$10/måned** som gir deg pålitelig tilgang til populære åpne kodemodeller. Go fungerer som enhver annen leverandør i OpenCode. Du abonnerer på OpenCode Go og får din API-nøkkel. Det er **helt valgfritt** og du trenger ikke bruke det for å bruke OpenCode. Det er designet primært for internasjonale brukere, med modeller driftet i USA, EU og Singapore for stabil global tilgang. * * * [Bakgrunn](https://opencode.ai/docs/nb/go#bakgrunn) ---------------------------------------------------- Åpne modeller har blitt veldig bra. De når nå ytelse nær proprietære modeller for kodeoppgaver. Og fordi mange leverandører kan servere dem konkurransedyktig, er de vanligvis mye billigere. Imidlertid kan det være vanskelig å få pålitelig tilgang med lav ventetid. Leverandører varierer i kvalitet og tilgjengelighet. For å fikse dette gjorde vi et par ting: 1. Vi testet en utvalgt gruppe åpne modeller og snakket med teamene deres om hvordan man best kjører dem. 2. Vi jobbet deretter med noen få leverandører for å sikre at disse ble servert riktig. 3. Til slutt ytelsestestet vi kombinasjonen av modell/leverandør og kom opp med en liste som vi føler oss trygge på å anbefale. OpenCode Go gir deg tilgang til disse modellene for **$10/måned**. * * * [Hvordan det fungerer](https://opencode.ai/docs/nb/go#hvordan-det-fungerer) ---------------------------------------------------------------------------- OpenCode Go fungerer som enhver annen leverandør i OpenCode. 1. Du logger deg inn på **[OpenCode Zen](https://opencode.ai/auth) **, abonnerer på Go, og kopierer API-nøkkelen din. 2. Du kjører kommandoen `/connect` i TUI-en, velger `OpenCode Go`, og limer inn API-nøkkelen din. 3. Kjør `/models` i TUI-en for å se listen over modeller tilgjengelig gjennom Go. Den nåværende listen over modeller inkluderer: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** Listen over modeller kan endres etter hvert som vi tester og legger til nye. * * * [Bruksgrenser](https://opencode.ai/docs/nb/go#bruksgrenser) ------------------------------------------------------------ OpenCode Go inkluderer følgende grenser: * **5 timers grense** — $12 i bruk * **Ukentlig grense** — $30 i bruk * **Månedlig grense** — $60 i bruk Grensene er definert i dollarverdi. Dette betyr at ditt faktiske antall forespørsler avhenger av modellen du bruker. Billigere modeller som MiniMax M2.5 tillater flere forespørsler, mens dyrere modeller som GLM-5 tillater færre. Tabellen nedenfor gir et estimert antall forespørsler basert på typiske Go-bruksmønstre: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | forespørsler per 5 timer | 1,150 | 1,850 | 30,000 | | forespørsler per uke | 2,880 | 4,630 | 75,000 | | forespørsler per måned | 5,750 | 9,250 | 150,000 | Estimater er basert på observerte gjennomsnittlige forespørselsmønstre: * GLM-5 — 700 input, 52,000 cached, 150 output tokens per forespørsel * Kimi K2.5 — 870 input, 55,000 cached, 200 output tokens per forespørsel * MiniMax M2.5 — 300 input, 55,000 cached, 125 output tokens per forespørsel Du kan spore din nåværende bruk i **[konsollen](https://opencode.ai/auth) **. Bruksgrenser kan endres etter hvert som vi lærer fra tidlig bruk og tilbakemeldinger. * * * ### [Priser](https://opencode.ai/docs/nb/go#priser) OpenCode Go er et **$10/måned** abonnementsplan. Nedenfor er prisene **per 1M tokens**. | Modell | Input | Output | Bufret lesing | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [Bruk utover grensene](https://opencode.ai/docs/nb/go#bruk-utover-grensene) Hvis du også har kreditter på din Zen-saldo, kan du aktivere alternativet **Bruk saldo** i konsollen. Når aktivert, vil Go falle tilbake til Zen-saldoen din etter at du har nådd bruksgrensene dine i stedet for å blokkere forespørsler. * * * [Endepunkter](https://opencode.ai/docs/nb/go#endepunkter) ---------------------------------------------------------- Du kan også få tilgang til Go-modeller gjennom følgende API-endepunkter. | Modell | Modell-ID | Endepunkt | AI SDK Pakke | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | [Modell-ID-en](https://opencode.ai/docs/config/#models) i din OpenCode-konfigurasjon bruker formatet `opencode-go/`. For eksempel, for Kimi K2.5, ville du bruke `opencode-go/kimi-k2.5` i konfigurasjonen din. * * * [Personvern](https://opencode.ai/docs/nb/go#personvern) -------------------------------------------------------- Planen er designet primært for internasjonale brukere, med modeller driftet i USA, EU og Singapore for stabil global tilgang. [Kontakt oss](mailto:contact@anoma.ly) hvis du har noen spørsmål. * * * [Mål](https://opencode.ai/docs/nb/go#m%C3%A5l) ----------------------------------------------- Vi opprettet OpenCode Go for å: 1. Gjøre AI-koding **tilgjengelig** for flere mennesker med et lavkostnadsabonnement. 2. Gi **pålitelig** tilgang til de beste åpne kodemodellene. 3. Kurere modeller som er **testet og ytelsestestet** for bruk av kodeagenter. 4. Ha **ingen innlåsing** ved å tillate deg å bruke hvilken som helst annen leverandør med OpenCode også. --- # Zen | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/zen#_top) Zen === قائمة منتقاة من النماذج يوفّرها OpenCode. OpenCode Zen هي قائمة بالنماذج التي اختبرها فريق OpenCode وتحقّق منها. يعمل Zen مثل أي مزوّد آخر في OpenCode. تسجّل الدخول إلى OpenCode Zen وتحصل على مفتاح API. استخدامه **اختياري بالكامل** ولا تحتاج إليه لاستخدام OpenCode. * * * [الخلفية](https://opencode.ai/docs/ar/zen#%D8%A7%D9%84%D8%AE%D9%84%D9%81%D9%8A%D8%A9) -------------------------------------------------------------------------------------- توجد نماذج كثيرة جدا، لكن عددا قليلا فقط منها يعمل بشكل جيد كعوامل للبرمجة. بالإضافة إلى ذلك، فإن معظم المزوّدين يختلفون كثيرا في طريقة الإعداد؛ لذلك قد تحصل على أداء وجودة مختلفين بشكل كبير. لذلك إذا كنت تستخدم نموذجا عبر خدمة مثل OpenRouter، فلن تكون واثقا أبدا من أنك تحصل على أفضل نسخة من النموذج الذي تريده. لمعالجة ذلك، قمنا بعدة أمور: 1. اختبرنا مجموعة منتقاة من النماذج وتحدثنا مع فرقها حول افضل طريقة لتشغيلها. 2. ثم عملنا مع عدد من المزوّدين للتأكد من تقديمها بشكل صحيح. 3. أخيرا، قمنا بقياس أداء توليفة النموذج/المزوّد وخرجنا بقائمة نوصي بها بثقة. OpenCode Zen هو بوابة للذكاء الاصطناعي تتيح لك الوصول إلى هذه النماذج. * * * [كيف يعمل](https://opencode.ai/docs/ar/zen#%D9%83%D9%8A%D9%81-%D9%8A%D8%B9%D9%85%D9%84) ---------------------------------------------------------------------------------------- يعمل OpenCode Zen مثل أي مزوّد آخر في OpenCode. 1. تسجّل الدخول إلى **[OpenCode Zen](https://opencode.ai/auth) **، وتضيف تفاصيل الفوترة، ثم تنسخ مفتاح API. 2. تشغّل الأمر `/connect` في واجهة TUI، وتختار OpenCode Zen، ثم تلصق مفتاح API. 3. شغّل `/models` في واجهة TUI لعرض قائمة النماذج التي نوصي بها. يتم احتساب الرسوم لكل طلب، ويمكنك إضافة رصيد إلى حسابك. * * * [نقاط النهاية](https://opencode.ai/docs/ar/zen#%D9%86%D9%82%D8%A7%D8%B7-%D8%A7%D9%84%D9%86%D9%87%D8%A7%D9%8A%D8%A9) -------------------------------------------------------------------------------------------------------------------- يمكنك أيضا الوصول إلى نماذجنا عبر نقاط نهاية API التالية. | النموذج | معرّف النموذج | نقطة النهاية | حزمة AI SDK | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | يستخدم [معرّف النموذج](https://opencode.ai/docs/config/#models) في إعدادات OpenCode الصيغة `opencode/`. على سبيل المثال، بالنسبة إلى GPT 5.2 Codex ستستخدم `opencode/gpt-5.2-codex` في إعداداتك. * * * ### [النماذج](https://opencode.ai/docs/ar/zen#%D8%A7%D9%84%D9%86%D9%85%D8%A7%D8%B0%D8%AC) يمكنك جلب القائمة الكاملة بالنماذج المتاحة وبياناتها الوصفية من: https://opencode.ai/zen/v1/models * * * [التسعير](https://opencode.ai/docs/ar/zen#%D8%A7%D9%84%D8%AA%D8%B3%D8%B9%D9%8A%D8%B1) -------------------------------------------------------------------------------------- ندعم نموذج الدفع حسب الاستخدام. فيما يلي الأسعار **لكل 1M tokens**. | النموذج | الإدخال | الإخراج | قراءة مخزنة | كتابة مخزنة | | --- | --- | --- | --- | --- | | Big Pickle | Free | Free | Free | \- | | MiniMax M2.5 Free | Free | Free | Free | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200K tokens) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200K tokens) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200K tokens) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200K tokens) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200K tokens) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200K tokens) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Free | Free | Free | \- | قد تلاحظ _Claude Haiku 3.5_ في سجل الاستخدام. هذا [نموذج منخفض التكلفة](https://opencode.ai/docs/config/#models) يُستخدم لتوليد عناوين جلساتك. النماذج المجانية: * MiniMax M2.5 Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج. * Big Pickle نموذج خفي ومتاح مجانا على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج. [تواصل معنا](mailto:contact@anoma.ly) إذا كانت لديك أي أسئلة. * * * ### [إعادة الشحن التلقائي](https://opencode.ai/docs/ar/zen#%D8%A5%D8%B9%D8%A7%D8%AF%D8%A9-%D8%A7%D9%84%D8%B4%D8%AD%D9%86-%D8%A7%D9%84%D8%AA%D9%84%D9%82%D8%A7%D8%A6%D9%8A) إذا انخفض رصيدك عن $5، فسيقوم Zen تلقائيا بإعادة شحن $20. يمكنك تغيير مبلغ إعادة الشحن التلقائي. ويمكنك أيضا تعطيل إعادة الشحن التلقائي بالكامل. * * * ### [الحدود الشهرية](https://opencode.ai/docs/ar/zen#%D8%A7%D9%84%D8%AD%D8%AF%D9%88%D8%AF-%D8%A7%D9%84%D8%B4%D9%87%D8%B1%D9%8A%D8%A9) يمكنك أيضا تعيين حد شهري للاستخدام لمساحة العمل بالكامل ولكل عضو في فريقك. على سبيل المثال، لنفترض أنك ضبطت حد الاستخدام الشهري على $20، فلن يتجاوز Zen مبلغ $20 خلال شهر. لكن إذا كانت إعادة الشحن التلقائي مفعّلة، فقد ينتهي الأمر بخصم أكثر من $20 إذا انخفض رصيدك عن $5. * * * ### [نماذج مهملة](https://opencode.ai/docs/ar/zen#%D9%86%D9%85%D8%A7%D8%B0%D8%AC-%D9%85%D9%87%D9%85%D9%84%D8%A9) | النموذج | تاريخ الإيقاف | | --- | --- | | Qwen3 Coder 480B | 6 فبراير 2026 | | Kimi K2 Thinking | 6 مارس 2026 | | Kimi K2 | 6 مارس 2026 | | MiniMax M2.1 | 15 مارس 2026 | | GLM 4.7 | 15 مارس 2026 | | GLM 4.6 | 15 مارس 2026 | * * * [الخصوصية](https://opencode.ai/docs/ar/zen#%D8%A7%D9%84%D8%AE%D8%B5%D9%88%D8%B5%D9%8A%D8%A9) --------------------------------------------------------------------------------------------- تتم استضافة جميع نماذجنا في الولايات المتحدة. يلتزم مزوّدونا بسياسة عدم الاحتفاظ بالبيانات (zero-retention) ولا يستخدمون بياناتك لتدريب النماذج، مع الاستثناءات التالية: * Big Pickle: خلال فترة إتاحته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج. * MiniMax M2.5 Free: خلال فترة إتاحته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج. * OpenAI APIs: يتم الاحتفاظ بالطلبات لمدة 30 يوما وفقا لـ [سياسات بيانات OpenAI](https://platform.openai.com/docs/guides/your-data) . * Anthropic APIs: يتم الاحتفاظ بالطلبات لمدة 30 يوما وفقا لـ [سياسات بيانات Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [للفرق](https://opencode.ai/docs/ar/zen#%D9%84%D9%84%D9%81%D8%B1%D9%82) ------------------------------------------------------------------------ يعمل Zen بشكل ممتاز للفرق أيضا. يمكنك دعوة زملاء الفريق، وتعيين الأدوار، وتنظيم النماذج التي يستخدمها فريقك، والمزيد. إدارة مساحة العمل مجانية حاليا للفرق كجزء من النسخة التجريبية. سنشارك المزيد من التفاصيل حول التسعير قريبا. * * * ### [الأدوار](https://opencode.ai/docs/ar/zen#%D8%A7%D9%84%D8%A3%D8%AF%D9%88%D8%A7%D8%B1) يمكنك دعوة زملاء الفريق إلى مساحة عملك وتعيين الأدوار: * **Admin**: إدارة النماذج والأعضاء ومفاتيح API والفوترة * **Member**: إدارة مفاتيح API الخاصة به فقط يمكن للمسؤولين أيضا تعيين حدود إنفاق شهرية لكل عضو للسيطرة على التكاليف. * * * ### [صلاحيات الوصول للنماذج](https://opencode.ai/docs/ar/zen#%D8%B5%D9%84%D8%A7%D8%AD%D9%8A%D8%A7%D8%AA-%D8%A7%D9%84%D9%88%D8%B5%D9%88%D9%84-%D9%84%D9%84%D9%86%D9%85%D8%A7%D8%B0%D8%AC) يمكن للمسؤولين تفعيل نماذج محددة لمساحة العمل أو تعطيلها. ستعيد الطلبات المرسلة إلى نموذج معطّل خطأ. يفيد ذلك في الحالات التي تريد فيها تعطيل استخدام نموذج يقوم بجمع البيانات. * * * ### [استخدم مفتاحك الخاص](https://opencode.ai/docs/ar/zen#%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D9%85-%D9%85%D9%81%D8%AA%D8%A7%D8%AD%D9%83-%D8%A7%D9%84%D8%AE%D8%A7%D8%B5) يمكنك استخدام مفاتيح API الخاصة بك لدى OpenAI أو Anthropic مع الاستمرار في الوصول إلى نماذج أخرى ضمن Zen. عند استخدام مفاتيحك الخاصة، تتم فوترة tokens مباشرة من المزوّد وليس من Zen. على سبيل المثال، قد تكون لدى مؤسستك بالفعل مفاتيح لـ OpenAI أو Anthropic وتريد استخدامها بدلا من المفتاح الذي يوفّره Zen. * * * [الأهداف](https://opencode.ai/docs/ar/zen#%D8%A7%D9%84%D8%A3%D9%87%D8%AF%D8%A7%D9%81) -------------------------------------------------------------------------------------- أنشأنا OpenCode Zen من أجل: 1. **قياس الأداء** لأفضل النماذج/المزوّدين لعوامل البرمجة. 2. إتاحة خيارات **عالية الجودة** دون خفض الأداء أو توجيه الطلبات إلى مزوّدين أرخص. 3. تمرير أي **انخفاض في الأسعار** عبر البيع بالتكلفة؛ بحيث تكون الزيادة الوحيدة لتغطية رسوم المعالجة. 4. عدم فرض **أي ارتباط حصري (lock-in)** عبر تمكينك من استخدامه مع أي عامل برمجة آخر، مع إتاحة استخدام أي مزوّد آخر مع OpenCode أيضا. --- # IDE | OpenCode [Skip to content](https://opencode.ai/docs/th/ide#_top) IDE === ส่วนขยาย OpenCode สำหรับ VS Code, Cursor และ IDE อื่นๆ OpenCode ทำงานร่วมกับ VS Code, Cursor หรือ IDE ใดๆ ที่รองรับ terminal เพียงเรียกใช้ `opencode` ใน terminal เพื่อเริ่มต้น * * * [การใช้งาน](https://opencode.ai/docs/th/ide#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99) ------------------------------------------------------------------------------------------------------------------------------- * **เปิดใช้ด่วน**: ใช้ `Cmd+Esc` (Mac) หรือ `Ctrl+Esc` (Windows/Linux) เพื่อเปิด OpenCode ในมุมมอง terminal แบบแยก หรือเน้นเซสชัน terminal ที่มีอยู่หากมีการทำงานอยู่แล้ว * **เซสชันใหม่**: ใช้ `Cmd+Shift+Esc` (Mac) หรือ `Ctrl+Shift+Esc` (Windows/Linux) เพื่อเริ่มเซสชัน terminal OpenCode ใหม่ แม้ว่าเซสชันหนึ่งจะเปิดอยู่แล้วก็ตาม คุณยังสามารถคลิกปุ่ม OpenCode ใน UI ได้ด้วย * **การรับรู้บริบท**: แชร์การเลือกหรือแท็บปัจจุบันของคุณโดยอัตโนมัติด้วย OpenCode * **ทางลัดการอ้างอิงไฟล์**: ใช้ `Cmd+Option+K` (Mac) หรือ `Alt+Ctrl+K` (Linux/Windows) เพื่อแทรกการอ้างอิงไฟล์ ตัวอย่างเช่น `@File#L37-42` * * * [การติดตั้ง](https://opencode.ai/docs/th/ide#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%95%E0%B8%B4%E0%B8%94%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87) ----------------------------------------------------------------------------------------------------------------------------------------- วิธีติดตั้ง OpenCode บน VS Code และทางแยกยอดนิยม เช่น Cursor, Windsurf, VSCodium: 1. เปิด VS Code 2. เปิด terminal รวม 3. เรียกใช้ `opencode` - ​​ส่วนขยายจะติดตั้งโดยอัตโนมัติ ในทางกลับกัน หากคุณต้องการใช้ IDE ของคุณเองเมื่อคุณเรียกใช้ `/editor` หรือ `/export` จาก TUI คุณจะต้องตั้งค่า `export EDITOR="code --wait"` [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/tui/#editor-setup) * * * ### [ติดตั้งด้วยตนเอง](https://opencode.ai/docs/th/ide#%E0%B8%95%E0%B8%B4%E0%B8%94%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2%E0%B8%95%E0%B8%99%E0%B9%80%E0%B8%AD%E0%B8%87) ค้นหา **OpenCode** ใน Extension Marketplace แล้วคลิก **ติดตั้ง** * * * ### [การแก้ไขปัญหา](https://opencode.ai/docs/th/ide#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%81%E0%B8%81%E0%B9%89%E0%B9%84%E0%B8%82%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2) หากส่วนขยายไม่สามารถติดตั้งได้โดยอัตโนมัติ: * ตรวจสอบให้แน่ใจว่าคุณใช้งาน `opencode` ใน terminal รวม * ยืนยันว่า CLI สำหรับ IDE ของคุณได้รับการติดตั้งแล้ว: * สำหรับ VS Code: `code` คำสั่ง * สำหรับ Cursor: `cursor` คำสั่ง * สำหรับ Windsurf: `windsurf` คำสั่ง * สำหรับ VSCodium: `codium` คำสั่ง * ถ้าไม่เช่นนั้น ให้รัน `Cmd+Shift+P` (Mac) หรือ `Ctrl+Shift+P` (Windows/Linux) และค้นหา “Shell Command: Install ‘code’ command in PATH” (หรือเทียบเท่ากับ IDE ของคุณ) * ตรวจสอบให้แน่ใจว่ารหัส VS มีสิทธิ์ในการติดตั้งส่วนขยาย --- # Go | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/go#_top) Go == اشتراك منخفض التكلفة لنماذج البرمجة المفتوحة. OpenCode Go هو اشتراك منخفض التكلفة بقيمة **10 دولارات شهرياً** يمنحك وصولاً موثوقاً إلى نماذج البرمجة المفتوحة الشائعة. يعمل Go مثل أي مزود آخر في OpenCode. تشترك في OpenCode Go وتحصل على مفتاح API الخاص بك. إنه **اختياري تماماً** ولا تحتاج إلى استخدامه لاستخدام OpenCode. صُمم بشكل أساسي للمستخدمين الدوليين، مع استضافة النماذج في الولايات المتحدة والاتحاد الأوروبي وسنغافورة لضمان وصول عالمي مستقر. * * * [الخلفية (Background)](https://opencode.ai/docs/ar/go#%D8%A7%D9%84%D8%AE%D9%84%D9%81%D9%8A%D8%A9-background) ------------------------------------------------------------------------------------------------------------- أصبحت النماذج المفتوحة جيدة حقاً. فهي تصل الآن إلى أداء قريب من النماذج المملوكة لمهام البرمجة. ولأن العديد من المزودين يمكنهم تقديمها بشكل تنافسي، فهي عادة ما تكون أرخص بكثير. ومع ذلك، فإن الحصول على وصول موثوق ومنخفض الكمون (low latency) إليها قد يكون صعباً. يختلف المزودون في الجودة والتوافر. لإصلاح ذلك، قمنا ببعض الأشياء: 1. اختبرنا مجموعة مختارة من النماذج المفتوحة وتحدثنا مع فرقهم حول أفضل طريقة لتشغيلها. 2. عملنا بعد ذلك مع عدد قليل من المزودين للتأكد من تقديمها بشكل صحيح. 3. أخيراً، قمنا بقياس أداء (benchmark) مزيج النموذج/المزود وتوصلنا إلى قائمة نشعر بالراحة في التوصية بها. يمنحك OpenCode Go الوصول إلى هذه النماذج مقابل **10 دولارات شهرياً**. * * * [كيف يعمل (How it works)](https://opencode.ai/docs/ar/go#%D9%83%D9%8A%D9%81-%D9%8A%D8%B9%D9%85%D9%84-how-it-works) ------------------------------------------------------------------------------------------------------------------- يعمل OpenCode Go مثل أي مزود آخر في OpenCode. 1. قم بتسجيل الدخول إلى **[OpenCode Zen](https://opencode.ai/auth) **، واشترك في Go، وانسخ مفتاح API الخاص بك. 2. قم بتشغيل الأمر `/connect` في واجهة TUI، وحدد `OpenCode Go`، والصق مفتاح API الخاص بك. 3. قم بتشغيل `/models` في واجهة TUI لرؤية قائمة النماذج المتاحة من خلال Go. تتضمن القائمة الحالية للنماذج: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** قد تتغير قائمة النماذج ونحن نختبر ونضيف نماذج جديدة. * * * [حدود الاستخدام (Usage limits)](https://opencode.ai/docs/ar/go#%D8%AD%D8%AF%D9%88%D8%AF-%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85-usage-limits) ------------------------------------------------------------------------------------------------------------------------------------------------------------- يتضمن OpenCode Go الحدود التالية: * **حد 5 ساعات** — 12 دولاراً من الاستخدام * **حد أسبوعي** — 30 دولاراً من الاستخدام * **حد شهري** — 60 دولاراً من الاستخدام يتم تعريف الحدود بقيمة الدولار. هذا يعني أن عدد طلباتك الفعلي يعتمد على النموذج الذي تستخدمه. تسمح النماذج الأرخص مثل MiniMax M2.5 بمزيد من الطلبات، بينما تسمح النماذج الأعلى تكلفة مثل GLM-5 بعدد أقل. يوفر الجدول أدناه عدداً تقديرياً للطلبات بناءً على أنماط استخدام Go النموذجية: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | طلبات كل 5 ساعات | 1,150 | 1,850 | 30,000 | | طلبات أسبوعياً | 2,880 | 4,630 | 75,000 | | طلبات شهرياً | 5,750 | 9,250 | 150,000 | تعتمد التقديرات على أنماط الطلبات المتوسطة الملحوظة: * GLM-5 — 700 input, 52,000 cached, 150 output tokens per request * Kimi K2.5 — 870 input, 55,000 cached, 200 output tokens per request * MiniMax M2.5 — 300 input, 55,000 cached, 125 output tokens per request يمكنك تتبع استخدامك الحالي في **[console](https://opencode.ai/auth) **. قد تتغير حدود الاستخدام ونحن نتعلم من الاستخدام المبكر والملاحظات. * * * ### [التسعير (Pricing)](https://opencode.ai/docs/ar/go#%D8%A7%D9%84%D8%AA%D8%B3%D8%B9%D9%8A%D8%B1-pricing) OpenCode Go هي خطة اشتراك بقيمة **10 دولارات شهرياً**. أدناه الأسعار **لكل 1 مليون رمز (token)**. | Model | Input | Output | Cached Read | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [الاستخدام خارج الحدود (Usage beyond limits)](https://opencode.ai/docs/ar/go#%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85-%D8%AE%D8%A7%D8%B1%D8%AC-%D8%A7%D9%84%D8%AD%D8%AF%D9%88%D8%AF-usage-beyond-limits) إذا كان لديك أيضاً أرصدة في رصيد Zen الخاص بك، يمكنك تمكين خيار **Use balance** في الـ console. عند التمكين، سيعود Go لاستخدام رصيد Zen الخاص بك بعد وصولك إلى حدود الاستخدام بدلاً من حظر الطلبات. * * * [نقاط النهاية (Endpoints)](https://opencode.ai/docs/ar/go#%D9%86%D9%82%D8%A7%D8%B7-%D8%A7%D9%84%D9%86%D9%87%D8%A7%D9%8A%D8%A9-endpoints) ----------------------------------------------------------------------------------------------------------------------------------------- يمكنك أيضاً الوصول إلى نماذج Go من خلال نقاط نهاية API التالية. | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | يستخدم [model id](https://opencode.ai/docs/config/#models) في تكوين OpenCode الخاص بك التنسيق `opencode-go/`. على سبيل المثال، بالنسبة لـ Kimi K2.5، ستستخدم `opencode-go/kimi-k2.5` في التكوين الخاص بك. * * * [الخصوصية (Privacy)](https://opencode.ai/docs/ar/go#%D8%A7%D9%84%D8%AE%D8%B5%D9%88%D8%B5%D9%8A%D8%A9-privacy) -------------------------------------------------------------------------------------------------------------- تم تصميم الخطة بشكل أساسي للمستخدمين الدوليين، مع استضافة النماذج في الولايات المتحدة والاتحاد الأوروبي وسنغافورة لضمان وصول عالمي مستقر. [تواصل معنا](mailto:contact@anoma.ly) إذا كان لديك أي أسئلة. * * * [الأهداف (Goals)](https://opencode.ai/docs/ar/go#%D8%A7%D9%84%D8%A3%D9%87%D8%AF%D8%A7%D9%81-goals) --------------------------------------------------------------------------------------------------- أنشأنا OpenCode Go لـ: 1. جعل برمجة الذكاء الاصطناعي **في المتناول** لمزيد من الناس باشتراك منخفض التكلفة. 2. توفير وصول **موثوق** لأفضل نماذج البرمجة المفتوحة. 3. انتقاء نماذج **مختبرة وتم قياس أدائها** لاستخدام وكيل البرمجة. 4. عدم وجود **قيود (lock-in)** من خلال السماح لك باستخدام أي مزود آخر مع OpenCode أيضاً. --- # Go | OpenCode [Skip to content](https://opencode.ai/docs/th/go#_top) Go == การสมัครสมาชิกราคาประหยัดสำหรับโมเดลการเขียนโค้ดแบบเปิด OpenCode Go คือการสมัครสมาชิกราคาประหยัดเพียง **$10/เดือน** ที่ให้คุณเข้าถึงโมเดลการเขียนโค้ดแบบเปิดยอดนิยมได้อย่างน่าเชื่อถือ Go ทำงานเหมือนกับผู้ให้บริการรายอื่นใน OpenCode คุณสมัครสมาชิก OpenCode Go และรับคีย์ API ของคุณ มันเป็น**ตัวเลือกเสริมทั้งหมด** และคุณไม่จำเป็นต้องใช้มันเพื่อใช้งาน OpenCode มันถูกออกแบบมาสำหรับผู้ใช้งานระดับนานาชาติเป็นหลัก โดยมีโมเดลโฮสต์อยู่ในสหรัฐอเมริกา สหภาพยุโรป และสิงคโปร์ เพื่อการเข้าถึงที่เสถียรทั่วโลก * * * [ความเป็นมา](https://opencode.ai/docs/th/go#%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B9%80%E0%B8%9B%E0%B9%87%E0%B8%99%E0%B8%A1%E0%B8%B2) ---------------------------------------------------------------------------------------------------------------------------------------- โมเดลแบบเปิดมีคุณภาพดีขึ้นมาก ปัจจุบันมีประสิทธิภาพใกล้เคียงกับโมเดลที่เป็นกรรมสิทธิ์สำหรับงานเขียนโค้ด และเนื่องจากผู้ให้บริการหลายรายสามารถให้บริการโมเดลเหล่านี้ได้อย่างแข่งขันกัน จึงมักจะมีราคาถูกกว่ามาก อย่างไรก็ตาม การเข้าถึงโมเดลเหล่านี้อย่างน่าเชื่อถือและมีความหน่วงต่ำอาจเป็นเรื่องยาก ผู้ให้บริการมีคุณภาพและความพร้อมใช้งานที่แตกต่างกัน เพื่อแก้ไขปัญหานี้ เราได้ทำสิ่งต่อไปนี้: 1. เราทดสอบกลุ่มโมเดลแบบเปิดที่เลือกสรรและพูดคุยกับทีมของพวกเขาเกี่ยวกับวิธีการรันโมเดลให้ดีที่สุด 2. จากนั้นเราทำงานร่วมกับผู้ให้บริการบางรายเพื่อให้แน่ใจว่าโมเดลเหล่านี้ได้รับการให้บริการอย่างถูกต้อง 3. สุดท้าย เราทำการทดสอบประสิทธิภาพ (Benchmark) การรวมกันของโมเดล/ผู้ให้บริการ และได้รายชื่อที่เรารู้สึกดีที่จะแนะนำ OpenCode Go ให้คุณเข้าถึงโมเดลเหล่านี้ในราคา **$10/เดือน** * * * [วิธีการทำงาน](https://opencode.ai/docs/th/go#%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99) ------------------------------------------------------------------------------------------------------------------------------------------------------------ OpenCode Go ทำงานเหมือนกับผู้ให้บริการรายอื่นใน OpenCode 1. ลงชื่อเข้าใช้ **[OpenCode Zen](https://opencode.ai/auth) ** สมัครสมาชิก Go และคัดลอกคีย์ API ของคุณ 2. รันคำสั่ง `/connect` ใน TUI เลือก `OpenCode Go` และวางคีย์ API ของคุณ 3. รัน `/models` ใน TUI เพื่อดูรายชื่อโมเดลที่สามารถใช้งานได้ผ่าน Go รายชื่อโมเดลปัจจุบันประกอบด้วย: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** รายชื่อโมเดลอาจมีการเปลี่ยนแปลงเมื่อเราทดสอบและเพิ่มโมเดลใหม่ * * * [ขีดจำกัดการใช้งาน](https://opencode.ai/docs/th/go#%E0%B8%82%E0%B8%B5%E0%B8%94%E0%B8%88%E0%B8%B3%E0%B8%81%E0%B8%B1%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode Go มีขีดจำกัดดังต่อไปนี้: * **ขีดจำกัด 5 ชั่วโมง** — การใช้งานมูลค่า $12 * **ขีดจำกัดรายสัปดาห์** — การใช้งานมูลค่า $30 * **ขีดจำกัดรายเดือน** — การใช้งานมูลค่า $60 ขีดจำกัดถูกกำหนดเป็นมูลค่าดอลลาร์ ซึ่งหมายความว่าจำนวนคำขอจริงของคุณจะขึ้นอยู่กับโมเดลที่คุณใช้ โมเดลที่ถูกกว่าเช่น MiniMax M2.5 อนุญาตให้ส่งคำขอได้มากกว่า ในขณะที่โมเดลที่มีราคาสูงกว่าเช่น GLM-5 จะอนุญาตให้ส่งคำขอได้น้อยกว่า ตารางด้านล่างแสดงจำนวนคำขอโดยประมาณตามรูปแบบการใช้งาน Go ทั่วไป: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | คำขอต่อ 5 ชั่วโมง | 1,150 | 1,850 | 30,000 | | คำขอต่อสัปดาห์ | 2,880 | 4,630 | 75,000 | | คำขอต่อเดือน | 5,750 | 9,250 | 150,000 | การประมาณการขึ้นอยู่กับรูปแบบคำขอเฉลี่ยที่สังเกตได้: * GLM-5 — 700 input, 52,000 cached, 150 output tokens ต่อคำขอ * Kimi K2.5 — 870 input, 55,000 cached, 200 output tokens ต่อคำขอ * MiniMax M2.5 — 300 input, 55,000 cached, 125 output tokens ต่อคำขอ คุณสามารถติดตามการใช้งานปัจจุบันของคุณได้ใน **[คอนโซล](https://opencode.ai/auth) ** ขีดจำกัดการใช้งานอาจมีการเปลี่ยนแปลงเมื่อเราเรียนรู้จากการใช้งานและข้อเสนอแนะในช่วงแรก * * * ### [ราคา](https://opencode.ai/docs/th/go#%E0%B8%A3%E0%B8%B2%E0%B8%84%E0%B8%B2) OpenCode Go เป็นแผนการสมัครสมาชิกราคา **$10/เดือน** ด้านล่างคือราคา**ต่อ 1 ล้านโทเค็น** | Model | Input | Output | Cached Read | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [การใช้งานเกินขีดจำกัด](https://opencode.ai/docs/th/go#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B9%80%E0%B8%81%E0%B8%B4%E0%B8%99%E0%B8%82%E0%B8%B5%E0%B8%94%E0%B8%88%E0%B8%B3%E0%B8%81%E0%B8%B1%E0%B8%94) หากคุณมีเครดิตในยอดคงเหลือ Zen ของคุณ คุณสามารถเปิดใช้งานตัวเลือก **Use balance** ในคอนโซล เมื่อเปิดใช้งาน Go จะเปลี่ยนไปใช้ยอดคงเหลือ Zen ของคุณหลังจากที่คุณใช้งานถึงขีดจำกัดแล้ว แทนที่จะบล็อกคำขอ * * * [Endpoints](https://opencode.ai/docs/th/go#endpoints) ------------------------------------------------------ คุณยังสามารถเข้าถึงโมเดล Go ผ่าน API endpoints ต่อไปนี้ | Model | Model ID | Endpoint | AI SDK Package | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | [รหัสโมเดล](https://opencode.ai/docs/config/#models) ในการกำหนดค่า OpenCode ของคุณใช้รูปแบบ `opencode-go/` ตัวอย่างเช่น สำหรับ Kimi K2.5 คุณจะใช้ `opencode-go/kimi-k2.5` ในการกำหนดค่าของคุณ * * * [ความเป็นส่วนตัว](https://opencode.ai/docs/th/go#%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B9%80%E0%B8%9B%E0%B9%87%E0%B8%99%E0%B8%AA%E0%B9%88%E0%B8%A7%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ แผนนี้ออกแบบมาสำหรับผู้ใช้ระดับนานาชาติเป็นหลัก โดยมีโมเดลโฮสต์อยู่ในสหรัฐอเมริกา สหภาพยุโรป และสิงคโปร์ เพื่อการเข้าถึงที่เสถียรทั่วโลก [ติดต่อเรา](mailto:contact@anoma.ly) หากคุณมีข้อสงสัยใดๆ * * * [เป้าหมาย](https://opencode.ai/docs/th/go#%E0%B9%80%E0%B8%9B%E0%B9%89%E0%B8%B2%E0%B8%AB%E0%B8%A1%E0%B8%B2%E0%B8%A2) -------------------------------------------------------------------------------------------------------------------- เราสร้าง OpenCode Go เพื่อ: 1. ทำให้การเขียนโค้ดด้วย AI **เข้าถึงได้** สำหรับผู้คนมากขึ้นด้วยการสมัครสมาชิกราคาประหยัด 2. ให้การเข้าถึงโมเดลการเขียนโค้ดแบบเปิดที่ดีที่สุดอย่าง **น่าเชื่อถือ** 3. คัดสรรโมเดลที่ผ่านการ **ทดสอบและวัดประสิทธิภาพ** สำหรับการใช้งานตัวแทน (Agent) เขียนโค้ด 4. **ไม่มีการผูกมัด** โดยอนุญาตให้คุณใช้ผู้ให้บริการรายอื่นกับ OpenCode ได้เช่นกัน --- # Go | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/go#_top) Go == Assinatura de baixo custo para modelos de codificação abertos. O OpenCode Go é uma assinatura de baixo custo de **$10/mês** que oferece acesso confiável a modelos de codificação abertos populares. O Go funciona como qualquer outro provedor no OpenCode. Você assina o OpenCode Go e obtém sua chave de API. É **totalmente opcional** e você não precisa usá-lo para usar o OpenCode. Ele é projetado principalmente para usuários internacionais, com modelos hospedados nos EUA, UE e Singapura para acesso global estável. * * * [Contexto](https://opencode.ai/docs/pt-br/go#contexto) ------------------------------------------------------- Modelos abertos ficaram realmente bons. Eles agora alcançam desempenho próximo aos modelos proprietários para tarefas de codificação. E como muitos provedores podem servi-los competitivamente, eles geralmente são muito mais baratos. No entanto, obter acesso confiável e de baixa latência a eles pode ser difícil. Os provedores variam em qualidade e disponibilidade. Para corrigir isso, fizemos algumas coisas: 1. Testamos um grupo selecionado de modelos abertos e conversamos com suas equipes sobre a melhor forma de executá-los. 2. Trabalhamos com alguns provedores para garantir que eles estivessem sendo servidos corretamente. 3. Finalmente, fizemos benchmarks da combinação modelo/provedor e chegamos a uma lista que nos sentimos bem em recomendar. O OpenCode Go oferece acesso a esses modelos por **$10/mês**. * * * [Como funciona](https://opencode.ai/docs/pt-br/go#como-funciona) ----------------------------------------------------------------- O OpenCode Go funciona como qualquer outro provedor no OpenCode. 1. Você faz login no **[OpenCode Zen](https://opencode.ai/auth) **, assina o Go e copia sua chave de API. 2. Você executa o comando `/connect` na TUI, seleciona `OpenCode Go` e cola sua chave de API. 3. Execute `/models` na TUI para ver a lista de modelos disponíveis através do Go. A lista atual de modelos inclui: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** A lista de modelos pode mudar conforme testamos e adicionamos novos. * * * [Limites de uso](https://opencode.ai/docs/pt-br/go#limites-de-uso) ------------------------------------------------------------------- O OpenCode Go inclui os seguintes limites: * **Limite de 5 horas** — $12 de uso * **Limite semanal** — $30 de uso * **Limite mensal** — $60 de uso Os limites são definidos em valor monetário. Isso significa que sua contagem real de requisições depende do modelo que você usa. Modelos mais baratos como o MiniMax M2.5 permitem mais requisições, enquanto modelos de custo mais alto como o GLM-5 permitem menos. A tabela abaixo fornece uma estimativa de contagem de requisições baseada em padrões típicos de uso do Go: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | requisições por 5 horas | 1.150 | 1.850 | 30.000 | | requisições por semana | 2.880 | 4.630 | 75.000 | | requisições por mês | 5.750 | 9.250 | 150.000 | As estimativas são baseadas em padrões médios de requisição observados: * GLM-5 — 700 tokens de entrada, 52.000 em cache, 150 tokens de saída por requisição * Kimi K2.5 — 870 tokens de entrada, 55.000 em cache, 200 tokens de saída por requisição * MiniMax M2.5 — 300 tokens de entrada, 55.000 em cache, 125 tokens de saída por requisição Você pode acompanhar seu uso atual no **[console](https://opencode.ai/auth) **. Os limites de uso podem mudar conforme aprendemos com o uso inicial e feedback. * * * ### [Preços](https://opencode.ai/docs/pt-br/go#pre%C3%A7os) O OpenCode Go é um plano de assinatura de **$10/mês**. Abaixo estão os preços **por 1M de tokens**. | Modelo | Entrada | Saída | Leitura em Cache | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [Uso além dos limites](https://opencode.ai/docs/pt-br/go#uso-al%C3%A9m-dos-limites) Se você também tiver créditos em seu saldo Zen, pode ativar a opção **Use balance** (Usar saldo) no console. Quando ativada, o Go recorrerá ao seu saldo Zen depois que você atingir seus limites de uso, em vez de bloquear as requisições. * * * [Endpoints](https://opencode.ai/docs/pt-br/go#endpoints) --------------------------------------------------------- Você também pode acessar os modelos Go através dos seguintes endpoints de API. | Modelo | ID do Modelo | Endpoint | Pacote AI SDK | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | O [model id](https://opencode.ai/docs/config/#models) (ID do modelo) na sua configuração do OpenCode usa o formato `opencode-go/`. Por exemplo, para o Kimi K2.5, você usaria `opencode-go/kimi-k2.5` na sua configuração. * * * [Privacidade](https://opencode.ai/docs/pt-br/go#privacidade) ------------------------------------------------------------- O plano é projetado principalmente para usuários internacionais, com modelos hospedados nos EUA, UE e Singapura para acesso global estável. [Entre em contato conosco](mailto:contact@anoma.ly) se tiver alguma dúvida. * * * [Objetivos](https://opencode.ai/docs/pt-br/go#objetivos) --------------------------------------------------------- Criamos o OpenCode Go para: 1. Tornar a IA de codificação **acessível** a mais pessoas com uma assinatura de baixo custo. 2. Fornecer acesso **confiável** aos melhores modelos de codificação abertos. 3. Curar modelos que são **testados e avaliados** para uso em agentes de codificação. 4. Não ter **nenhum bloqueio (lock-in)**, permitindo que você use qualquer outro provedor com o OpenCode também. --- # Zen | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/zen#_top) Zen === Подобранный список моделей, предоставленный OpenCode. OpenCode Zen — это список протестированных и проверенных моделей, предоставленный командой OpenCode. Zen работает как любой другой провайдер в OpenCode. Вы входите в OpenCode Zen и получаете ваш ключ API. Это **совершенно необязательно**, и вам не обязательно использовать его для использования OpenCode. * * * [Предыстория](https://opencode.ai/docs/ru/zen#%D0%BF%D1%80%D0%B5%D0%B4%D1%8B%D1%81%D1%82%D0%BE%D1%80%D0%B8%D1%8F) ------------------------------------------------------------------------------------------------------------------ Существует большое количество моделей, но лишь некоторые из них хорошо работают в качестве кодинг-агентов. Кроме того, большинство провайдеров настроены совсем по-другому; так что вы получите совсем другую производительность и качество. Поэтому, если вы используете модель через что-то вроде OpenRouter, вы никогда не сможете уверен, что вы получаете лучшую версию модели, которую хотите. Чтобы это исправить, мы сделали пару вещей: 1. Мы протестировали избранную группу моделей и поговорили с их командами о том, как лучше всего запустить их. 2. Затем мы поработали с несколькими поставщиками услуг, чтобы убедиться, что они обслуживаются правильно. 3. Наконец, мы сравнили комбинацию модель/провайдер и составили список, который мы с удовольствием рекомендуем. OpenCode Zen — это шлюз искусственного интеллекта, который дает вам доступ к этим моделям. * * * [Как это работает](https://opencode.ai/docs/ru/zen#%D0%BA%D0%B0%D0%BA-%D1%8D%D1%82%D0%BE-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82) ------------------------------------------------------------------------------------------------------------------------------------------- OpenCode Zen работает так же, как и любой другой поставщик OpenCode. 1. Вы входите в систему **[OpenCode Zen](https://opencode.ai/auth) **, добавляете платежные данные и копируете свой ключ API. 2. Вы запускаете команду `/connect` в TUI, выбираете OpenCode Zen и вставляете свой ключ API. 3. Запустите `/models` в TUI, чтобы просмотреть список рекомендуемых нами моделей. С вас взимается плата за каждый запрос, и вы можете добавить кредиты на свой счет. * * * [Конечные точки](https://opencode.ai/docs/ru/zen#%D0%BA%D0%BE%D0%BD%D0%B5%D1%87%D0%BD%D1%8B%D0%B5-%D1%82%D0%BE%D1%87%D0%BA%D0%B8) ---------------------------------------------------------------------------------------------------------------------------------- Вы также можете получить доступ к нашим моделям через следующие конечные точки API. | Модель | Идентификатор модели | Конечная точка | Пакет AI SDK | | --- | --- | --- | --- | | GPT 5.4 | gpt-5.4 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.3 Codex | gpt-5.3-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 | gpt-5.2 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.2 Codex | gpt-5.2-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 | gpt-5.1 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex | gpt-5.1-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Max | gpt-5.1-codex-max | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5.1 Codex Mini | gpt-5.1-codex-mini | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 | gpt-5 | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Codex | gpt-5-codex | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | GPT 5 Nano | gpt-5-nano | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` | | Claude Opus 4.6 | claude-opus-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.5 | claude-opus-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Opus 4.1 | claude-opus-4-1 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.6 | claude-sonnet-4-6 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4.5 | claude-sonnet-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Sonnet 4 | claude-sonnet-4 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Claude Haiku 3.5 | claude-3-5-haiku | `https://opencode.ai/zen/v1/messages` | `@ai-sdk/anthropic` | | Gemini 3.1 Pro | gemini-3.1-pro | `https://opencode.ai/zen/v1/models/gemini-3.1-pro` | `@ai-sdk/google` | | Gemini 3 Pro | gemini-3-pro | `https://opencode.ai/zen/v1/models/gemini-3-pro` | `@ai-sdk/google` | | Gemini 3 Flash | gemini-3-flash | `https://opencode.ai/zen/v1/models/gemini-3-flash` | `@ai-sdk/google` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 Free | minimax-m2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.1 | minimax-m2.1 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 5 | glm-5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.7 | glm-4.7 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | GLM 4.6 | glm-4.6 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 Thinking | kimi-k2-thinking | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2 | kimi-k2 | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Qwen3 Coder 480B | qwen3-coder | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Big Pickle | big-pickle | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` | [модель id](https://opencode.ai/docs/config/#models) в вашей конфигурации opencode использует формат `opencode/`. Например, для Кодекса GPT 5.2 вы должны используйте `opencode/gpt-5.2-codex` в вашей конфигурации. * * * ### [Модели](https://opencode.ai/docs/ru/zen#%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D0%B8) Полный список доступных моделей и их метаданные можно получить по адресу: https://opencode.ai/zen/v1/models * * * [Цены](https://opencode.ai/docs/ru/zen#%D1%86%D0%B5%D0%BD%D1%8B) ----------------------------------------------------------------- Мы поддерживаем модель оплаты по мере использования. Ниже приведены цены **за 1 миллион токенов**. | Модель | Вход | Выход | Кэшированное чтение | Кэшированная запись | | --- | --- | --- | --- | --- | | Big Pickle | Бесплатно | Бесплатно | Бесплатно | \- | | MiniMax M2.5 Free | Бесплатно | Бесплатно | Бесплатно | \- | | MiniMax M2.5 | $0.30 | $1.20 | $0.06 | \- | | MiniMax M2.1 | $0.30 | $1.20 | $0.10 | \- | | GLM 5 | $1.00 | $3.20 | $0.20 | \- | | GLM 4.7 | $0.60 | $2.20 | $0.10 | \- | | GLM 4.6 | $0.60 | $2.20 | $0.10 | \- | | Kimi K2.5 | $0.60 | $3.00 | $0.08 | \- | | Kimi K2 Thinking | $0.40 | $2.50 | \- | \- | | Kimi K2 | $0.40 | $2.50 | \- | \- | | Qwen3 Coder 480B | $0.45 | $1.50 | \- | \- | | Claude Opus 4.6 (≤ 200 тыс. токенов) | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.6 (> 200 тыс. токенов) | $10.00 | $37.50 | $1.00 | $12.50 | | Claude Opus 4.5 | $5.00 | $25.00 | $0.50 | $6.25 | | Claude Opus 4.1 | $15.00 | $75.00 | $1.50 | $18.75 | | Claude Sonnet 4.6 (≤ 200 тыс. токенов) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.6 (> 200 тыс. токенов) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4.5 (≤ 200 тыс. токенов) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4.5 (> 200 тыс. токенов) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Sonnet 4 (≤ 200 тыс. токенов) | $3.00 | $15.00 | $0.30 | $3.75 | | Claude Sonnet 4 (> 200 тыс. токенов) | $6.00 | $22.50 | $0.60 | $7.50 | | Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | | Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | $1.00 | | Gemini 3.1 Pro (≤ 200 тыс. токенов) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3.1 Pro (> 200 тыс. токенов) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Pro (≤ 200 тыс. токенов) | $2.00 | $12.00 | $0.20 | \- | | Gemini 3 Pro (> 200 тыс. токенов) | $4.00 | $18.00 | $0.40 | \- | | Gemini 3 Flash | $0.50 | $3.00 | $0.05 | \- | | GPT 5.4 | $2.50 | $15.00 | $0.25 | \- | | GPT 5.3 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 | $1.75 | $14.00 | $0.175 | \- | | GPT 5.2 Codex | $1.75 | $14.00 | $0.175 | \- | | GPT 5.1 | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5.1 Codex Max | $1.25 | $10.00 | $0.125 | \- | | GPT 5.1 Codex Mini | $0.25 | $2.00 | $0.025 | \- | | GPT 5 | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Codex | $1.07 | $8.50 | $0.107 | \- | | GPT 5 Nano | Бесплатно | Бесплатно | Бесплатно | \- | Вы можете заметить _Claude Haiku 3.5_ в своей истории использования. Это [недорогая модель](https://opencode.ai/docs/config/#models) , которая используется для создания заголовков ваших сеансов. Бесплатные модели: * MiniMax M2.5 Free доступен на OpenCode в течение ограниченного времени. Команда использует это время для сбора отзывов и улучшения модели. * Big Pickle — это стелс-модель, которая доступна бесплатно на OpenCode в течение ограниченного времени. Команда использует это время для сбора отзывов и улучшения модели. [Свяжитесь с нами](mailto:contact@anoma.ly) , если у вас есть вопросы. * * * ### [Автопополнение](https://opencode.ai/docs/ru/zen#%D0%B0%D0%B2%D1%82%D0%BE%D0%BF%D0%BE%D0%BF%D0%BE%D0%BB%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5) Если ваш баланс упадет ниже 5 долларов, Zen автоматически пополнит 20 долларов. Вы можете изменить сумму автопополнения. Вы также можете полностью отключить автопополнение. * * * ### [Ежемесячные лимиты](https://opencode.ai/docs/ru/zen#%D0%B5%D0%B6%D0%B5%D0%BC%D0%B5%D1%81%D1%8F%D1%87%D0%BD%D1%8B%D0%B5-%D0%BB%D0%B8%D0%BC%D0%B8%D1%82%D1%8B) Вы также можете установить месячный лимит использования для всего рабочего пространства и для каждого член вашей команды. Например, предположим, что вы установили ежемесячный лимит использования в размере 20 долларов США, Zen не будет использовать более 20 долларов в месяц. Но если у вас включено автопополнение, Zen может взимать с вас более 20 долларов США, если ваш баланс опускается ниже 5 долларов США. * * * ### [Устаревшие модели](https://opencode.ai/docs/ru/zen#%D1%83%D1%81%D1%82%D0%B0%D1%80%D0%B5%D0%B2%D1%88%D0%B8%D0%B5-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D0%B8) | Модель | Дата отключения | | --- | --- | | Qwen3 Coder 480B | 6 февр. 2026 г. | | Kimi K2 Thinking | 6 марта 2026 г. | | Kimi K2 | 6 марта 2026 г. | | MiniMax M2.1 | 15 марта 2026 г. | | GLM 4.7 | 15 марта 2026 г. | | GLM 4.6 | 15 марта 2026 г. | * * * [Конфиденциальность](https://opencode.ai/docs/ru/zen#%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B4%D0%B5%D0%BD%D1%86%D0%B8%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C) ------------------------------------------------------------------------------------------------------------------------------------------------------------------- Все наши модели размещены в США. Наши поставщики придерживаются политики нулевого хранения и не используют ваши данные для обучения моделей, за следующими исключениями: * Big Pickle: во время бесплатного периода собранные данные могут быть использованы для улучшения модели. * MiniMax M2.5 Free: в течение бесплатного периода собранные данные могут использоваться для улучшения модели. * API OpenAI: запросы хранятся в течение 30 дней в соответствии с [Политикой данных OpenAI](https://platform.openai.com/docs/guides/your-data) . * API-интерфейсы Anthropic: запросы хранятся в течение 30 дней в соответствии с [Политикой данных Anthropic](https://docs.anthropic.com/en/docs/claude-code/data-usage) . * * * [Для команд](https://opencode.ai/docs/ru/zen#%D0%B4%D0%BB%D1%8F-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4) ------------------------------------------------------------------------------------------------------ Zen также отлично подходит для команд. Вы можете приглашать товарищей по команде, назначать роли, выбирать модели, которые использует ваша команда, и многое другое. Управление вашим рабочим пространством в настоящее время бесплатно для команд в рамках бета-тестирования. Мы вскоре поделимся более подробной информацией о ценах. * * * ### [Роли](https://opencode.ai/docs/ru/zen#%D1%80%D0%BE%D0%BB%D0%B8) Вы можете приглашать товарищей по команде в свое рабочее пространство и распределять роли: * **Администратор**: управляйте моделями, участниками, ключами API и выставлением счетов. * **Участник**: Управляйте только своими собственными ключами API. Администраторы также могут установить ежемесячные лимиты расходов для каждого участника, чтобы держать расходы под контролем. * * * ### [Доступ к модели](https://opencode.ai/docs/ru/zen#%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF-%D0%BA-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D0%B8) Администраторы могут включать или отключать определенные модели для рабочей области. Запросы, сделанные к отключенной модели, вернут ошибку. Это полезно в случаях, когда вы хотите отключить использование модели, которая собирает данные. * * * ### [Использование собственных API-ключей](https://opencode.ai/docs/ru/zen#%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D1%81%D0%BE%D0%B1%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D1%8B%D1%85-api-%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%B9) Вы можете использовать свои собственные ключи API OpenAI или Anthropic, сохраняя при этом доступ к другим моделям в Zen. Когда вы используете свои собственные ключи, счета за токены взимаются непосредственно провайдером, а не Zen. Например, у вашей организации уже может быть ключ для OpenAI или Anthropic. и вы хотите использовать его вместо того, который предоставляет Zen. * * * [Цели](https://opencode.ai/docs/ru/zen#%D1%86%D0%B5%D0%BB%D0%B8) ----------------------------------------------------------------- Мы создали OpenCode Zen, чтобы: 1. **Сравнить** лучшие модели/поставщики кодинг-агентов. 2. Получить доступ к вариантам **наивысшего качества**, не снижая производительность и не обращаясь к более дешевым поставщикам. 3. Передавать **снижение цен**, продавая по себестоимости; поэтому единственная наценка предназначена для покрытия наших комиссий за обработку. 4. Исключить **привязку**, позволяя использовать его с любым другим кодинг-агентом. И всегда позволяя вам использовать любого другого провайдера с OpenCode. --- # Custom Tools | OpenCode [Skip to content](https://opencode.ai/docs/custom-tools#_top) Custom Tools ============ Create tools the LLM can call in opencode. Custom tools are functions you create that the LLM can call during conversations. They work alongside opencode’s [built-in tools](https://opencode.ai/docs/tools) like `read`, `write`, and `bash`. * * * [Creating a tool](https://opencode.ai/docs/custom-tools#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](https://opencode.ai/docs/custom-tools#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](https://opencode.ai/docs/custom-tools#structure) The easiest way to create tools is using the `tool()` helper which provides type-safety and validation. 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](https://opencode.ai/docs/custom-tools#multiple-tools-per-file) You can also export multiple tools from a single file. Each export becomes **a separate tool** with the name **`_`**: 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 },}) 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 },}) This creates two tools: `math_add` and `math_multiply`. * * * #### [Name collisions with built-in tools](https://opencode.ai/docs/custom-tools#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 `bash` tool: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Arguments](https://opencode.ai/docs/custom-tools#arguments) You can use `tool.schema`, which is just [Zod](https://zod.dev/) , to define argument types. args: { query: tool.schema.string().describe("SQL query to execute")} You can also import [Zod](https://zod.dev/) directly and return a plain object: 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](https://opencode.ai/docs/custom-tools#context) Tools receive context about the current session: 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](https://opencode.ai/docs/custom-tools#examples) ----------------------------------------------------------- ### [Write a tool in Python](https://opencode.ai/docs/custom-tools#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: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Then create the tool definition that invokes it: 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.$`](https://bun.com/docs/runtime/shell) utility to run the Python script. --- # Benutzerdefinierte Tools | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/custom-tools#_top) Benutzerdefinierte Tools ======================== Erstellen Sie Tools, die der LLM in OpenCode aufrufen kann. Benutzerdefinierte Tools sind von Ihnen erstellte Funktionen, die der LLM während Gesprächen aufrufen kann. Sie arbeiten neben [built-in tools](https://opencode.ai/docs/tools) von OpenCode wie `read`, `write` und `bash`. * * * [Ein Tool erstellen](https://opencode.ai/docs/de/custom-tools#ein-tool-erstellen) ---------------------------------------------------------------------------------- Tools werden als **TypeScript**\- oder **JavaScript**\-Dateien definiert. Die Tooldefinition kann jedoch Skripte aufrufen, die in **jeder Sprache** geschrieben sind – TypeScript oder JavaScript wird nur für die Tooldefinition selbst verwendet. * * * ### [Speicherort](https://opencode.ai/docs/de/custom-tools#speicherort) Sie können wie folgt definiert werden: * Lokal, indem Sie sie im Verzeichnis `.opencode/tools/` Ihres Projekts platzieren. * Oder global, indem Sie sie in `~/.config/opencode/tools/` platzieren. * * * ### [Struktur](https://opencode.ai/docs/de/custom-tools#struktur) Der einfachste Weg, Tools zu erstellen, ist die Verwendung des `tool()`\-Helfers, der Typsicherheit und Validierung bietet. 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}` },}) Der **Dateiname** wird zum **Toolnamen**. Das Obige erstellt ein `database`\-Tool. * * * #### [Mehrere Werkzeuge pro Datei](https://opencode.ai/docs/de/custom-tools#mehrere-werkzeuge-pro-datei) Sie können auch mehrere Tools aus einer einzigen Datei exportieren. Jeder Export wird zu **einem separaten Tool** mit dem Namen **`_`**: 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 },}) 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 },}) Dadurch werden zwei Tools erstellt: `math_add` und `math_multiply`. * * * ### [Argumente](https://opencode.ai/docs/de/custom-tools#argumente) Sie können `tool.schema` verwenden, was nur [Zod](https://zod.dev/) ist, um Argumenttypen zu definieren. args: { query: tool.schema.string().describe("SQL query to execute")} Sie können [Zod](https://zod.dev/) auch direkt importieren und ein ähnliches Objekt zurückgeben: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Kontext](https://opencode.ai/docs/de/custom-tools#kontext) Tools erhalten Kontext zur aktuellen Sitzung: 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}` },}) Verwenden Sie `context.directory` für das Sitzungsarbeitsverzeichnis. Verwenden Sie `context.worktree` für das Stammverzeichnis des Git-Arbeitsbaums. * * * [Beispiele](https://opencode.ai/docs/de/custom-tools#beispiele) ---------------------------------------------------------------- ### [Ein Tool in Python schreiben](https://opencode.ai/docs/de/custom-tools#ein-tool-in-python-schreiben) Sie können Ihre Tools in jeder gewünschten Sprache schreiben. Hier ist ein Beispiel, das mit Python zwei Zahlen addiert. Erstellen Sie zunächst das Tool als Python-Skript: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Erstellen Sie dann die Werkzeugdefinition, die es aufruft: 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() },}) Hier verwenden wir das Dienstprogramm [`Bun.$`](https://bun.com/docs/runtime/shell) , um das Python-Skript auszuführen. --- # Go | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/go#_top) Go == Недорогая подписка на открытые модели для кодинга. OpenCode Go — это недорогая подписка за **$10/месяц**, которая предоставляет надежный доступ к популярным открытым моделям для кодинга. Go работает как любой другой провайдер в OpenCode. Вы подписываетесь на OpenCode Go и получаете свой API ключ. Это **полностью опционально**, и вам не нужно использовать его, чтобы пользоваться OpenCode. Он разработан в первую очередь для международных пользователей, с моделями, размещенными в США, ЕС и Сингапуре для стабильного глобального доступа. * * * [Предыстория](https://opencode.ai/docs/ru/go#%D0%BF%D1%80%D0%B5%D0%B4%D1%8B%D1%81%D1%82%D0%BE%D1%80%D0%B8%D1%8F) ----------------------------------------------------------------------------------------------------------------- Открытые модели стали действительно хорошими. Теперь они достигают производительности, близкой к проприетарным моделям для задач кодинга. И поскольку многие провайдеры могут обслуживать их на конкурентной основе, они обычно намного дешевле. Однако получение надежного доступа к ним с низкой задержкой может быть сложным. Качество и доступность провайдеров варьируются. Чтобы исправить это, мы сделали пару вещей: 1. Мы протестировали избранную группу открытых моделей и поговорили с их командами о том, как лучше всего их запускать. 2. Затем мы работали с несколькими провайдерами, чтобы убедиться, что они обслуживаются правильно. 3. Наконец, мы провели бенчмаркинг комбинации модели/провайдера и составили список, который мы можем смело рекомендовать. OpenCode Go дает вам доступ к этим моделям за **$10/месяц**. * * * [Как это работает](https://opencode.ai/docs/ru/go#%D0%BA%D0%B0%D0%BA-%D1%8D%D1%82%D0%BE-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82) ------------------------------------------------------------------------------------------------------------------------------------------ OpenCode Go работает как любой другой провайдер в OpenCode. 1. Вы входите в **[OpenCode Zen](https://opencode.ai/auth) **, подписываетесь на Go и копируете свой API ключ. 2. Вы запускаете команду `/connect` в TUI, выбираете `OpenCode Go` и вставляете свой API ключ. 3. Запустите `/models` в TUI, чтобы увидеть список моделей, доступных через Go. Текущий список моделей включает: * **GLM-5** * **Kimi K2.5** * **MiniMax M2.5** Список моделей может меняться по мере того, как мы тестируем и добавляем новые. * * * [Лимиты использования](https://opencode.ai/docs/ru/go#%D0%BB%D0%B8%D0%BC%D0%B8%D1%82%D1%8B-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode Go включает следующие лимиты: * **5-часовой лимит** — $12 использования * **Недельный лимит** — $30 использования * **Месячный лимит** — $60 использования Лимиты определены в денежном выражении. Это означает, что ваше фактическое количество запросов зависит от модели, которую вы используете. Более дешевые модели, такие как MiniMax M2.5, позволяют делать больше запросов, в то время как более дорогие модели, такие как GLM-5, позволяют меньше. Таблица ниже предоставляет примерное количество запросов на основе типичных паттернов использования Go: | | GLM-5 | Kimi K2.5 | MiniMax M2.5 | | --- | --- | --- | --- | | запросов за 5 часов | 1,150 | 1,850 | 30,000 | | запросов в неделю | 2,880 | 4,630 | 75,000 | | запросов в месяц | 5,750 | 9,250 | 150,000 | Оценки основаны на наблюдаемых средних паттернах запросов: * GLM-5 — 700 входных, 52,000 кэшированных, 150 выходных токенов на запрос * Kimi K2.5 — 870 входных, 55,000 кэшированных, 200 выходных токенов на запрос * MiniMax M2.5 — 300 входных, 55,000 кэшированных, 125 выходных токенов на запрос Вы можете отслеживать свое текущее использование в **[консоли](https://opencode.ai/auth) **. Лимиты использования могут меняться по мере того, как мы учимся на раннем использовании и отзывах. * * * ### [Ценообразование](https://opencode.ai/docs/ru/go#%D1%86%D0%B5%D0%BD%D0%BE%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) OpenCode Go — это план подписки за **$10/месяц**. Ниже приведены цены **за 1 млн токенов**. | Модель | Ввод | Вывод | Кэшированное чтение | | --- | --- | --- | --- | | GLM-5 | $1.00 | $3.20 | $0.20 | | Kimi K2.5 | $0.60 | $3.00 | $0.10 | | MiniMax M2.5 | $0.30 | $1.20 | $0.03 | * * * ### [Использование сверх лимитов](https://opencode.ai/docs/ru/go#%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D1%81%D0%B2%D0%B5%D1%80%D1%85-%D0%BB%D0%B8%D0%BC%D0%B8%D1%82%D0%BE%D0%B2) Если у вас также есть кредиты на балансе Zen, вы можете включить опцию **Use balance** (Использовать баланс) в консоли. Когда она включена, Go переключится на ваш баланс Zen после того, как вы исчерпаете свои лимиты использования, вместо блокировки запросов. * * * [Эндпоинты](https://opencode.ai/docs/ru/go#%D1%8D%D0%BD%D0%B4%D0%BF%D0%BE%D0%B8%D0%BD%D1%82%D1%8B) --------------------------------------------------------------------------------------------------- Вы также можете получить доступ к моделям Go через следующие API эндпоинты. | Модель | ID модели | Эндпоинт | Пакет AI SDK | | --- | --- | --- | --- | | GLM-5 | glm-5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | Kimi K2.5 | kimi-k2.5 | `https://opencode.ai/zen/go/v1/chat/completions` | `@ai-sdk/openai-compatible` | | MiniMax M2.5 | minimax-m2.5 | `https://opencode.ai/zen/go/v1/messages` | `@ai-sdk/anthropic` | [Model id](https://opencode.ai/docs/config/#models) в вашей конфигурации OpenCode использует формат `opencode-go/`. Например, для Kimi K2.5 вы бы использовали `opencode-go/kimi-k2.5` в вашей конфигурации. * * * [Конфиденциальность](https://opencode.ai/docs/ru/go#%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B4%D0%B5%D0%BD%D1%86%D0%B8%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C) ------------------------------------------------------------------------------------------------------------------------------------------------------------------ План разработан в первую очередь для международных пользователей, с моделями, размещенными в США, ЕС и Сингапуре для стабильного глобального доступа. [Свяжитесь с нами](mailto:contact@anoma.ly) , если у вас есть вопросы. * * * [Цели](https://opencode.ai/docs/ru/go#%D1%86%D0%B5%D0%BB%D0%B8) ---------------------------------------------------------------- Мы создали OpenCode Go, чтобы: 1. Сделать ИИ-кодинг **доступным** большему количеству людей с недорогой подпиской. 2. Обеспечить **надежный** доступ к лучшим открытым моделям для кодинга. 3. Отобрать модели, которые **протестированы и проверены** для использования агентами кодинга. 4. Не иметь **привязки к поставщику** (no lock-in), позволяя вам использовать любого другого провайдера с OpenCode. --- # 自訂工具 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/custom-tools#_top) 自訂工具 ==== 建立 LLM 可在 OpenCode 中呼叫的工具。 自訂工具是您建立的函式,LLM 可以在對話過程中呼叫它們。它們與 OpenCode 的[內建工具](https://opencode.ai/docs/tools) (如 `read`、`write` 和 `bash`)協同工作。 * * * [建立工具](https://opencode.ai/docs/zh-tw/custom-tools#%E5%BB%BA%E7%AB%8B%E5%B7%A5%E5%85%B7) ----------------------------------------------------------------------------------------- 工具以 **TypeScript** 或 **JavaScript** 檔案的形式定義。不過,工具定義可以呼叫**任何語言**編寫的指令碼——TypeScript 或 JavaScript 僅用於工具定義本身。 * * * ### [位置](https://opencode.ai/docs/zh-tw/custom-tools#%E4%BD%8D%E7%BD%AE) 工具可以在以下位置定義: * 本地定義:將工具檔案放在專案的 `.opencode/tools/` 目錄中。 * 全域定義:將工具檔案放在 `~/.config/opencode/tools/` 中。 * * * ### [結構](https://opencode.ai/docs/zh-tw/custom-tools#%E7%B5%90%E6%A7%8B) 建立工具最簡單的方式是使用 `tool()` 輔助函式,它提供型別安全和參數校驗。 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}` },}) **檔案名稱**即為**工具名稱**。上面的範例建立了一個名為 `database` 的工具。 * * * #### [單檔案多工具](https://opencode.ai/docs/zh-tw/custom-tools#%E5%96%AE%E6%AA%94%E6%A1%88%E5%A4%9A%E5%B7%A5%E5%85%B7) 您也可以從單個檔案中匯出多個工具。每個匯出都會成為**一個獨立的工具**,命名格式為 **`_`**: 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 },}) 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 },}) 這會建立兩個工具:`math_add` 和 `math_multiply`。 * * * #### [與內建工具名稱衝突](https://opencode.ai/docs/zh-tw/custom-tools#%E8%88%87%E5%85%A7%E5%BB%BA%E5%B7%A5%E5%85%B7%E5%90%8D%E7%A8%B1%E8%A1%9D%E7%AA%81) 自訂工具以工具名稱作為鍵值。如果自訂工具使用與內建工具相同的名稱,則自訂工具具有優先權。 例如,此檔案將替換內建的 `bash` 工具: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [參數](https://opencode.ai/docs/zh-tw/custom-tools#%E5%8F%83%E6%95%B8) 您可以使用 `tool.schema`(即 [Zod](https://zod.dev/) )來定義參數型別。 args: { query: tool.schema.string().describe("SQL query to execute")} 您也可以直接匯入 [Zod](https://zod.dev/) 並回傳一個普通物件: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [上下文](https://opencode.ai/docs/zh-tw/custom-tools#%E4%B8%8A%E4%B8%8B%E6%96%87) 工具會接收當前工作階段的上下文資訊: 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}` },}) 使用 `context.directory` 取得工作階段的工作目錄。 使用 `context.worktree` 取得 git worktree 根目錄。 * * * [範例](https://opencode.ai/docs/zh-tw/custom-tools#%E7%AF%84%E4%BE%8B) --------------------------------------------------------------------- ### [用 Python 編寫工具](https://opencode.ai/docs/zh-tw/custom-tools#%E7%94%A8-python-%E7%B7%A8%E5%AF%AB%E5%B7%A5%E5%85%B7) 您可以使用任何語言編寫工具。以下範例展示了如何用 Python 實作兩數相加。 首先,建立一個 Python 指令碼作為工具: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) 然後建立呼叫該指令碼的工具定義: 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() },}) 這裡我們使用 [`Bun.$`](https://bun.com/docs/runtime/shell) 工具函式來執行 Python 指令碼。 --- # Özel Araçlar | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/custom-tools#_top) Özel Araçlar ============ LLM'un opencode'da çağırabileceği araçları birleştirebilir. Özel araçlar, LLM’un konuşmalar sırasında arayabileceği, oluşturduğunuz işlevlerdir. opencode’un [built-in tools](https://opencode.ai/docs/tools) ile birlikte `read`, `write` ve `bash` gibi çalışırlar. * * * [Araç oluşturma](https://opencode.ai/docs/tr/custom-tools#ara%C3%A7-olu%C5%9Fturma) ------------------------------------------------------------------------------------ Araçlar **TypeScript** veya **JavaScript** dosyaları olarak tanımlanır. Ancak araç tanımı **herhangi bir dilde** yazılmış komut dosyalarını çağırabilir; TypeScript veya JavaScript yalnızca araç tanımının kendisi için kullanılır. * * * ### [Konum](https://opencode.ai/docs/tr/custom-tools#konum) Bunlar tanımlanabilir: * Yerel olarak bunları projenizin `.opencode/tools/` dizinine yerleştirerek. * Veya küresel olarak bunları `~/.config/opencode/tools/` içine yerleştirerek. * * * ### [Yapı](https://opencode.ai/docs/tr/custom-tools#yap%C4%B1) Araç oluşturmanın en kolay yolu, tür güvenliği ve doğrulama sağlayan `tool()` yardımcısını kullanmaktır. 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}` },}) **dosya adı**, **araç adı** olur. Yukarıdakiler bir `database` aracı oluşturur. * * * #### [Dosya başına birden fazla araç](https://opencode.ai/docs/tr/custom-tools#dosya-ba%C5%9F%C4%B1na-birden-fazla-ara%C3%A7) Ayrıca tek bir dosyadan birden fazla aracı dışa aktarabilirsiniz. Her dışa aktarma, **`_`** adıyla **ayrı bir araç** haline gelir: 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 },}) 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 },}) Bu iki araç oluşturur: `math_add` ve `math_multiply`. * * * #### [Yerleşik araçlarla ad çakışmaları](https://opencode.ai/docs/tr/custom-tools#yerle%C5%9Fik-ara%C3%A7larla-ad-%C3%A7ak%C4%B1%C5%9Fmalar%C4%B1) Özel araçlar, araç adına göre anahtarlanır. Özel bir araç yerleşik bir araçla aynı adı kullanıyorsa, özel araç önceliklidir. Örneğin, bu dosya yerleşik `bash` aracının yerini alır: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Argümanlar](https://opencode.ai/docs/tr/custom-tools#arg%C3%BCmanlar) Bağımsız değişken türlerini tanımlamak için yalnızca [Zod](https://zod.dev/) olan `tool.schema` öğesini kullanabilirsiniz. args: { query: tool.schema.string().describe("SQL query to execute")} Ayrıca [Zod](https://zod.dev/) öğesini doğrudan içe aktarabilir ve düz bir nesne döndürebilirsiniz: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Bağlam](https://opencode.ai/docs/tr/custom-tools#ba%C4%9Flam) Araçlar geçerli oturumla ilgili bağlamı alır: 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}` },}) Oturum çalışma dizisi için `context.directory` kullanın. Git çalışma ağacı kökü için `context.worktree` kullanın. * * * [Örnekler](https://opencode.ai/docs/tr/custom-tools#%C3%B6rnekler) ------------------------------------------------------------------- ### [Python ile araç yazma](https://opencode.ai/docs/tr/custom-tools#python-ile-ara%C3%A7-yazma) Araçlarınızı dilediğiniz dilde yazabilirsiniz. İşte Python kullanarak iki sayıyı toplayan bir örnek. Öncelikle aracı bir Python betiği olarak oluşturun: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Ardından onu çağıran araç tanımını oluşturun: 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() },}) Burada Python betiğini çalıştırmak için [`Bun.$`](https://bun.com/docs/runtime/shell) yardımcı programını kullanıyoruz. --- # TUI | OpenCode [Skip to content](https://opencode.ai/docs/tui#_top) TUI === Using the OpenCode terminal user interface. OpenCode provides an interactive terminal interface or TUI for working on your projects with an LLM. Running OpenCode starts the TUI for the current directory. opencode Or you can start it for a specific working directory. opencode /path/to/project Once you’re in the TUI, you can prompt it with a message. Give me a quick summary of the codebase. * * * [File references](https://opencode.ai/docs/tui#file-references) ---------------------------------------------------------------- You can reference files in your messages using `@`. This does a fuzzy file search in the current working directory. How is auth handled in @packages/functions/src/api/index.ts? The content of the file is added to the conversation automatically. * * * [Bash commands](https://opencode.ai/docs/tui#bash-commands) ------------------------------------------------------------ Start a message with `!` to run a shell command. !ls -la The output of the command is added to the conversation as a tool result. * * * [Commands](https://opencode.ai/docs/tui#commands) -------------------------------------------------- When using the OpenCode TUI, you can type `/` followed by a command name to quickly execute actions. For example: /help Most commands also have keybind using `ctrl+x` as the leader key, where `ctrl+x` is the default leader key. [Learn more](https://opencode.ai/docs/keybinds) . Here are all available slash commands: * * * ### [connect](https://opencode.ai/docs/tui#connect) Add a provider to OpenCode. Allows you to select from available providers and add their API keys. /connect * * * ### [compact](https://opencode.ai/docs/tui#compact) Compact the current session. _Alias_: `/summarize` /compact **Keybind:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/tui#details) Toggle tool execution details. /details **Keybind:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/tui#editor) Open external editor for composing messages. Uses the editor set in your `EDITOR` environment variable. [Learn more](https://opencode.ai/docs/tui#editor-setup) . /editor **Keybind:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/tui#exit) Exit OpenCode. _Aliases_: `/quit`, `/q` /exit **Keybind:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/tui#export) Export current conversation to Markdown and open in your default editor. Uses the editor set in your `EDITOR` environment variable. [Learn more](https://opencode.ai/docs/tui#editor-setup) . /export **Keybind:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/tui#help) Show the help dialog. /help **Keybind:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/tui#init) Create or update `AGENTS.md` file. [Learn more](https://opencode.ai/docs/rules) . /init **Keybind:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/tui#models) List available models. /models **Keybind:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/tui#new) Start a new session. _Alias_: `/clear` /new **Keybind:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/tui#redo) Redo a previously undone message. Only available after using `/undo`. Internally, this uses Git to manage the file changes. So your project **needs to be a Git repository**. /redo **Keybind:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/tui#sessions) List and switch between sessions. _Aliases_: `/resume`, `/continue` /sessions **Keybind:** `ctrl+x l` * * * Share current session. [Learn more](https://opencode.ai/docs/share) . /share **Keybind:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/tui#themes) List available themes. /themes **Keybind:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/tui#thinking) Toggle the visibility of thinking/reasoning blocks in the conversation. When enabled, you can see the model’s reasoning process for models that support extended thinking. /thinking * * * ### [undo](https://opencode.ai/docs/tui#undo) Undo last message in the conversation. Removes the most recent user message, all subsequent responses, and any file changes. Internally, this uses Git to manage the file changes. So your project **needs to be a Git repository**. /undo **Keybind:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/tui#unshare) Unshare current session. [Learn more](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Editor setup](https://opencode.ai/docs/tui#editor-setup) ---------------------------------------------------------- Both the `/editor` and `/export` commands use the editor specified in your `EDITOR` environment variable. * [Linux/macOS](https://opencode.ai/docs/tui#tab-panel-4) * [Windows (CMD)](https://opencode.ai/docs/tui#tab-panel-5) * [Windows (PowerShell)](https://opencode.ai/docs/tui#tab-panel-6) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" To make it permanent, add this to your shell profile; `~/.bashrc`, `~/.zshrc`, etc. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait To make it permanent, use **System Properties** > **Environment Variables**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" To make it permanent, add this to your PowerShell profile. Popular editor options include: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim editor * `vim` - Vim editor * `nano` - Nano editor * `notepad` - Windows Notepad * `subl` - Sublime Text Some editors need command-line arguments to run in blocking mode. The `--wait` flag makes the editor process block until closed. * * * [Configure](https://opencode.ai/docs/tui#configure) ---------------------------------------------------- You can customize TUI behavior through `tui.json` (or `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} This is separate from `opencode.json`, which configures server/runtime behavior. ### [Options](https://opencode.ai/docs/tui#options) * `theme` - Sets your UI theme. [Learn more](https://opencode.ai/docs/themes) . * `keybinds` - Customizes keyboard shortcuts. [Learn more](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Enable macOS-style scroll acceleration for smooth, natural scrolling. When enabled, scroll speed increases with rapid scrolling gestures and stays precise for slower movements. **This setting takes precedence over `scroll_speed` and overrides it when enabled.** * `scroll_speed` - Controls how fast the TUI scrolls when using scroll commands (minimum: `0.001`, supports decimal values). Defaults to `3`. **Note: This is ignored if `scroll_acceleration.enabled` is set to `true`.** * `diff_style` - Controls diff rendering. `"auto"` adapts to terminal width, `"stacked"` always shows a single-column layout. Use `OPENCODE_TUI_CONFIG` to load a custom TUI config path. * * * [Customization](https://opencode.ai/docs/tui#customization) ------------------------------------------------------------ You can customize various aspects of the TUI view using the command palette (`ctrl+x h` or `/help`). These settings persist across restarts. * * * #### [Username display](https://opencode.ai/docs/tui#username-display) Toggle whether your username appears in chat messages. Access this through: * Command palette: Search for “username” or “hide username” * The setting persists automatically and will be remembered across TUI sessions --- # 自定义工具 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/custom-tools#_top) 自定义工具 ===== 创建 LLM 可在 opencode 中调用的工具。 自定义工具是你创建的函数,LLM 可以在对话过程中调用它们。它们与 opencode 的[内置工具](https://opencode.ai/docs/tools) (如 `read`、`write` 和 `bash`)协同工作。 * * * [创建工具](https://opencode.ai/docs/zh-cn/custom-tools#%E5%88%9B%E5%BB%BA%E5%B7%A5%E5%85%B7) ----------------------------------------------------------------------------------------- 工具以 **TypeScript** 或 **JavaScript** 文件的形式定义。不过,工具定义可以调用**任何语言**编写的脚本——TypeScript 或 JavaScript 仅用于工具定义本身。 * * * ### [位置](https://opencode.ai/docs/zh-cn/custom-tools#%E4%BD%8D%E7%BD%AE) 工具可以在以下位置定义: * 本地定义:将工具文件放在项目的 `.opencode/tools/` 目录中。 * 全局定义:将工具文件放在 `~/.config/opencode/tools/` 中。 * * * ### [结构](https://opencode.ai/docs/zh-cn/custom-tools#%E7%BB%93%E6%9E%84) 创建工具最简单的方式是使用 `tool()` 辅助函数,它提供类型安全和参数校验。 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}` },}) **文件名**即为**工具名称**。上面的示例创建了一个名为 `database` 的工具。 * * * #### [单文件多工具](https://opencode.ai/docs/zh-cn/custom-tools#%E5%8D%95%E6%96%87%E4%BB%B6%E5%A4%9A%E5%B7%A5%E5%85%B7) 你也可以从单个文件中导出多个工具。每个导出都会成为**一个独立的工具**,命名格式为 **`_`**: 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 },}) 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 },}) 这会创建两个工具:`math_add` 和 `math_multiply`。 * * * #### [与内置工具的名称冲突](https://opencode.ai/docs/zh-cn/custom-tools#%E4%B8%8E%E5%86%85%E7%BD%AE%E5%B7%A5%E5%85%B7%E7%9A%84%E5%90%8D%E7%A7%B0%E5%86%B2%E7%AA%81) 自定义工具通过工具名称进行索引。如果自定义工具使用了与内置工具相同的名称,则优先使用自定义工具。 例如,这个文件取代了内置的bash工具: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [参数](https://opencode.ai/docs/zh-cn/custom-tools#%E5%8F%82%E6%95%B0) 你可以使用 `tool.schema`(即 [Zod](https://zod.dev/) )来定义参数类型。 args: { query: tool.schema.string().describe("SQL query to execute")} 你也可以直接导入 [Zod](https://zod.dev/) 并返回一个普通对象: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [上下文](https://opencode.ai/docs/zh-cn/custom-tools#%E4%B8%8A%E4%B8%8B%E6%96%87) 工具会接收当前会话的上下文信息: 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}` },}) 使用 `context.directory` 获取会话的工作目录。 使用 `context.worktree` 获取 git worktree 根目录。 * * * [示例](https://opencode.ai/docs/zh-cn/custom-tools#%E7%A4%BA%E4%BE%8B) --------------------------------------------------------------------- ### [用 Python 编写工具](https://opencode.ai/docs/zh-cn/custom-tools#%E7%94%A8-python-%E7%BC%96%E5%86%99%E5%B7%A5%E5%85%B7) 你可以使用任何语言编写工具。以下示例展示了如何用 Python 实现两数相加。 首先,创建一个 Python 脚本作为工具: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) 然后创建调用该脚本的工具定义: 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() },}) 这里我们使用 [`Bun.$`](https://bun.com/docs/runtime/shell) 工具函数来运行 Python 脚本。 --- # Herramientas personalizadas | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/custom-tools#_top) Herramientas personalizadas =========================== Cree herramientas que LLM pueda llamar en opencode. Las herramientas personalizadas son funciones que usted crea y que el LLM puede llamar durante las conversaciones. Trabajan junto con las [herramientas integradas](https://opencode.ai/docs/tools) de opencode como `read`, `write` y `bash`. * * * [Crear una herramienta](https://opencode.ai/docs/es/custom-tools#crear-una-herramienta) ---------------------------------------------------------------------------------------- Las herramientas se definen como archivos **TypeScript** o **JavaScript**. Sin embargo, la definición de la herramienta puede invocar secuencias de comandos escritas en **cualquier idioma**: TypeScript o JavaScript solo se utilizan para la definición de la herramienta en sí. * * * ### [Ubicación](https://opencode.ai/docs/es/custom-tools#ubicaci%C3%B3n) Se pueden definir: * Localmente colocándolos en el directorio `.opencode/tools/` de tu proyecto. * O de forma global, colocándolos en `~/.config/opencode/tools/`. * * * ### [Estructura](https://opencode.ai/docs/es/custom-tools#estructura) La forma más sencilla de crear herramientas es utilizar el asistente `tool()` que proporciona seguridad de tipos y validación. 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}` },}) El **nombre de archivo** se convierte en el **nombre de la herramienta**. Lo anterior crea una herramienta `database`. * * * #### [Múltiples herramientas por archivo](https://opencode.ai/docs/es/custom-tools#m%C3%BAltiples-herramientas-por-archivo) También puede exportar varias herramientas desde un solo archivo. Cada exportación se convierte en **una herramienta independiente** con el nombre **`_`**: 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 },}) 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 },}) Esto crea dos herramientas: `math_add` y `math_multiply`. * * * #### [Colisiones de nombres con herramientas integradas](https://opencode.ai/docs/es/custom-tools#colisiones-de-nombres-con-herramientas-integradas) Las herramientas personalizadas están codificadas por el nombre de la herramienta. Si una herramienta personalizada utiliza el mismo nombre que una herramienta integrada, la herramienta personalizada tiene prioridad. Por ejemplo, este archivo reemplaza la herramienta `bash` integrada: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Argumentos](https://opencode.ai/docs/es/custom-tools#argumentos) Puedes usar `tool.schema`, que es simplemente [Zod](https://zod.dev/) , para definir tipos de argumentos. args: { query: tool.schema.string().describe("SQL query to execute")} También puedes importar [Zod](https://zod.dev/) directamente y devolver un objeto simple: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Contexto](https://opencode.ai/docs/es/custom-tools#contexto) Las herramientas reciben contexto sobre la sesión actual: 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}` },}) Utilice `context.directory` para el directorio de trabajo de la sesión. Utilice `context.worktree` para la raíz del árbol de trabajo de git. * * * [Ejemplos](https://opencode.ai/docs/es/custom-tools#ejemplos) -------------------------------------------------------------- ### [Escribir una herramienta en Python](https://opencode.ai/docs/es/custom-tools#escribir-una-herramienta-en-python) Puede escribir sus herramientas en cualquier idioma que desee. Aquí hay un ejemplo que suma dos números usando Python. Primero, cree la herramienta como un script de Python: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Luego cree la definición de herramienta que la invoca: 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() },}) Aquí estamos usando la utilidad [`Bun.$`](https://bun.com/docs/runtime/shell) para ejecutar el script Python. --- # Пользовательские инструменты | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/custom-tools#_top) Пользовательские инструменты ============================ Создавайте инструменты, которые LLM может вызывать в opencode. Пользовательские инструменты — это создаваемые вами функции, которые LLM может вызывать во время разговоров. Они работают вместе со [встроенными инструментами](https://opencode.ai/docs/tools) opencode, такими как `read`, `write` и `bash`. * * * [Создание инструмента](https://opencode.ai/docs/ru/custom-tools#%D1%81%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%B0) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Инструменты определяются как файлы **TypeScript** или **JavaScript**. Однако определение инструмента может вызывать сценарии, написанные на **любом языке** — TypeScript или JavaScript используются только для самого определения инструмента. * * * ### [Расположение](https://opencode.ai/docs/ru/custom-tools#%D1%80%D0%B0%D1%81%D0%BF%D0%BE%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) Их можно определить: * Локально, поместив их в каталог `.opencode/tools/` вашего проекта. * Или глобально, поместив их в `~/.config/opencode/tools/`. * * * ### [Структура](https://opencode.ai/docs/ru/custom-tools#%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0) Самый простой способ создания инструментов — использовать помощник `tool()`, который обеспечивает безопасность типов и проверку. 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}` },}) **имя файла** становится **именем инструмента**. Вышеупомянутое создает инструмент `database`. * * * #### [Несколько инструментов в файле](https://opencode.ai/docs/ru/custom-tools#%D0%BD%D0%B5%D1%81%D0%BA%D0%BE%D0%BB%D1%8C%D0%BA%D0%BE-%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%BE%D0%B2-%D0%B2-%D1%84%D0%B0%D0%B9%D0%BB%D0%B5) Вы также можете экспортировать несколько инструментов из одного файла. Каждый экспорт становится **отдельным инструментом** с именем **`_`**: 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 },}) 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 },}) При этом создаются два инструмента: `math_add` и `math_multiply`. * * * ### [Аргументы](https://opencode.ai/docs/ru/custom-tools#%D0%B0%D1%80%D0%B3%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B) Вы можете использовать `tool.schema`, то есть просто [Zod](https://zod.dev/) , для определения типов аргументов. args: { query: tool.schema.string().describe("SQL query to execute")} Вы также можете импортировать [Zod](https://zod.dev/) напрямую и вернуть простой объект: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Контекст](https://opencode.ai/docs/ru/custom-tools#%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BA%D1%81%D1%82) Инструменты получают контекст текущего сеанса: 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}` },}) Используйте `context.directory` для рабочего каталога сеанса. Используйте `context.worktree` для корня рабочего дерева git. * * * [Примеры](https://opencode.ai/docs/ru/custom-tools#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B) ----------------------------------------------------------------------------------------------- ### [Инструмент на Python](https://opencode.ai/docs/ru/custom-tools#%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82-%D0%BD%D0%B0-python) Вы можете писать свои инструменты на любом языке, который захотите. Вот пример сложения двух чисел с использованием Python. Сначала создайте инструмент как скрипт Python: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Затем создайте определение инструмента, которое его вызывает: 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() },}) Здесь мы используем утилиту [`Bun.$`](https://bun.com/docs/runtime/shell) для запуска скрипта Python. --- # Troubleshooting | OpenCode [Skip to content](https://opencode.ai/docs/troubleshooting#_top) Troubleshooting =============== Common issues and how to resolve them. To debug issues with OpenCode, start by checking the logs and local data it stores on disk. * * * [Logs](https://opencode.ai/docs/troubleshooting#logs) ------------------------------------------------------ Log files are written to: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.local\share\opencode\log` Log files are named with timestamps (e.g., `2025-01-09T123456.log`) and the most recent 10 log files are kept. You can set the log level with the `--log-level` command-line option to get more detailed debug information. For example, `opencode --log-level DEBUG`. * * * [Storage](https://opencode.ai/docs/troubleshooting#storage) ------------------------------------------------------------ opencode stores session data and other application data on disk at: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.local\share\opencode` This directory contains: * `auth.json` - Authentication data like API keys, OAuth tokens * `log/` - Application logs * `project/` - Project-specific data like session and message data * If the project is within a Git repo, it is stored in `.//storage/` * If it is not a Git repo, it is stored in `./global/storage/` * * * [Desktop app](https://opencode.ai/docs/troubleshooting#desktop-app) -------------------------------------------------------------------- OpenCode Desktop runs a local OpenCode server (the `opencode-cli` sidecar) in the background. Most issues are caused by a misbehaving plugin, a corrupted cache, or a bad server setting. ### [Quick checks](https://opencode.ai/docs/troubleshooting#quick-checks) * Fully quit and relaunch the app. * If the app shows an error screen, click **Restart** and copy the error details. * macOS only: `OpenCode` menu -> **Reload Webview** (helps if the UI is blank/frozen). * * * ### [Disable plugins](https://opencode.ai/docs/troubleshooting#disable-plugins) If the desktop app is crashing on launch, hanging, or behaving strangely, start by disabling plugins. #### [Check the global config](https://opencode.ai/docs/troubleshooting#check-the-global-config) Open your global config file and look for a `plugin` key. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (or `~/.config/opencode/opencode.json`) * **macOS/Linux** (older installs): `~/.local/share/opencode/opencode.jsonc` * **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.config\opencode\opencode.jsonc` If you have plugins configured, temporarily disable them by removing the key or setting it to an empty array: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Check plugin directories](https://opencode.ai/docs/troubleshooting#check-plugin-directories) OpenCode can also load local plugins from disk. Temporarily move these out of the way (or rename the folder) and restart the desktop app: * **Global plugins** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.config\opencode\plugins` * **Project plugins** (only if you use per-project config) * `/.opencode/plugins/` If the app starts working again, re-enable plugins one at a time to find which one is causing the issue. * * * ### [Clear the cache](https://opencode.ai/docs/troubleshooting#clear-the-cache) If disabling plugins doesn’t help (or a plugin install is stuck), clear the cache so OpenCode can rebuild it. 1. Quit OpenCode Desktop completely. 2. Delete the cache directory: * **macOS**: Finder -> `Cmd+Shift+G` -> paste `~/.cache/opencode` * **Linux**: delete `~/.cache/opencode` (or run `rm -rf ~/.cache/opencode`) * **Windows**: Press `WIN+R` and paste `%USERPROFILE%\.cache\opencode` 3. Restart OpenCode Desktop. * * * ### [Fix server connection issues](https://opencode.ai/docs/troubleshooting#fix-server-connection-issues) OpenCode Desktop can either start its own local server (default) or connect to a server URL you configured. If you see a **“Connection Failed”** dialog (or the app never gets past the splash screen), check for a custom server URL. #### [Clear the desktop default server URL](https://opencode.ai/docs/troubleshooting#clear-the-desktop-default-server-url) From the Home screen, click the server name (with the status dot) to open the Server picker. In the **Default server** section, click **Clear**. #### [Remove `server.port` / `server.hostname` from your config](https://opencode.ai/docs/troubleshooting#remove-serverport--serverhostname-from-your-config) If your `opencode.json(c)` contains a `server` section, temporarily remove it and restart the desktop app. #### [Check environment variables](https://opencode.ai/docs/troubleshooting#check-environment-variables) If you have `OPENCODE_PORT` set in your environment, the desktop app will try to use that port for the local server. * Unset `OPENCODE_PORT` (or pick a free port) and restart. * * * ### [Linux: Wayland / X11 issues](https://opencode.ai/docs/troubleshooting#linux-wayland--x11-issues) On Linux, some Wayland setups can cause blank windows or compositor errors. * If you’re on Wayland and the app is blank/crashing, try launching with `OC_ALLOW_WAYLAND=1`. * If that makes things worse, remove it and try launching under an X11 session instead. * * * ### [Windows: WebView2 runtime](https://opencode.ai/docs/troubleshooting#windows-webview2-runtime) On Windows, OpenCode Desktop requires the Microsoft Edge **WebView2 Runtime**. If the app opens to a blank window or won’t start, install/update WebView2 and try again. * * * ### [Windows: General performance issues](https://opencode.ai/docs/troubleshooting#windows-general-performance-issues) If you’re experiencing slow performance, file access issues, or terminal problems on Windows, try using [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) . WSL provides a Linux environment that works more seamlessly with OpenCode’s features. * * * ### [Notifications not showing](https://opencode.ai/docs/troubleshooting#notifications-not-showing) OpenCode Desktop only shows system notifications when: * notifications are enabled for OpenCode in your OS settings, and * the app window is not focused. * * * ### [Reset desktop app storage (last resort)](https://opencode.ai/docs/troubleshooting#reset-desktop-app-storage-last-resort) If the app won’t start and you can’t clear settings from inside the UI, reset the desktop app’s saved state. 1. Quit OpenCode Desktop. 2. Find and delete these files (they live in the OpenCode Desktop app data directory): * `opencode.settings.dat` (desktop default server URL) * `opencode.global.dat` and `opencode.workspace.*.dat` (UI state like recent servers/projects) To find the directory quickly: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (then search for the filenames above) * **Linux**: search under `~/.local/share` for the filenames above * **Windows**: Press `WIN+R` -> `%APPDATA%` (then search for the filenames above) * * * [Getting help](https://opencode.ai/docs/troubleshooting#getting-help) ---------------------------------------------------------------------- If you’re experiencing issues with OpenCode: 1. **Report issues on GitHub** The best way to report bugs or request features is through our GitHub repository: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Before creating a new issue, search existing issues to see if your problem has already been reported. 2. **Join our Discord** For real-time help and community discussion, join our Discord server: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Common issues](https://opencode.ai/docs/troubleshooting#common-issues) ------------------------------------------------------------------------ Here are some common issues and how to resolve them. * * * ### [OpenCode won’t start](https://opencode.ai/docs/troubleshooting#opencode-wont-start) 1. Check the logs for error messages 2. Try running with `--print-logs` to see output in the terminal 3. Ensure you have the latest version with `opencode upgrade` * * * ### [Authentication issues](https://opencode.ai/docs/troubleshooting#authentication-issues) 1. Try re-authenticating with the `/connect` command in the TUI 2. Check that your API keys are valid 3. Ensure your network allows connections to the provider’s API * * * ### [Model not available](https://opencode.ai/docs/troubleshooting#model-not-available) 1. Check that you’ve authenticated with the provider 2. Verify the model name in your config is correct 3. Some models may require specific access or subscriptions If you encounter `ProviderModelNotFoundError` you are most likely incorrectly referencing a model somewhere. Models should be referenced like so: `/` Examples: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` To figure out what models you have access to, run `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/troubleshooting#provideriniterror) If you encounter a ProviderInitError, you likely have an invalid or corrupted configuration. To resolve this: 1. First, verify your provider is set up correctly by following the [providers guide](https://opencode.ai/docs/providers) 2. If the issue persists, try clearing your stored configuration: rm -rf ~/.local/share/opencode On Windows, press `WIN+R` and delete: `%USERPROFILE%\.local\share\opencode` 3. Re-authenticate with your provider using the `/connect` command in the TUI. * * * ### [AI\_APICallError and provider package issues](https://opencode.ai/docs/troubleshooting#ai_apicallerror-and-provider-package-issues) If you encounter API call errors, this may be due to outdated provider packages. opencode dynamically installs provider packages (OpenAI, Anthropic, Google, etc.) as needed and caches them locally. To resolve provider package issues: 1. Clear the provider package cache: rm -rf ~/.cache/opencode On Windows, press `WIN+R` and delete: `%USERPROFILE%\.cache\opencode` 2. Restart opencode to reinstall the latest provider packages This will force opencode to download the most recent versions of provider packages, which often resolves compatibility issues with model parameters and API changes. * * * ### [Copy/paste not working on Linux](https://opencode.ai/docs/troubleshooting#copypaste-not-working-on-linux) Linux users need to have one of the following clipboard utilities installed for copy/paste functionality to work: **For X11 systems:** apt install -y xclip# orapt install -y xsel **For Wayland systems:** apt install -y wl-clipboard **For headless environments:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode will detect if you’re using Wayland and prefer `wl-clipboard`, otherwise it will try to find clipboard tools in order of: `xclip` and `xsel`. --- # Keybinds | OpenCode [Skip to content](https://opencode.ai/docs/keybinds#_top) Keybinds ======== Customize your keybinds. OpenCode has a list of keybinds that you can customize through `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Leader key](https://opencode.ai/docs/keybinds#leader-key) ----------------------------------------------------------- OpenCode uses a `leader` key for most keybinds. This avoids conflicts in your terminal. By default, `ctrl+x` is the leader key and most 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. * * * [Disable keybind](https://opencode.ai/docs/keybinds#disable-keybind) --------------------------------------------------------------------- You can disable a keybind by adding the key to `tui.json` with a value of “none”. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Desktop prompt shortcuts](https://opencode.ai/docs/keybinds#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](https://opencode.ai/docs/keybinds#shiftenter) ------------------------------------------------------------ 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](https://opencode.ai/docs/keybinds#windows-terminal) Open your `settings.json` at: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Add this to the root-level `actions` array: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Add this to the root-level `keybindings` array:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Save the file and restart Windows Terminal or open a new tab. --- # カスタムツール | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/custom-tools#_top) カスタムツール ======= LLM が OpenCode で呼び出すことができるツールを作成します。 カスタムツールは、会話中に LLM が呼び出すことができる作成した関数です。これらは、OpenCode の[組み込みツール](https://opencode.ai/docs/tools) (`read`、`write`、`bash` など) と連携して動作します。 * * * [ツールの作成](https://opencode.ai/docs/ja/custom-tools#%E3%83%84%E3%83%BC%E3%83%AB%E3%81%AE%E4%BD%9C%E6%88%90) ---------------------------------------------------------------------------------------------------------- ツールは **TypeScript** または **JavaScript** ファイルとして定義されます。ただし、ツール定義では**任意の言語**で記述されたスクリプトを呼び出すことができます。TypeScript または JavaScript はツール定義自体にのみ使用されます。 * * * ### [場所](https://opencode.ai/docs/ja/custom-tools#%E5%A0%B4%E6%89%80) それらは次のように定義できます。 * ローカルでは、プロジェクトの `.opencode/tools/` ディレクトリに配置します。 * または、グローバルに、それらを `~/.config/opencode/tools/` に配置します。 * * * ### [構造](https://opencode.ai/docs/ja/custom-tools#%E6%A7%8B%E9%80%A0) ツールを作成する最も簡単な方法は、型安全性と検証を提供する `tool()` ヘルパーを使用することです。 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}` },}) **ファイル名**は**ツール名**になります。上記により `database` ツールが作成されます。 * * * #### [ファイルごとに複数のツール](https://opencode.ai/docs/ja/custom-tools#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%94%E3%81%A8%E3%81%AB%E8%A4%87%E6%95%B0%E3%81%AE%E3%83%84%E3%83%BC%E3%83%AB) 単一のファイルから複数のツールをエクスポートすることもできます。各エクスポートは **`_`** という名前の **別のツール** になります。 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 },}) 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 },}) これにより、`math_add` と `math_multiply` という 2 つのツールが作成されます。 * * * #### [組み込みツールとの名前の衝突](https://opencode.ai/docs/ja/custom-tools#%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF%E3%83%84%E3%83%BC%E3%83%AB%E3%81%A8%E3%81%AE%E5%90%8D%E5%89%8D%E3%81%AE%E8%A1%9D%E7%AA%81) カスタムツールはツール名でキー設定されます。カスタムツールが組み込みツールと同じ名前を使用する場合、カスタムツールが優先されます。 たとえば、このファイルは組み込みの `bash` ツールを置き換えます。 import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [引数](https://opencode.ai/docs/ja/custom-tools#%E5%BC%95%E6%95%B0) 引数の型を定義するには、`tool.schema` (つまり [Zod](https://zod.dev/) ) を使用できます。 args: { query: tool.schema.string().describe("SQL query to execute")} [Zod](https://zod.dev/) を直接インポートしてプレーンオブジェクトを返すこともできます。 import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [コンテキスト](https://opencode.ai/docs/ja/custom-tools#%E3%82%B3%E3%83%B3%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88) ツールは現在のセッションに関するコンテキストを受け取ります。 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}` },}) セッションの作業ディレクトリには `context.directory` を使用します。 git ワークツリーのルートには `context.worktree` を使用します。 * * * [例](https://opencode.ai/docs/ja/custom-tools#%E4%BE%8B) -------------------------------------------------------- ### [Python でのツールの作成](https://opencode.ai/docs/ja/custom-tools#python-%E3%81%A7%E3%81%AE%E3%83%84%E3%83%BC%E3%83%AB%E3%81%AE%E4%BD%9C%E6%88%90) ツールは任意の言語で作成できます。以下は、Python を使用して 2 つの数値を加算する例です。 まず、ツールを Python スクリプトとして作成します。 import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) 次に、それを呼び出すツール定義を作成します。 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() },}) ここでは、[`Bun.$`](https://bun.com/docs/runtime/shell) ユーティリティを使用して Python スクリプトを実行しています。 --- # Ferramentas Personalizadas | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/custom-tools#_top) Ferramentas Personalizadas ========================== Crie ferramentas que o LLM pode chamar no opencode. Ferramentas personalizadas são funções que você cria e que o LLM pode chamar durante as conversas. Elas funcionam junto com as [ferramentas integradas](https://opencode.ai/docs/tools) do opencode, como `read`, `write` e `bash`. * * * [Criando uma ferramenta](https://opencode.ai/docs/pt-br/custom-tools#criando-uma-ferramenta) --------------------------------------------------------------------------------------------- As ferramentas são definidas como arquivos **TypeScript** ou **JavaScript**. No entanto, a definição da ferramenta pode invocar scripts escritos em **qualquer linguagem** — TypeScript ou JavaScript é usado apenas para a definição da ferramenta em si. * * * ### [Localização](https://opencode.ai/docs/pt-br/custom-tools#localiza%C3%A7%C3%A3o) Elas podem ser definidas: * Localmente, colocando-as no diretório `.opencode/tools/` do seu projeto. * Ou globalmente, colocando-as em `~/.config/opencode/tools/`. * * * ### [Estrutura](https://opencode.ai/docs/pt-br/custom-tools#estrutura) A maneira mais fácil de criar ferramentas é usando o helper `tool()`, que fornece segurança de tipo e validação. import { tool } from "@opencode-ai/plugin" export default tool({ description: "Consultar o banco de dados do projeto", args: { query: tool.schema.string().describe("Consulta SQL para executar"), }, async execute(args) { // Sua lógica de banco de dados aqui return `Consulta executada: ${args.query}` },}) O **nome do arquivo** se torna o **nome da ferramenta**. O acima cria uma ferramenta `database`. * * * #### [Múltiplas ferramentas por arquivo](https://opencode.ai/docs/pt-br/custom-tools#m%C3%BAltiplas-ferramentas-por-arquivo) Você também pode exportar várias ferramentas de um único arquivo. Cada exportação se torna **uma ferramenta separada** com o nome **`_`**: import { tool } from "@opencode-ai/plugin" export const add = tool({ description: "Adicionar dois números", args: { a: tool.schema.number().describe("Primeiro número"), b: tool.schema.number().describe("Segundo número"), }, async execute(args) { return args.a + args.b },}) export const multiply = tool({ description: "Multiplicar dois números", args: { a: tool.schema.number().describe("Primeiro número"), b: tool.schema.number().describe("Segundo número"), }, async execute(args) { return args.a * args.b },}) Isso cria duas ferramentas: `math_add` e `math_multiply`. * * * #### [Colisões de nome com ferramentas integradas](https://opencode.ai/docs/pt-br/custom-tools#colis%C3%B5es-de-nome-com-ferramentas-integradas) Ferramentas personalizadas são chaveadas pelo nome da ferramenta. Se uma ferramenta personalizada usar o mesmo nome que uma ferramenta integrada, a ferramenta personalizada tem precedência. Por exemplo, este arquivo substitui a ferramenta `bash` integrada: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Argumentos](https://opencode.ai/docs/pt-br/custom-tools#argumentos) Você pode usar `tool.schema`, que é apenas [Zod](https://zod.dev/) , para definir tipos de argumentos. args: { query: tool.schema.string().describe("Consulta SQL para executar")} Você também pode importar [Zod](https://zod.dev/) diretamente e retornar um objeto simples: import { z } from "zod" export default { description: "Descrição da ferramenta", args: { param: z.string().describe("Descrição do parâmetro"), }, async execute(args, context) { // Implementação da ferramenta return "result" },} * * * ### [Contexto](https://opencode.ai/docs/pt-br/custom-tools#contexto) As ferramentas recebem contexto sobre a sessão atual: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Obter informações do projeto", args: {}, async execute(args, context) { // Acessar informações de contexto const { agent, sessionID, messageID, directory, worktree } = context return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}, Directory: ${directory}, Worktree: ${worktree}` },}) Use `context.directory` para o diretório de trabalho da sessão. Use `context.worktree` para a raiz do worktree do git. * * * [Exemplos](https://opencode.ai/docs/pt-br/custom-tools#exemplos) ----------------------------------------------------------------- ### [Escrevendo uma ferramenta em Python](https://opencode.ai/docs/pt-br/custom-tools#escrevendo-uma-ferramenta-em-python) Você pode escrever suas ferramentas em qualquer linguagem que desejar. Aqui está um exemplo que adiciona dois números usando Python. Primeiro, crie a ferramenta como um script Python: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Em seguida, crie a definição da ferramenta que a invoca: import { tool } from "@opencode-ai/plugin"import path from "path" export default tool({ description: "Adicionar dois números usando Python", args: { a: tool.schema.number().describe("Primeiro número"), b: tool.schema.number().describe("Segundo número"), }, 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() },}) Aqui estamos usando o utilitário [`Bun.$`](https://bun.com/docs/runtime/shell) para executar o script Python. --- # เครื่องมือที่กำหนดเอง | OpenCode [Skip to content](https://opencode.ai/docs/th/custom-tools#_top) เครื่องมือที่กำหนดเอง ===================== สร้างเครื่องมือที่ LLM สามารถเรียกใช้ใน opencode เครื่องมือแบบกำหนดเองคือฟังก์ชันที่คุณสร้างขึ้นซึ่ง LLM สามารถเรียกใช้ระหว่างการสนทนาได้ โดยทำงานร่วมกับ [เครื่องมือในตัว](https://opencode.ai/docs/tools) ของ opencode เช่น `read`, `write` และ `bash` * * * [การสร้างเครื่องมือ](https://opencode.ai/docs/th/custom-tools#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เครื่องมือถูกกำหนดให้เป็นไฟล์ **TypeScript** หรือ **JavaScript** อย่างไรก็ตาม คำจำกัดความของเครื่องมือสามารถเรียกใช้สคริปต์ที่เขียนใน **ภาษาใดก็ได้** — TypeScript หรือ JavaScript ใช้สำหรับคำจำกัดความของเครื่องมือเท่านั้น * * * ### [ที่ตั้ง](https://opencode.ai/docs/th/custom-tools#%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87) สามารถกำหนดได้: * ภายในเครื่องโดยวางไว้ในไดเรกทอรี `.opencode/tools/` ของโครงการของคุณ * หรือทั่วโลกโดยวางไว้ที่ `~/.config/opencode/tools/` * * * ### [โครงสร้าง](https://opencode.ai/docs/th/custom-tools#%E0%B9%82%E0%B8%84%E0%B8%A3%E0%B8%87%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87) วิธีที่ง่ายที่สุดในการสร้างเครื่องมือคือการใช้ตัวช่วย `tool()` ซึ่งให้ความปลอดภัยและการตรวจสอบประเภท 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}` },}) **ชื่อไฟล์** จะกลายเป็น **ชื่อเครื่องมือ** ข้างต้นจะสร้างเครื่องมือ `database` * * * #### [เครื่องมือหลายอย่างต่อไฟล์](https://opencode.ai/docs/th/custom-tools#%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B8%AB%E0%B8%A5%E0%B8%B2%E0%B8%A2%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C) คุณยังสามารถส่งออกเครื่องมือหลายรายการจากไฟล์เดียวได้ การส่งออกแต่ละครั้งจะกลายเป็น **เครื่องมือแยกต่างหาก** โดยมีชื่อ **`_`**: 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 },}) 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 },}) สิ่งนี้จะสร้างเครื่องมือสองอย่าง: `math_add` และ `math_multiply` * * * #### [ชื่อซ้ำกับเครื่องมือในตัว](https://opencode.ai/docs/th/custom-tools#%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%8B%E0%B9%89%E0%B8%B3%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B9%83%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7) เครื่องมือแบบกำหนดเองจะถูกระบุด้วยชื่อเครื่องมือ หากเครื่องมือแบบกำหนดเองใช้ชื่อเดียวกับเครื่องมือในตัว เครื่องมือแบบกำหนดเองจะมีความสำคัญเหนือกว่า ตัวอย่างเช่น ไฟล์นี้จะแทนที่เครื่องมือ `bash` ในตัว: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [ข้อโต้แย้ง](https://opencode.ai/docs/th/custom-tools#%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B9%82%E0%B8%95%E0%B9%89%E0%B9%81%E0%B8%A2%E0%B9%89%E0%B8%87) คุณสามารถใช้ `tool.schema` ซึ่งก็คือ [Zod](https://zod.dev/) เพื่อกำหนดประเภทอาร์กิวเมนต์ args: { query: tool.schema.string().describe("SQL query to execute")} คุณยังสามารถนำเข้า [Zod](https://zod.dev/) ได้โดยตรงและส่งคืนออบเจ็กต์ธรรมดา: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [บริบท](https://opencode.ai/docs/th/custom-tools#%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%9A%E0%B8%97) เครื่องมือได้รับบริบทเกี่ยวกับเซสชันปัจจุบัน: 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}` },}) ใช้ `context.directory` สำหรับไดเร็กทอรีการทำงานของเซสชัน ใช้ `context.worktree` สำหรับรูท git worktree * * * [ตัวอย่าง](https://opencode.ai/docs/th/custom-tools#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87) ------------------------------------------------------------------------------------------------------------------------------ ### [เขียนเครื่องมือใน Python](https://opencode.ai/docs/th/custom-tools#%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B9%83%E0%B8%99-python) คุณสามารถเขียนเครื่องมือของคุณเป็นภาษาใดก็ได้ที่คุณต้องการ นี่คือตัวอย่างที่บวกตัวเลขสองตัวโดยใช้ Python ขั้นแรก สร้างเครื่องมือเป็นสคริปต์ Python: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) จากนั้นสร้างคำจำกัดความของเครื่องมือที่เรียกใช้: 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() },}) ที่นี่เราใช้ยูทิลิตี้ [`Bun.$`](https://bun.com/docs/runtime/shell) เพื่อรันสคริปต์ Python --- # Outils personnalisés | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/custom-tools#_top) Outils personnalisés ==================== Créez des outils que le LLM peut appeler dans opencode. Les outils personnalisés sont des fonctions que vous créez et que le LLM peut appeler pendant les conversations. Ils fonctionnent avec les [outils intégrés](https://opencode.ai/docs/tools) de opencode comme `read`, `write` et `bash`. * * * [Création d’un outil](https://opencode.ai/docs/fr/custom-tools#cr%C3%A9ation-dun-outil) ---------------------------------------------------------------------------------------- Les outils sont définis sous forme de fichiers **TypeScript** ou **JavaScript**. Cependant, la définition de l’outil peut appeler des scripts écrits dans **n’importe quel langage** : TypeScript ou JavaScript n’est utilisé que pour la définition de l’outil elle-même. * * * ### [Emplacement](https://opencode.ai/docs/fr/custom-tools#emplacement) Ils peuvent être définis : * Localement en les plaçant dans le répertoire `.opencode/tools/` de votre projet. * Ou globalement, en les plaçant dans `~/.config/opencode/tools/`. * * * ### [Structure](https://opencode.ai/docs/fr/custom-tools#structure) Le moyen le plus simple de créer des outils est d’utiliser l’assistant `tool()` qui fournit la sécurité et la validation de type. 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}` },}) Le **nom de fichier** devient le **nom de l’outil**. Ce qui précède crée un outil `database`. * * * #### [Plusieurs outils par fichier](https://opencode.ai/docs/fr/custom-tools#plusieurs-outils-par-fichier) Vous pouvez également exporter plusieurs outils à partir d’un seul fichier. Chaque exportation devient **un outil distinct** portant le nom **`_`** : 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 },}) 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 },}) Cela crée deux outils : `math_add` et `math_multiply`. * * * ### [Arguments](https://opencode.ai/docs/fr/custom-tools#arguments) Vous pouvez utiliser `tool.schema`, qui est simplement [Zod](https://zod.dev/) , pour définir les types d’arguments. args: { query: tool.schema.string().describe("SQL query to execute")} Vous pouvez également importer [Zod](https://zod.dev/) directement et renvoyer un objet simple : import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Contexte](https://opencode.ai/docs/fr/custom-tools#contexte) Les outils reçoivent le contexte de la session en cours : 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}` },}) Utilisez `context.directory` pour le répertoire de travail de la session. Utilisez `context.worktree` pour la racine du worktree git. * * * [Exemples](https://opencode.ai/docs/fr/custom-tools#exemples) -------------------------------------------------------------- ### [Écrire un outil en Python](https://opencode.ai/docs/fr/custom-tools#%C3%A9crire-un-outil-en-python) Vous pouvez écrire vos outils dans le langage de votre choix. Voici un exemple qui ajoute deux nombres à l’aide de Python. Tout d’abord, créez l’outil en tant que script Python : import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Créez ensuite la définition d’outil qui l’invoque : 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() },}) Ici, nous utilisons l’utilitaire [`Bun.$`](https://bun.com/docs/runtime/shell) pour exécuter le script Python. --- # Web | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/web#_top) Web === Bruke OpenCode i nettleseren din. OpenCode kan kjøres som en nettapplikasjon i nettleseren din, og gir den samme kraftige AI-kodingsopplevelsen uten at du trenger en terminal. ![OpenCode Web - Ny økt](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Komme i gang](https://opencode.ai/docs/nb/web#komme-i-gang) ------------------------------------------------------------- Start web-grensesnittet ved å kjøre: opencode web Dette starter en lokal server på `127.0.0.1` med en tilfeldig tilgjengelig port og åpner automatisk OpenCode i standard nettleser. * * * [Konfigurasjon](https://opencode.ai/docs/nb/web#konfigurasjon) --------------------------------------------------------------- Du kan konfigurere webserveren ved å bruke kommandolinjeflagg eller i [konfigurasjonsfilen](https://opencode.ai/docs/config) . ### [Port](https://opencode.ai/docs/nb/web#port) Som standard velger OpenCode en tilgjengelig port. Du kan spesifisere en port: opencode web --port 4096 ### [Vertsnavn](https://opencode.ai/docs/nb/web#vertsnavn) Som standard binder serveren seg til `127.0.0.1` (kun localhost). Slik gjør du OpenCode tilgjengelig på nettverket ditt: opencode web --hostname 0.0.0.0 * * * ### [Autentisering](https://opencode.ai/docs/nb/web#autentisering) For å beskytte tilgang, angi et passord ved hjelp av miljøvariabelen `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web Brukernavnet er satt til `opencode` som standard, men kan endres med `OPENCODE_SERVER_USERNAME`. * * * [Bruke webgrensesnittet](https://opencode.ai/docs/nb/web#bruke-webgrensesnittet) --------------------------------------------------------------------------------- Når den er startet, gir nettgrensesnittet tilgang til dine OpenCode-økter. ### [Sesjoner](https://opencode.ai/docs/nb/web#sesjoner) Se og administrer øktene dine fra hjemmesiden. Du kan se aktive økter og starte nye. ![OpenCode Web - Active Session](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Serverstatus](https://opencode.ai/docs/nb/web#serverstatus) Klikk på “Se servere” for å se tilkoblede servere og deres status. ![OpenCode Web - Se servere](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Koble til en terminal](https://opencode.ai/docs/nb/web#koble-til-en-terminal) ------------------------------------------------------------------------------- Du kan koble en terminal TUI til en kjørende webserver: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Dette lar deg bruke både nettgrensesnittet og terminalen samtidig, og deler samme økter og tilstand. * * * [Konfigurasjonsfil](https://opencode.ai/docs/nb/web#konfigurasjonsfil) ----------------------------------------------------------------------- Du kan også konfigurere serverinnstillinger i `opencode.json` konfigurasjonsfilen: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Kommandolinjeflagg har forrang over konfigurasjonsfilinnstillinger. --- # 快捷鍵 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/keybinds#_top) 快捷鍵 === 自訂您的快捷鍵。 OpenCode 提供了一系列快捷鍵,您可以透過 `tui.json` 進行自訂。 { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [前導鍵](https://opencode.ai/docs/zh-tw/keybinds#%E5%89%8D%E5%B0%8E%E9%8D%B5) --------------------------------------------------------------------------- OpenCode 的大多數快捷鍵使用 `leader`(前導鍵)。這可以避免與終端機中的其他快捷鍵衝突。 預設情況下,`ctrl+x` 是前導鍵,大多數操作需要您先按下前導鍵,然後再按對應的快捷鍵。例如,要新建一個工作階段,請先按 `ctrl+x`,然後按 `n`。 您不一定需要使用前導鍵來設定快捷鍵,但我們建議您這樣做。 * * * [停用快捷鍵](https://opencode.ai/docs/zh-tw/keybinds#%E5%81%9C%E7%94%A8%E5%BF%AB%E6%8D%B7%E9%8D%B5) ----------------------------------------------------------------------------------------------- 您可以透過在 `tui.json` 中將對應的鍵值設定為 “none” 來停用某個快捷鍵。 { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [桌面版提示詞輸入快捷鍵](https://opencode.ai/docs/zh-tw/keybinds#%E6%A1%8C%E9%9D%A2%E7%89%88%E6%8F%90%E7%A4%BA%E8%A9%9E%E8%BC%B8%E5%85%A5%E5%BF%AB%E6%8D%B7%E9%8D%B5) ----------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode 桌面應用程式的提示詞輸入框支援常見的 Readline/Emacs 風格文字編輯快捷鍵。這些快捷鍵為內建功能,目前無法透過 `opencode.json` 進行設定。 | 快捷鍵 | 操作 | | --- | --- | | `ctrl+a` | 移動到當前行的開頭 | | `ctrl+e` | 移動到當前行的末尾 | | `ctrl+b` | 游標向後移動一個字元 | | `ctrl+f` | 游標向前移動一個字元 | | `alt+b` | 游標向後移動一個單詞 | | `alt+f` | 游標向前移動一個單詞 | | `ctrl+d` | 刪除游標所在位置的字元 | | `ctrl+k` | 刪除從游標到行尾的內容 | | `ctrl+u` | 刪除從游標到行首的內容 | | `ctrl+w` | 刪除前一個單詞 | | `alt+d` | 刪除後一個單詞 | | `ctrl+t` | 交換游標前後的字元 | | `ctrl+g` | 取消彈出視窗 / 中止正在執行的回應 | * * * [Shift+Enter](https://opencode.ai/docs/zh-tw/keybinds#shiftenter) ------------------------------------------------------------------ 某些終端機預設不會發送帶修飾鍵的 Enter 鍵。您可能需要設定終端機將 `Shift+Enter` 作為跳脫序列發送。 ### [Windows Terminal](https://opencode.ai/docs/zh-tw/keybinds#windows-terminal) 開啟您的 `settings.json` 檔案,路徑為: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json 將以下內容新增到根級 `actions` 陣列中: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ 將以下內容新增到根級 `keybindings` 陣列中:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ 儲存檔案並重新啟動 Windows Terminal,或開啟一個新分頁。 --- # 키바인드 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/keybinds#_top) 키바인드 ==== 키바인드를 커스터마이즈하세요. OpenCode에는 `tui.json`을 통해 커스터마이즈할 수 있는 키바인드 목록이 있습니다. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [리더 키](https://opencode.ai/docs/ko/keybinds#%EB%A6%AC%EB%8D%94-%ED%82%A4) -------------------------------------------------------------------------- OpenCode는 대부분의 keybinds에 `leader` 키를 사용합니다. 이렇게 하면 terminal에서 충돌을 피할 수 있습니다. 기본값으로 `ctrl+x`가 리더 키이며, 대부분의 작업은 먼저 리더 키를 누른 뒤 단축키를 누릅니다. 예를 들어 새 세션을 시작하려면 먼저 `ctrl+x`를 누르고 `n`을 누릅니다. keybinds에 리더 키를 꼭 사용할 필요는 없지만, 사용하는 것을 권장합니다. * * * [키바인드 비활성화](https://opencode.ai/docs/ko/keybinds#%ED%82%A4%EB%B0%94%EC%9D%B8%EB%93%9C-%EB%B9%84%ED%99%9C%EC%84%B1%ED%99%94) ---------------------------------------------------------------------------------------------------------------------------- `tui.json`에 해당 키를 값 `"none"`으로 추가하면 키바인드를 비활성화할 수 있습니다. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [데스크탑 프롬프트 단축키](https://opencode.ai/docs/ko/keybinds#%EB%8D%B0%EC%8A%A4%ED%81%AC%ED%83%91-%ED%94%84%EB%A1%AC%ED%94%84%ED%8A%B8-%EB%8B%A8%EC%B6%95%ED%82%A4) ------------------------------------------------------------------------------------------------------------------------------------------------------------ OpenCode 데스크톱 앱의 프롬프트 입력은 텍스트 편집을 위한 일반적인 Readline/Emacs-style 단축키를 지원합니다. 이 단축키는 내장되어 있으며 현재 `opencode.json`으로는 설정할 수 없습니다. | 단축키 | 동작 | | --- | --- | | `ctrl+a` | 현재 줄 시작으로 이동 | | `ctrl+e` | 현재 줄 끝으로 이동 | | `ctrl+b` | 커서를 문자 하나 뒤로 이동 | | `ctrl+f` | 커서를 문자 하나 앞으로 이동 | | `alt+b` | 커서를 단어 하나 뒤로 이동 | | `alt+f` | 커서를 단어 하나 앞으로 이동 | | `ctrl+d` | 커서 아래 문자 삭제 | | `ctrl+k` | 줄 끝까지 삭제 | | `ctrl+u` | 줄 시작까지 삭제 | | `ctrl+w` | 이전 단어 삭제 | | `alt+d` | 다음 단어 삭제 | | `ctrl+t` | 문자 순서 바꾸기 | | `ctrl+g` | 팝오버 취소 / 실행 중인 응답 중단 | * * * [Shift+Enter](https://opencode.ai/docs/ko/keybinds#shiftenter) --------------------------------------------------------------- 일부 terminal은 기본적으로 Enter와 modifier 키 조합을 전송하지 않습니다. `Shift+Enter`를 이스케이프 시퀀스로 전송하도록 terminal을 설정해야 할 수도 있습니다. ### [Windows Terminal](https://opencode.ai/docs/ko/keybinds#windows-terminal) 다음 경로의 `settings.json`을 여세요: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json 루트 레벨 `actions` 배열에 다음을 추가하세요: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ 루트 레벨 `keybindings` 배열에 다음을 추가하세요:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ 파일을 저장한 뒤 Windows Terminal을 다시 시작하거나 새 탭을 여세요. --- # Combinaciones de teclas | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/keybinds#_top) Combinaciones de teclas ======================= Personaliza tus combinaciones de teclas. OpenCode tiene una lista de combinaciones de teclas que puede personalizar a través de `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Tecla líder](https://opencode.ai/docs/es/keybinds#tecla-l%C3%ADder) --------------------------------------------------------------------- OpenCode usa una tecla `leader` para la mayoría de las combinaciones de teclas. Esto evita conflictos en tu terminal. De forma predeterminada, `ctrl+x` es la tecla principal y la mayoría de las acciones requieren que primero presione la tecla principal y luego el acceso directo. Por ejemplo, para iniciar una nueva sesión, primero presione `ctrl+x` y luego presione `n`. No es necesario utilizar una tecla líder para las combinaciones de teclas, pero le recomendamos que lo haga. * * * [Desactivar combinación de teclas](https://opencode.ai/docs/es/keybinds#desactivar-combinaci%C3%B3n-de-teclas) --------------------------------------------------------------------------------------------------------------- Puede deshabilitar una combinación de teclas agregando la clave a `tui.json` con un valor de “none”. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Atajos de mensajes de escritorio](https://opencode.ai/docs/es/keybinds#atajos-de-mensajes-de-escritorio) ---------------------------------------------------------------------------------------------------------- La entrada de solicitud de la aplicación de escritorio OpenCode admite atajos comunes de estilo Readline/Emacs para editar texto. Estos están integrados y actualmente no se pueden configurar a través de `opencode.json`. | Atajo | Acción | | --- | --- | | `ctrl+a` | Mover al inicio de la línea actual | | `ctrl+e` | Mover al final de la línea actual | | `ctrl+b` | Mover el cursor hacia atrás un carácter | | `ctrl+f` | Mover el cursor hacia adelante un carácter | | `alt+b` | Mover el cursor hacia atrás una palabra | | `alt+f` | Mover el cursor hacia adelante una palabra | | `ctrl+d` | Eliminar carácter debajo del cursor | | `ctrl+k` | Borrar hasta el final de la línea | | `ctrl+u` | Borrar al inicio de la línea | | `ctrl+w` | Borrar palabra anterior | | `alt+d` | Borrar la siguiente palabra | | `ctrl+t` | Transponer caracteres | | `ctrl+g` | Cancelar ventanas emergentes/abortar la respuesta en ejecución | * * * [Mayús+Entrar](https://opencode.ai/docs/es/keybinds#may%C3%BAsentrar) ---------------------------------------------------------------------- Algunos terminales no envían teclas modificadoras con Enter de forma predeterminada. Es posible que necesite configurar su terminal para enviar `Shift+Enter` como secuencia de escape. ### [Windows Terminal](https://opencode.ai/docs/es/keybinds#windows-terminal) Abra su `settings.json` en: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Agregue esto a la matriz `actions` de nivel raíz: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Agregue esto a la matriz `keybindings` de nivel raíz:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Guarde el archivo y reinicie Windows Terminal o abra una nueva pestaña. --- # TUI | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/tui#_top) TUI === Usa l'interfaccia utente da terminale (TUI) di OpenCode. OpenCode fornisce un’interfaccia interattiva da terminale (TUI) per lavorare sui tuoi progetti con un LLM. Eseguire OpenCode avvia la TUI per la directory corrente. opencode Oppure puoi avviarla per una specifica working directory. opencode /path/to/project Una volta nella TUI, puoi inviare un messaggio come prompt. Give me a quick summary of the codebase. * * * [Riferimenti ai file](https://opencode.ai/docs/it/tui#riferimenti-ai-file) --------------------------------------------------------------------------- Puoi riferirti ai file nei messaggi usando `@`. Questo esegue una ricerca fuzzy dei file nella working directory corrente. How is auth handled in @packages/functions/src/api/index.ts? Il contenuto del file viene aggiunto automaticamente alla conversazione. * * * [Comandi bash](https://opencode.ai/docs/it/tui#comandi-bash) ------------------------------------------------------------- Inizia un messaggio con `!` per eseguire un comando shell. !ls -la L’output del comando viene aggiunto alla conversazione come risultato di uno strumento. * * * [Comandi](https://opencode.ai/docs/it/tui#comandi) --------------------------------------------------- Quando usi la TUI di OpenCode, puoi digitare `/` seguito dal nome di un comando per eseguire rapidamente azioni. Per esempio: /help Molti comandi hanno anche una scorciatoia da tastiera che usa `ctrl+x` come tasto leader (predefinito). [Scopri di più](https://opencode.ai/docs/keybinds) . Ecco tutti i comandi slash disponibili: * * * ### [connetti](https://opencode.ai/docs/it/tui#connetti) Aggiunge un provider a OpenCode. Ti permette di selezionare tra i provider disponibili e aggiungere le relative chiavi API. /connect * * * ### [compatta](https://opencode.ai/docs/it/tui#compatta) Compatta la sessione corrente. _Alias_: `/summarize` /compact **Scorciatoia:** `ctrl+x c` * * * ### [dettagli](https://opencode.ai/docs/it/tui#dettagli) Attiva/disattiva i dettagli di esecuzione degli strumenti. /details **Scorciatoia:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/it/tui#editor) Apre un editor esterno per comporre messaggi. Usa l’editor impostato nella variabile d’ambiente `EDITOR`. [Scopri di più](https://opencode.ai/docs/it/tui#editor-setup) . /editor **Scorciatoia:** `ctrl+x e` * * * ### [esci](https://opencode.ai/docs/it/tui#esci) Esce da OpenCode. _Alias_: `/quit`, `/q` /exit **Scorciatoia:** `ctrl+x q` * * * ### [esporta](https://opencode.ai/docs/it/tui#esporta) Esporta la conversazione corrente in Markdown e la apre nell’editor predefinito. Usa l’editor impostato nella variabile d’ambiente `EDITOR`. [Scopri di più](https://opencode.ai/docs/it/tui#editor-setup) . /export **Scorciatoia:** `ctrl+x x` * * * ### [aiuto](https://opencode.ai/docs/it/tui#aiuto) Mostra la finestra di aiuto. /help **Scorciatoia:** `ctrl+x h` * * * ### [inizializza](https://opencode.ai/docs/it/tui#inizializza) Crea o aggiorna il file `AGENTS.md`. [Scopri di più](https://opencode.ai/docs/rules) . /init **Scorciatoia:** `ctrl+x i` * * * ### [modelli](https://opencode.ai/docs/it/tui#modelli) Elenca i modelli disponibili. /models **Scorciatoia:** `ctrl+x m` * * * ### [nuovo](https://opencode.ai/docs/it/tui#nuovo) Avvia una nuova sessione. _Alias_: `/clear` /new **Scorciatoia:** `ctrl+x n` * * * ### [rifai](https://opencode.ai/docs/it/tui#rifai) Rifai un messaggio precedentemente annullato. Disponibile solo dopo aver usato `/undo`. Internamente usa Git per gestire le modifiche ai file. Quindi il progetto **deve essere un repository Git**. /redo **Scorciatoia:** `ctrl+x r` * * * ### [sessioni](https://opencode.ai/docs/it/tui#sessioni) Elenca e passa tra le sessioni. _Alias_: `/resume`, `/continue` /sessions **Scorciatoia:** `ctrl+x l` * * * ### [condividi](https://opencode.ai/docs/it/tui#condividi) Condivide la sessione corrente. [Scopri di più](https://opencode.ai/docs/share) . /share **Scorciatoia:** `ctrl+x s` * * * ### [temi](https://opencode.ai/docs/it/tui#temi) Elenca i temi disponibili. /themes **Scorciatoia:** `ctrl+x t` * * * ### [ragionamento](https://opencode.ai/docs/it/tui#ragionamento) Attiva/disattiva la visibilità dei blocchi thinking/reasoning nella conversazione. Quando abilitato, puoi vedere il ragionamento del modello per i modelli che supportano extended thinking. /thinking * * * ### [annulla](https://opencode.ai/docs/it/tui#annulla) Annulla l’ultimo messaggio nella conversazione. Rimuove l’ultimo messaggio utente, tutte le risposte successive e qualsiasi modifica ai file. Internamente usa Git per gestire le modifiche ai file. Quindi il progetto **deve essere un repository Git**. /undo **Scorciatoia:** `ctrl+x u` * * * ### [annulla condivisione](https://opencode.ai/docs/it/tui#annulla-condivisione) Annulla la condivisione della sessione corrente. [Scopri di più](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Configurazione dell’editor](https://opencode.ai/docs/it/tui#configurazione-delleditor) ---------------------------------------------------------------------------------------- Sia `/editor` sia `/export` usano l’editor specificato nella variabile d’ambiente `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/it/tui#tab-panel-53) * [Windows (CMD)](https://opencode.ai/docs/it/tui#tab-panel-54) * [Windows (PowerShell)](https://opencode.ai/docs/it/tui#tab-panel-55) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" Per renderlo permanente, aggiungilo al profilo della shell; `~/.bashrc`, `~/.zshrc`, ecc. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait Per renderlo permanente, usa **System Properties** > **Environment Variables**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" Per renderlo permanente, aggiungilo al profilo PowerShell. Opzioni comuni per l’editor includono: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim editor * `vim` - Vim editor * `nano` - Nano editor * `notepad` - Windows Notepad * `subl` - Sublime Text Alcuni editor richiedono argomenti da riga di comando per funzionare in modalità bloccante. Il flag `--wait` fa sì che il processo dell’editor resti in attesa finché non viene chiuso. * * * [Configurazione](https://opencode.ai/docs/it/tui#configurazione) ----------------------------------------------------------------- Puoi personalizzare il comportamento della TUI tramite `tui.json` (o `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Questo è separato da `opencode.json`, che configura il comportamento di server/runtime. ### [Opzioni](https://opencode.ai/docs/it/tui#opzioni) * `theme` - Imposta il tema della UI. [Scopri di più](https://opencode.ai/docs/themes) . * `keybinds` - Personalizza le scorciatoie da tastiera. [Scopri di più](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Abilita l’accelerazione di scroll in stile macOS per uno scorrimento fluido e naturale. Quando abilitata, la velocità aumenta con gesture rapide e resta precisa con movimenti lenti. **Questa impostazione ha precedenza su `scroll_speed` e lo sovrascrive quando attiva.** * `scroll_speed` - Controlla la velocità di scorrimento della TUI quando usi i comandi di scroll (minimo: `0.001`, supporta valori decimali). Default: `3`. **Nota: viene ignorata se `scroll_acceleration.enabled` è impostato a `true`.** * `diff_style` - Controlla il rendering delle diff. `"auto"` si adatta alla larghezza del terminale, `"stacked"` mostra sempre un layout a colonna singola. Usa `OPENCODE_TUI_CONFIG` per caricare un path di configurazione TUI personalizzato. * * * [Personalizzazione](https://opencode.ai/docs/it/tui#personalizzazione) ----------------------------------------------------------------------- Puoi personalizzare vari aspetti della vista TUI usando la palette dei comandi (`ctrl+x h` o `/help`). Queste impostazioni persistono tra i riavvii. * * * #### [Visualizzazione nome utente](https://opencode.ai/docs/it/tui#visualizzazione-nome-utente) Attiva/disattiva se lo username appare nei messaggi della chat. Puoi farlo da: * Palette comandi: cerca “username” o “hide username” * L’impostazione viene salvata automaticamente e ricordata tra le sessioni TUI --- # Strumenti personalizzati | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/custom-tools#_top) Strumenti personalizzati ======================== Crea strumenti che l'LLM puo chiamare in opencode. Gli strumenti personalizzati sono funzioni che crei e che l’LLM puo chiamare durante le conversazioni. Funzionano insieme agli [strumenti integrati](https://opencode.ai/docs/tools) di opencode come `read`, `write` e `bash`. * * * [Creazione di uno strumento](https://opencode.ai/docs/it/custom-tools#creazione-di-uno-strumento) -------------------------------------------------------------------------------------------------- Gli strumenti sono definiti come file **TypeScript** o **JavaScript**. Tuttavia, la definizione dello strumento puo invocare script scritti in **qualsiasi linguaggio**: TypeScript o JavaScript vengono usati solo per la definizione in se. * * * ### [Posizione](https://opencode.ai/docs/it/custom-tools#posizione) Possono essere definiti: * In locale, mettendoli nella directory `.opencode/tools/` del progetto. * Oppure in globale, mettendoli in `~/.config/opencode/tools/`. * * * ### [Struttura](https://opencode.ai/docs/it/custom-tools#struttura) Il modo piu semplice per creare strumenti e usare l’helper `tool()` che fornisce type-safety e validazione. 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}` },}) Il **nome del file** diventa il **nome dello strumento**. L’esempio sopra crea lo strumento `database`. * * * #### [Strumenti multipli per file](https://opencode.ai/docs/it/custom-tools#strumenti-multipli-per-file) Puoi anche esportare piu strumenti da un singolo file. Ogni export diventa **uno strumento separato** con nome **`_`**: 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 },}) 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 },}) Questo crea due strumenti: `math_add` e `math_multiply`. * * * #### [Collisioni di nomi con strumenti integrati](https://opencode.ai/docs/it/custom-tools#collisioni-di-nomi-con-strumenti-integrati) Gli strumenti personalizzati sono indicizzati per nome. Se uno strumento personalizzato usa lo stesso nome di uno strumento integrato, quello personalizzato ha la precedenza. Per esempio, questo file sostituisce lo strumento `bash` integrato: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Argomenti](https://opencode.ai/docs/it/custom-tools#argomenti) Puoi usare `tool.schema`, che e semplicemente [Zod](https://zod.dev/) , per definire i tipi degli argomenti. args: { query: tool.schema.string().describe("SQL query to execute")} Puoi anche importare [Zod](https://zod.dev/) direttamente e restituire un oggetto semplice: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Contesto](https://opencode.ai/docs/it/custom-tools#contesto) Gli strumenti ricevono un contesto sulla sessione corrente: 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}` },}) Usa `context.directory` per la working directory della sessione. Usa `context.worktree` per la root del worktree git. * * * [Esempi](https://opencode.ai/docs/it/custom-tools#esempi) ---------------------------------------------------------- ### [Scrivere uno strumento in Python](https://opencode.ai/docs/it/custom-tools#scrivere-uno-strumento-in-python) Puoi scrivere gli strumenti in qualunque linguaggio. Ecco un esempio che somma due numeri usando Python. Per prima cosa, crea lo strumento come script Python: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Poi crea la definizione dello strumento che lo invoca: 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() },}) Qui usiamo l’utility [`Bun.$`](https://bun.com/docs/runtime/shell) per eseguire lo script Python. --- # Narzędzia specjalistyczne | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/custom-tools#_top) Narzędzia specjalistyczne ========================= Twórz narzędzi, które LLM mogą być uruchamiane w otwartym kodzie. Narzędzia specjalistyczne to funkcje, które tworzysz i które LLM może wywoływać podczas rozmów. Współpracują one z [wbudowanymi narzędziami](https://opencode.ai/docs/tools) opencode, takimi jak `read`, `write` i `bash`. * * * [Tworzenie narzędzia](https://opencode.ai/docs/pl/custom-tools#tworzenie-narz%C4%99dzia) ----------------------------------------------------------------------------------------- Narzędzia tworzą pliki **TypeScript** lub **JavaScript**. Definicja narzędzia może być odwoływana do skryptów napisanych w **dowolnym języku** — TypeScript lub JavaScript są używane tylko w tym samym narzędziu. * * * ### [Lokalizacja](https://opencode.ai/docs/pl/custom-tools#lokalizacja) Można je uruchomić: * Lokalnie, umieszczając je w katalogu `.opencode/tools/` swojego projektu. * Lub globalnie, umieszczając je w `~/.config/opencode/tools/`. * * * ### [Struktura](https://opencode.ai/docs/pl/custom-tools#struktura) Najłatwiejszym sposobem tworzenia narzędzia jest pomocnika `tool()`, który zapewnia bezpieczeństwo i sprawdzanie poprawności. 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}` },}) **Nazwa pliku** staje się **nazwą narzędzia**. Pierwotne narzędzie `database`. * * * #### [Wiele narzędzi na plik](https://opencode.ai/docs/pl/custom-tools#wiele-narz%C4%99dzi-na-plik) Można także eksportować wiele narzędzi z jednego pliku. Każdy eksport staje się **oddzielnym językiem** o nazwie **`_`**: 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 },}) 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 },}) Tworzy to dwa narzędzia: `math_add` i `math_multiply`. * * * #### [Kolizje nazw z wbudowanymi narzędziami](https://opencode.ai/docs/pl/custom-tools#kolizje-nazw-z-wbudowanymi-narz%C4%99dziami) Niestandardowe narzędzia są identyfikowane według nazwy narzędzia. Jeśli niestandardowe narzędzie używa tej samej nazwy co wbudowane narzędzie, niestandardowe narzędzie ma pierwszeństwo. Na przykład ten plik zastępuje wbudowane narzędzie `bash`: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Argumenty](https://opencode.ai/docs/pl/custom-tools#argumenty) Do zdefiniowania argumentów można zastosować `tool.schema`, czyli po prostu [Zod](https://zod.dev/) . args: { query: tool.schema.string().describe("SQL query to execute")} Można także bezpośrednio zaimportować [Zod](https://zod.dev/) i zwyczajowo zwykły obiekt: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Kontekst](https://opencode.ai/docs/pl/custom-tools#kontekst) Narzędzia kontekstowe charakterystycznej sesji: 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}` },}) `context.directory` jako katalogowy pracodawczy. `context.worktree` dla katalogu głównego zwalczającego git. * * * [Przykład](https://opencode.ai/docs/pl/custom-tools#przyk%C5%82ad) ------------------------------------------------------------------- ### [Napisz narzędzie w Pythonie](https://opencode.ai/docs/pl/custom-tools#napisz-narz%C4%99dzie-w-pythonie) Możesz pisać swoje narzędzia w dowolnym języku. Oto przykład dodania dwóch liczb przy użyciu języka Python. Najpierw utwórz narzędzie jako skrypt w języku Python: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Następnie utwórz definicję narzędzia, która go wywołuje: 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() },}) Tutaj używamy narzędzia [`Bun.$`](https://bun.com/docs/runtime/shell) do uruchomienia skryptu w języku Python. --- # Egendefinerte verktøy | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/custom-tools#_top) Egendefinerte verktøy ===================== Lag verktøy som LLM kan kalle inn OpenCode. Egendefinerte verktøy er funksjoner du oppretter som LLM kan kalle under samtaler. De fungerer sammen med OpenCode sine [innebygde verktøy](https://opencode.ai/docs/tools) som `read`, `write` og `bash`. * * * [Opprette et verktøy](https://opencode.ai/docs/nb/custom-tools#opprette-et-verkt%C3%B8y) ----------------------------------------------------------------------------------------- Verktøy er definert som **TypeScript**\- eller **JavaScript**\-filer. Verktøydefinisjonen kan imidlertid påkalle skript skrevet på **alle språk** - TypeScript eller JavaScript brukes bare for selve verktøydefinisjonen. * * * ### [Plassering](https://opencode.ai/docs/nb/custom-tools#plassering) De kan defineres: * Lokalt ved å plassere dem i `.opencode/tools/`\-katalogen til prosjektet ditt. * Eller globalt, ved å plassere dem i `~/.config/opencode/tools/`. * * * ### [Struktur](https://opencode.ai/docs/nb/custom-tools#struktur) Den enkleste måten å lage verktøy på er å bruke `tool()`\-hjelperen som gir typesikkerhet og validering. 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}` },}) **filnavnet** blir **verktøynavnet**. Ovennevnte oppretter et `database`\-verktøy. * * * #### [Flere verktøy per fil](https://opencode.ai/docs/nb/custom-tools#flere-verkt%C3%B8y-per-fil) Du kan også eksportere flere verktøy fra en enkelt fil. Hver eksport blir **et separat verktøy** med navnet **`_`**: 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 },}) 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 },}) Dette lager to verktøy: `math_add` og `math_multiply`. * * * #### [Navnekollisjoner med innebygde verktøy](https://opencode.ai/docs/nb/custom-tools#navnekollisjoner-med-innebygde-verkt%C3%B8y) Egendefinerte verktøy er nøklet etter verktøynavn. Hvis et egendefinert verktøy bruker samme navn som et innebygd verktøy, vil det egendefinerte verktøyet ha forrang. For eksempel erstatter denne filen det innebygde `bash`\-verktøyet: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Argumenter](https://opencode.ai/docs/nb/custom-tools#argumenter) Du kan bruke `tool.schema`, som bare er [Zod](https://zod.dev/) , for å definere argumenttyper. args: { query: tool.schema.string().describe("SQL query to execute")} Du kan også importere [Zod](https://zod.dev/) direkte og returnere et vanlig objekt: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Kontekst](https://opencode.ai/docs/nb/custom-tools#kontekst) Verktøy mottar kontekst om gjeldende økt: 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}` },}) Bruk `context.directory` for øktens arbeidskatalog. Bruk `context.worktree` for git-arbeidstreet. * * * [Eksempler](https://opencode.ai/docs/nb/custom-tools#eksempler) ---------------------------------------------------------------- ### [Skrive et verktøy i Python](https://opencode.ai/docs/nb/custom-tools#skrive-et-verkt%C3%B8y-i-python) Du kan skrive verktøyene dine på hvilket som helst språk du vil. Her er et eksempel som legger til to tall ved hjelp av Python. Først lager du verktøyet som et Python-skript: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Lag deretter verktøydefinisjonen som påkaller den: 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() },}) Her bruker vi [`Bun.$`](https://bun.com/docs/runtime/shell) \-verktøyet for å kjøre Python-skriptet. --- # Brugerdefinerede værktøjer | OpenCode [Gå til indhold](https://opencode.ai/docs/da/custom-tools#_top) Brugerdefinerede værktøjer ========================== Opret værktøjer, som LLM kan kalde opencode ind. Brugerdefinerede værktøjer er funktioner, du opretter, som LLM kan kalde under samtaler. De arbejder sammen med opencodes [built-in tools](https://opencode.ai/docs/tools) som `read`, `write` og `bash`. * * * [Oprettelse af et værktøj](https://opencode.ai/docs/da/custom-tools#oprettelse-af-et-v%C3%A6rkt%C3%B8j) -------------------------------------------------------------------------------------------------------- Værktøjer er defineret som **TypeScript**\- eller **JavaScript**\-filer. Værktøjsdefinitionen kan dog kalde scripts skrevet på **alle sprog** - TypeScript eller JavaScript bruges kun til selve værktøjsdefinitionen. * * * ### [Placering](https://opencode.ai/docs/da/custom-tools#placering) De kan definere: * Lokalt ved at placere dem i biblioteket `.opencode/tools/` i dit projekt. * Eller globalt ved at placere dem i `~/.config/opencode/tools/`. * * * ### [Struktur](https://opencode.ai/docs/da/custom-tools#struktur) Den nemmeste måde at oprette værktøjer på er at bruge `tool()`\-hjælperen, som giver typesikkerhed og validering. 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}` },}) **filnavnet** bliver **værktøjsnavnet**. Ovenstående opretter et `database` værktøj. * * * #### [Flere værktøjer pr. fil](https://opencode.ai/docs/da/custom-tools#flere-v%C3%A6rkt%C3%B8jer-pr-fil) Du kan også eksportere flere værktøjer fra en enkelt fil. Hver eksport bliver **et separat værktøj** med navnet **`_`**: 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 },}) 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 },}) Dette skaber værktøjer: `math_add` og `math_multiply`. * * * #### [Navnekollisioner med indbyggede værktøjer](https://opencode.ai/docs/da/custom-tools#navnekollisioner-med-indbyggede-v%C3%A6rkt%C3%B8jer) Brugerdefinerede værktøjer er identificeret ved værktøjsnavn. Hvis et brugerdefineret værktøj bruger samme navn som et indbygget værktøj, har det brugerdefinerede værktøj forrang. For eksempel erstatter denne fil det indbyggede `bash` værktøj: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [Argumenter](https://opencode.ai/docs/da/custom-tools#argumenter) Du kan bruge `tool.schema`, som kun er [Zod](https://zod.dev/) , til at definere argumenttyper. args: { query: tool.schema.string().describe("SQL query to execute")} Du kan også importere [Zod](https://zod.dev/) direkte og returnere et almindeligt objekt: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [Kontekst](https://opencode.ai/docs/da/custom-tools#kontekst) Værktøjer modtager kontekst om den aktuelle session: 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}` },}) Brug `context.directory` til sessionens arbejdsmappe. Brug `context.worktree` til git-arbejdstræets rod. * * * [Eksempler](https://opencode.ai/docs/da/custom-tools#eksempler) ---------------------------------------------------------------- ### [Skriv et værktøj i Python](https://opencode.ai/docs/da/custom-tools#skriv-et-v%C3%A6rkt%C3%B8j-i-python) Du kan skrive dine værktøjer på et hvilket som helst sprog, du ønsker. Her er et eksempel, der tilføjer til tal ved hjælp af Python. Først skal du oprette værktøjet som et Python-script: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) Opret derefter værktøjsdefinitionen, der kalder den: 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() },}) Her bruger vi [`Bun.$`](https://bun.com/docs/runtime/shell) \-værktøjet til at køre Python-scriptet. --- # الأدوات المخصصة | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/custom-tools#_top) الأدوات المخصصة =============== أنشئ أدوات يمكن لـ LLM استدعاؤها في opencode. الأدوات المخصصة هي دوال تنشئها يمكن لـ LLM استدعاؤها أثناء المحادثات. تعمل جنبا إلى جنب مع [الأدوات المدمجة](https://opencode.ai/docs/tools) في opencode مثل `read` و`write` و`bash`. * * * [إنشاء أداة](https://opencode.ai/docs/ar/custom-tools#%D8%A5%D9%86%D8%B4%D8%A7%D8%A1-%D8%A3%D8%AF%D8%A7%D8%A9) --------------------------------------------------------------------------------------------------------------- تُعرّف الأدوات كملفات **TypeScript** أو **JavaScript**. لكن تعريف الأداة يمكنه استدعاء سكربتات مكتوبة **بأي لغة** — إذ تُستخدم TypeScript أو JavaScript فقط لتعريف الأداة نفسه. * * * ### [الموقع](https://opencode.ai/docs/ar/custom-tools#%D8%A7%D9%84%D9%85%D9%88%D9%82%D8%B9) يمكن تعريفها: * محليا بوضعها في مجلد `.opencode/tools/` داخل مشروعك. * أو عالميا بوضعها في `~/.config/opencode/tools/`. * * * ### [البنية](https://opencode.ai/docs/ar/custom-tools#%D8%A7%D9%84%D8%A8%D9%86%D9%8A%D8%A9) أسهل طريقة لإنشاء أدوات هي استخدام المساعد `tool()` الذي يوفر أمان الأنواع والتحقق. 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}` },}) يصبح **اسم الملف** هو **اسم الأداة**. المثال أعلاه ينشئ أداة باسم `database`. * * * #### [عدة أدوات في ملف واحد](https://opencode.ai/docs/ar/custom-tools#%D8%B9%D8%AF%D8%A9-%D8%A3%D8%AF%D9%88%D8%A7%D8%AA-%D9%81%D9%8A-%D9%85%D9%84%D9%81-%D9%88%D8%A7%D8%AD%D8%AF) يمكنك أيضا تصدير عدة أدوات من ملف واحد. يصبح كل تصدير **أداة مستقلة** باسم **`_`**: 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 },}) 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 },}) ينشئ هذا أداتين: `math_add` و`math_multiply`. * * * #### [تضارب الأسماء مع الأدوات المدمجة](https://opencode.ai/docs/ar/custom-tools#%D8%AA%D8%B6%D8%A7%D8%B1%D8%A8-%D8%A7%D9%84%D8%A3%D8%B3%D9%85%D8%A7%D8%A1-%D9%85%D8%B9-%D8%A7%D9%84%D8%A3%D8%AF%D9%88%D8%A7%D8%AA-%D8%A7%D9%84%D9%85%D8%AF%D9%85%D8%AC%D8%A9) تُصنّف الأدوات المخصصة حسب اسم الأداة. إذا استخدمت أداة مخصصة نفس اسم أداة مدمجة، فإن الأداة المخصصة تأخذ الأولوية. على سبيل المثال، يستبدل هذا الملف أداة `bash` المدمجة: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [الوسائط](https://opencode.ai/docs/ar/custom-tools#%D8%A7%D9%84%D9%88%D8%B3%D8%A7%D8%A6%D8%B7) يمكنك استخدام `tool.schema`، وهو في الأساس [Zod](https://zod.dev/) ، لتعريف أنواع الوسائط. args: { query: tool.schema.string().describe("SQL query to execute")} يمكنك أيضا استيراد [Zod](https://zod.dev/) مباشرة وإرجاع كائن عادي: import { z } from "zod" export default { description: "Tool description", args: { param: z.string().describe("Parameter description"), }, async execute(args, context) { // Tool implementation return "result" },} * * * ### [السياق](https://opencode.ai/docs/ar/custom-tools#%D8%A7%D9%84%D8%B3%D9%8A%D8%A7%D9%82) تستقبل الأدوات سياقا حول الجلسة الحالية: 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}` },}) استخدم `context.directory` لدليل العمل الخاص بالجلسة. استخدم `context.worktree` لجذر شجرة العمل (worktree) في git. * * * [أمثلة](https://opencode.ai/docs/ar/custom-tools#%D8%A3%D9%85%D8%AB%D9%84%D8%A9) --------------------------------------------------------------------------------- ### [كتابة أداة بلغة Python](https://opencode.ai/docs/ar/custom-tools#%D9%83%D8%AA%D8%A7%D8%A8%D8%A9-%D8%A3%D8%AF%D8%A7%D8%A9-%D8%A8%D9%84%D8%BA%D8%A9-python) يمكنك كتابة أدواتك بأي لغة تريدها. إليك مثالا يجمع رقمين باستخدام Python. أولا، أنشئ الأداة كسكربت Python: import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) ثم أنشئ تعريف الأداة الذي يستدعيه: 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() },}) هنا نستخدم أداة [`Bun.$`](https://bun.com/docs/runtime/shell) لتشغيل سكربت Python. --- # Feilsøking | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/troubleshooting#_top) Feilsøking ========== Vanlige problemer og hvordan de kan løses. For å feilsøke problemer med OpenCode, start med å sjekke loggene og lokale data den lagrer på disken. * * * [Logger](https://opencode.ai/docs/nb/troubleshooting#logger) ------------------------------------------------------------- Loggfiler skrives til: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.local\share\opencode\log` Loggfiler navngis med tidsstempler (f.eks. `2025-01-09T123456.log`) og de siste 10 loggfilene beholdes. Du kan angi loggnivået med kommandolinjealternativet `--log-level` for å få mer detaljert feilsøkingsinformasjon. For eksempel `opencode --log-level DEBUG`. * * * [Lagring](https://opencode.ai/docs/nb/troubleshooting#lagring) --------------------------------------------------------------- OpenCode lagrer øktdata og andre applikasjonsdata på disken på: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.local\share\opencode` Denne katalogen inneholder: * `auth.json` - Autentiseringsdata som API-nøkler, OAuth-tokens * `log/` - Applikasjonslogger * `project/` - Prosjektspesifikke data som økt- og meldingsdata * Hvis prosjektet er innenfor en Git-repo, lagres det i `.//storage/` * Hvis det ikke er en Git-repo, lagres det i `./global/storage/` * * * [Skrivebordsapp](https://opencode.ai/docs/nb/troubleshooting#skrivebordsapp) ----------------------------------------------------------------------------- OpenCode Desktop kjører en lokal OpenCode-server (`opencode-cli` sidevognen) i bakgrunnen. De fleste problemene er forårsaket av en plugin som fungerer dårlig, en ødelagt cache eller en dårlig serverinnstilling. ### [Raske sjekker](https://opencode.ai/docs/nb/troubleshooting#raske-sjekker) * Avslutt og start appen på nytt. * Hvis appen viser en feilskjerm, klikker du på **Start på nytt** og kopierer feildetaljene. * Bare macOS: `OpenCode`\-meny -> **Last nettvisning på nytt** (hjelper hvis UI er tom/frosset). * * * ### [Deaktiver plugins](https://opencode.ai/docs/nb/troubleshooting#deaktiver-plugins) Hvis skrivebordsappen krasjer ved oppstart, henger eller oppfører seg merkelig, start med å deaktivere plugins. #### [Sjekk den globale konfigurasjonen](https://opencode.ai/docs/nb/troubleshooting#sjekk-den-globale-konfigurasjonen) Åpne den globale konfigurasjonsfilen og se etter en `plugin`\-nøkkel. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (eller `~/.config/opencode/opencode.json`) * **macOS/Linux** (eldre installasjoner): `~/.local/share/opencode/opencode.jsonc` * **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.config\opencode\opencode.jsonc` Hvis du har konfigurert plugins, deaktiver dem midlertidig ved å fjerne nøkkelen eller sette den til en tom matrise: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Sjekk plugin-kataloger](https://opencode.ai/docs/nb/troubleshooting#sjekk-plugin-kataloger) OpenCode kan også laste lokale plugins fra disken. Flytt disse midlertidig ut av veien (eller gi nytt navn til mappen) og start skrivebordsappen på nytt: * **Globale plugins** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.config\opencode\plugins` * **Prosjektplugins** (bare hvis du bruker konfigurasjon per prosjekt) * `/.opencode/plugins/` Hvis appen begynner å fungere igjen, aktiverer du plugins én om gangen for å finne ut hvilken som forårsaker problemet. * * * ### [Tøm hurtigbufferen](https://opencode.ai/docs/nb/troubleshooting#t%C3%B8m-hurtigbufferen) Hvis deaktivering av plugins ikke hjelper (eller en plugin-installasjon sitter fast), tøm hurtigbufferen slik at OpenCode kan gjenoppbygge den. 1. Avslutt OpenCode Desktop helt. 2. Slett hurtigbufferkatalogen: * **macOS**: Finder -> `Cmd+Shift+G` -> lim inn `~/.cache/opencode` * **Linux**: slett `~/.cache/opencode` (eller kjør `rm -rf ~/.cache/opencode`) * **Windows**: Trykk `WIN+R` og lim inn `%USERPROFILE%\.cache\opencode` 3. Start OpenCode Desktop på nytt. * * * ### [Løs problemer med servertilkobling](https://opencode.ai/docs/nb/troubleshooting#l%C3%B8s-problemer-med-servertilkobling) OpenCode Desktop kan enten starte sin egen lokale server (standard) eller koble til en server URL du har konfigurert. Hvis du ser en **“Tilkobling mislyktes”**\-dialogboks (eller appen kommer aldri forbi splash-skjermen), se etter en tilpasset server URL. #### [Slett skrivebordsappens standardserver-URL](https://opencode.ai/docs/nb/troubleshooting#slett-skrivebordsappens-standardserver-url) Fra startskjermen klikker du på servernavnet (med statusprikken) for å åpne servervelgeren. I delen **Standardserver** klikker du på **Slett**. #### [Fjern `server.port` / `server.hostname` fra konfigurasjonen din](https://opencode.ai/docs/nb/troubleshooting#fjern-serverport--serverhostname-fra-konfigurasjonen-din) Hvis `opencode.json(c)` inneholder en `server`\-del, fjern den midlertidig og start skrivebordsappen på nytt. #### [Sjekk miljøvariabler](https://opencode.ai/docs/nb/troubleshooting#sjekk-milj%C3%B8variabler) Hvis du har `OPENCODE_PORT` satt i miljøet ditt, vil skrivebordsappen prøve å bruke den porten for den lokale serveren. * Deaktiver `OPENCODE_PORT` (eller velg en ledig port) og start på nytt. * * * ### [Linux: Wayland / X11 problemer](https://opencode.ai/docs/nb/troubleshooting#linux-wayland--x11-problemer) På Linux kan noen Wayland-oppsett forårsake tomme vinduer eller kompositorfeil. * Hvis du er på Wayland og appen er tom/krasj, prøv å starte med `OC_ALLOW_WAYLAND=1`. * Hvis det gjør ting verre, fjern det og prøv å starte under en X11-økt i stedet. * * * ### [Windows: WebView2 kjøretid](https://opencode.ai/docs/nb/troubleshooting#windows-webview2-kj%C3%B8retid) På Windows krever OpenCode Desktop Microsoft Edge **WebView2 Runtime**. Hvis appen åpnes i et tomt vindu eller ikke starter, installer/oppdater WebView2 og prøv igjen. * * * ### [Windows: Generelle ytelsesproblemer](https://opencode.ai/docs/nb/troubleshooting#windows-generelle-ytelsesproblemer) Hvis du opplever treg ytelse, problemer med filtilgang eller terminalproblemer på Windows, kan du prøve å bruke [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) . WSL gir et Linux-miljø som fungerer mer sømløst med funksjonene til OpenCode. * * * ### [Varsler vises ikke](https://opencode.ai/docs/nb/troubleshooting#varsler-vises-ikke) OpenCode Desktop viser bare systemvarsler når: * varsler er aktivert for OpenCode i OS-innstillingene dine, og * appvinduet er ikke fokusert. * * * ### [Tilbakestill skrivebordsapplagring (siste utvei)](https://opencode.ai/docs/nb/troubleshooting#tilbakestill-skrivebordsapplagring-siste-utvei) Hvis appen ikke starter og du ikke kan slette innstillingene fra UI-et, tilbakestill skrivebordsappens lagrede tilstand. 1. Avslutt OpenCode Desktop. 2. Finn og slett disse filene (de finnes i OpenCode Desktop-appens datakatalog): * `opencode.settings.dat` (stasjonær standardserver URL) * `opencode.global.dat` og `opencode.workspace.*.dat` (UI tilstand som nylige servere/prosjekter) * * * ### [Modellen er ikke tilgjengelig](https://opencode.ai/docs/nb/troubleshooting#modellen-er-ikke-tilgjengelig) 1. Sjekk at du har autentisert deg med leverandøren 2. Kontroller at modellnavnet i konfigurasjonen er riktig 3. Noen modeller kan kreve spesifikk tilgang eller abonnement Hvis du støter på `ProviderModelNotFoundError` refererer du mest sannsynlig feil til en modell et sted. Modeller skal refereres slik: `/` * * * ### [AI\_APICallError og leverandørpakkeproblemer](https://opencode.ai/docs/nb/troubleshooting#ai_apicallerror-og-leverand%C3%B8rpakkeproblemer) Hvis du støter på API-anropsfeil, kan dette skyldes utdaterte provider-pakker. OpenCode installerer dynamisk provider-pakker (OpenAI, Anthropic, Google, etc.) etter behov og cacher dem lokalt. For å løse problemer med leverandørpakke: 1. Tøm leverandørens pakkebuffer: rm -rf ~/.cache/opencode På Windows, trykk `WIN+R` og slett: `%USERPROFILE%\.cache\opencode` 2. Start OpenCode på nytt for å installere de nyeste provider-pakkene på nytt Dette vil tvinge OpenCode til å laste ned de nyeste versjonene av provider-pakkene, som ofte løser kompatibilitetsproblemer med modellparametere og API-endringer. * * * ### [Kopier/lim inn fungerer ikke på Linux](https://opencode.ai/docs/nb/troubleshooting#kopierlim-inn-fungerer-ikke-p%C3%A5-linux) Linux-brukere må ha ett av følgende utklippstavle-verktøy installert for at kopier/lim inn-funksjonalitet skal fungere: **For X11-systemer:** apt install -y xclip# orapt install -y xsel **For Wayland-systemer:** apt install -y wl-clipboard **For headless-miljøer:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 OpenCode vil oppdage om du bruker Wayland og foretrekker `wl-clipboard`, ellers vil den prøve å finne utklippstavle-verktøy i rekkefølgen: `xclip` og `xsel`. --- # 快捷键 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/keybinds#_top) 快捷键 === 自定义您的快捷键。 OpenCode 提供了一系列快捷键,您可以通过 `tui.json` 进行自定义。 { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [前导键](https://opencode.ai/docs/zh-cn/keybinds#%E5%89%8D%E5%AF%BC%E9%94%AE) --------------------------------------------------------------------------- OpenCode 的大多数快捷键使用 `leader`(前导键)。这可以避免与终端中的其他快捷键冲突。 默认情况下,`ctrl+x` 是前导键,大多数操作需要您先按下前导键,然后再按对应的快捷键。例如,要新建一个会话,请先按 `ctrl+x`,然后按 `n`。 您不一定需要使用前导键来设置快捷键,但我们建议您这样做。 * * * [禁用快捷键](https://opencode.ai/docs/zh-cn/keybinds#%E7%A6%81%E7%94%A8%E5%BF%AB%E6%8D%B7%E9%94%AE) ----------------------------------------------------------------------------------------------- 您可以通过将键值添加到 `tui.json` 并设置为 “none” 来禁用某个快捷键。 { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [桌面版提示词输入快捷键](https://opencode.ai/docs/zh-cn/keybinds#%E6%A1%8C%E9%9D%A2%E7%89%88%E6%8F%90%E7%A4%BA%E8%AF%8D%E8%BE%93%E5%85%A5%E5%BF%AB%E6%8D%B7%E9%94%AE) ----------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode 桌面应用的提示词输入框支持常见的 Readline/Emacs 风格文本编辑快捷键。这些快捷键为内置功能,目前无法通过 `opencode.json` 进行配置。 | 快捷键 | 操作 | | --- | --- | | `ctrl+a` | 移动到当前行的开头 | | `ctrl+e` | 移动到当前行的末尾 | | `ctrl+b` | 光标向后移动一个字符 | | `ctrl+f` | 光标向前移动一个字符 | | `alt+b` | 光标向后移动一个单词 | | `alt+f` | 光标向前移动一个单词 | | `ctrl+d` | 删除光标所在位置的字符 | | `ctrl+k` | 删除从光标到行尾的内容 | | `ctrl+u` | 删除从光标到行首的内容 | | `ctrl+w` | 删除前一个单词 | | `alt+d` | 删除后一个单词 | | `ctrl+t` | 交换光标前后的字符 | | `ctrl+g` | 取消弹出窗口 / 中止正在运行的响应 | * * * [Shift+Enter](https://opencode.ai/docs/zh-cn/keybinds#shiftenter) ------------------------------------------------------------------ 某些终端默认不会发送带修饰键的 Enter 键。您可能需要配置终端将 `Shift+Enter` 作为转义序列发送。 ### [Windows Terminal](https://opencode.ai/docs/zh-cn/keybinds#windows-terminal) 打开您的 `settings.json` 文件,路径为: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json 将以下内容添加到根级 `actions` 数组中: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ 将以下内容添加到根级 `keybindings` 数组中:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ 保存文件并重启 Windows Terminal,或打开一个新标签页。 --- # TUI | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/tui#_top) TUI === 使用 OpenCode 终端用户界面。 OpenCode 提供了一个交互式终端界面(TUI),用于配合 LLM 处理您的项目。 运行 OpenCode 即可启动当前目录的 TUI。 opencode 或者您可以为指定的工作目录启动它。 opencode /path/to/project 进入 TUI 后,您可以输入消息进行提示。 Give me a quick summary of the codebase. * * * [文件引用](https://opencode.ai/docs/zh-cn/tui#%E6%96%87%E4%BB%B6%E5%BC%95%E7%94%A8) -------------------------------------------------------------------------------- 您可以使用 `@` 在消息中引用文件。这会在当前工作目录中进行模糊文件搜索。 How is auth handled in @packages/functions/src/api/index.ts? 文件的内容会自动添加到对话中。 * * * [Bash 命令](https://opencode.ai/docs/zh-cn/tui#bash-%E5%91%BD%E4%BB%A4) ---------------------------------------------------------------------- 以 `!` 开头的消息会作为 shell 命令执行。 !ls -la 命令的输出会作为工具结果添加到对话中。 * * * [命令](https://opencode.ai/docs/zh-cn/tui#%E5%91%BD%E4%BB%A4) ------------------------------------------------------------ 使用 OpenCode TUI 时,您可以输入 `/` 后跟命令名称来快速执行操作。例如: /help 大多数命令还支持以 `ctrl+x` 作为前导键的快捷键,其中 `ctrl+x` 是默认前导键。[了解更多](https://opencode.ai/docs/keybinds) 。 以下是所有可用的斜杠命令: * * * ### [connect](https://opencode.ai/docs/zh-cn/tui#connect) 将提供商添加到 OpenCode。允许您从可用的提供商中选择并添加其 API 密钥。 /connect * * * ### [compact](https://opencode.ai/docs/zh-cn/tui#compact) 压缩当前会话。_别名_:`/summarize` /compact **快捷键:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/zh-cn/tui#details) 切换工具执行详情的显示。 /details **快捷键:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/zh-cn/tui#editor) 打开外部编辑器来编写消息。使用 `EDITOR` 环境变量中设置的编辑器。[了解更多](https://opencode.ai/docs/zh-cn/tui#editor-setup) 。 /editor **快捷键:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/zh-cn/tui#exit) 退出 OpenCode。_别名_:`/quit`、`/q` /exit **快捷键:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/zh-cn/tui#export) 将当前对话导出为 Markdown 并在默认编辑器中打开。使用 `EDITOR` 环境变量中设置的编辑器。[了解更多](https://opencode.ai/docs/zh-cn/tui#editor-setup) 。 /export **快捷键:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/zh-cn/tui#help) 显示帮助对话框。 /help **快捷键:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/zh-cn/tui#init) 创建或更新 `AGENTS.md` 文件。[了解更多](https://opencode.ai/docs/rules) 。 /init **快捷键:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/zh-cn/tui#models) 列出可用模型。 /models **快捷键:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/zh-cn/tui#new) 开始新的会话。_别名_:`/clear` /new **快捷键:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/zh-cn/tui#redo) 重做之前撤销的消息。仅在使用 `/undo` 后可用。 在内部,这使用 Git 来管理文件更改。因此您的项目**需要是一个 Git 仓库**。 /redo **快捷键:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/zh-cn/tui#sessions) 列出会话并在会话之间切换。_别名_:`/resume`、`/continue` /sessions **快捷键:** `ctrl+x l` * * * 分享当前会话。[了解更多](https://opencode.ai/docs/share) 。 /share **快捷键:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/zh-cn/tui#themes) 列出可用主题。 /themes **快捷键:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/zh-cn/tui#thinking) 切换对话中思考/推理块的可见性。启用后,您可以看到支持扩展思考的模型的推理过程。 /thinking * * * ### [undo](https://opencode.ai/docs/zh-cn/tui#undo) 撤销对话中的最后一条消息。移除最近的用户消息、所有后续响应以及所有文件更改。 在内部,这使用 Git 来管理文件更改。因此您的项目**需要是一个 Git 仓库**。 /undo **快捷键:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/zh-cn/tui#unshare) 取消分享当前会话。[了解更多](https://opencode.ai/docs/share#un-sharing) 。 /unshare * * * [编辑器设置](https://opencode.ai/docs/zh-cn/tui#%E7%BC%96%E8%BE%91%E5%99%A8%E8%AE%BE%E7%BD%AE) ------------------------------------------------------------------------------------------ `/editor` 和 `/export` 命令都使用 `EDITOR` 环境变量中指定的编辑器。 * [Linux/macOS](https://opencode.ai/docs/zh-cn/tui#tab-panel-116) * [Windows (CMD)](https://opencode.ai/docs/zh-cn/tui#tab-panel-117) * [Windows (PowerShell)](https://opencode.ai/docs/zh-cn/tui#tab-panel-118) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" 要使其永久生效,请将其添加到您的 shell 配置文件中; `~/.bashrc`、`~/.zshrc` 等。 set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait 要使其永久生效,请使用**系统属性** > **环境变量**。 $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" 要使其永久生效,请将其添加到您的 PowerShell 配置文件中。 常用的编辑器选项包括: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim 编辑器 * `vim` - Vim 编辑器 * `nano` - Nano 编辑器 * `notepad` - Notepad(Windows 记事本) * `subl` - Sublime Text 某些编辑器需要命令行参数才能以阻塞模式运行。`--wait` 标志使编辑器进程阻塞直到关闭。 * * * [配置](https://opencode.ai/docs/zh-cn/tui#%E9%85%8D%E7%BD%AE) ------------------------------------------------------------ 您可以通过 OpenCode 配置文件自定义 TUI 行为。 { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true } }} ### [选项](https://opencode.ai/docs/zh-cn/tui#%E9%80%89%E9%A1%B9) * `scroll_acceleration` - 启用 macOS 风格的滚动加速,实现平滑、自然的滚动体验。启用后,快速滚动时速度会增加,慢速移动时保持精确。**此设置优先于 `scroll_speed`,启用时会覆盖它。** * `scroll_speed` - 控制使用滚动命令时 TUI 的滚动速度(最小值:`1`)。默认为 `3`。**注意:如果 `scroll_acceleration.enabled` 设置为 `true`,则此设置会被忽略。** * * * [自定义](https://opencode.ai/docs/zh-cn/tui#%E8%87%AA%E5%AE%9A%E4%B9%89) ---------------------------------------------------------------------- 您可以使用命令面板(`ctrl+x h` 或 `/help`)自定义 TUI 视图的各个方面。这些设置在重启后仍会保留。 * * * #### [用户名显示](https://opencode.ai/docs/zh-cn/tui#%E7%94%A8%E6%88%B7%E5%90%8D%E6%98%BE%E7%A4%BA) 切换您的用户名是否显示在聊天消息中。通过以下方式访问: * 命令面板:搜索 “username” 或 “hide username” * 该设置会自动保存,并在各个 TUI 会话中保持记忆 --- # Solución de problemas | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/troubleshooting#_top) Solución de problemas ===================== Problemas comunes y cómo resolverlos. Para depurar problemas con OpenCode, comience verificando los registros y los datos locales que almacena en el disco. * * * [Registros](https://opencode.ai/docs/es/troubleshooting#registros) ------------------------------------------------------------------- Los archivos de registro se escriben en: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.local\share\opencode\log` Los archivos de registro reciben nombres con marcas de tiempo (por ejemplo, `2025-01-09T123456.log`) y se conservan los 10 archivos de registro más recientes. Puede configurar el nivel de registro con la opción de línea de comandos `--log-level` para obtener información de depuración más detallada. Por ejemplo, `opencode --log-level DEBUG`. * * * [Almacenamiento](https://opencode.ai/docs/es/troubleshooting#almacenamiento) ----------------------------------------------------------------------------- opencode almacena datos de sesión y otros datos de aplicaciones en el disco en: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.local\share\opencode` Este directorio contiene: * `auth.json` - Datos de autenticación como API claves, OAuth tokens * `log/` - Registros de aplicaciones * `project/` - Datos específicos del proyecto, como datos de sesión y mensajes. * Si el proyecto está dentro de un repositorio de Git, se almacena en `.//storage/` * Si no es un repositorio de Git, se almacena en `./global/storage/` * * * [Aplicación de escritorio](https://opencode.ai/docs/es/troubleshooting#aplicaci%C3%B3n-de-escritorio) ------------------------------------------------------------------------------------------------------ OpenCode Desktop ejecuta un servidor OpenCode local (el sidecar `opencode-cli`) en segundo plano. La mayoría de los problemas se deben a un complemento que no funciona correctamente, una memoria caché dañada o una mala configuración del servidor. ### [Comprobaciones rápidas](https://opencode.ai/docs/es/troubleshooting#comprobaciones-r%C3%A1pidas) * Salga por completo y reinicie la aplicación. * Si la aplicación muestra una pantalla de error, haga clic en **Reiniciar** y copie los detalles del error. * Solo macOS: menú `OpenCode` -> **Recargar vista web** (ayuda si la interfaz de usuario está en blanco/congelada). * * * ### [Deshabilitar complementos](https://opencode.ai/docs/es/troubleshooting#deshabilitar-complementos) Si la aplicación de escritorio falla al iniciarse, se bloquea o se comporta de manera extraña, comience por deshabilitar los complementos. #### [Verifique la configuración global](https://opencode.ai/docs/es/troubleshooting#verifique-la-configuraci%C3%B3n-global) Abra su archivo de configuración global y busque una clave `plugin`. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (o `~/.config/opencode/opencode.json`) * **macOS/Linux** (instalaciones anteriores): `~/.local/share/opencode/opencode.jsonc` * **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.config\opencode\opencode.jsonc` Si tiene complementos configurados, desactívelos temporalmente eliminando la clave o configurándola en una matriz vacía: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Verificar directorios de complementos](https://opencode.ai/docs/es/troubleshooting#verificar-directorios-de-complementos) OpenCode también puede cargar complementos locales desde el disco. Quítelos temporalmente del camino (o cambie el nombre de la carpeta) y reinicie la aplicación de escritorio: * **Complementos globales** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.config\opencode\plugins` * **Complementos de proyecto** (solo si usas la configuración por proyecto) * `/.opencode/plugins/` Si la aplicación comienza a funcionar nuevamente, vuelva a habilitar los complementos uno a la vez para encontrar cuál está causando el problema. * * * ### [Borrar el caché](https://opencode.ai/docs/es/troubleshooting#borrar-el-cach%C3%A9) Si deshabilitar los complementos no ayuda (o la instalación de un complemento está bloqueada), borre el caché para que OpenCode pueda reconstruirlo. 1. Salga de OpenCode Desktop por completo. 2. Elimine el directorio de caché: * **macOS**: Buscador -> `Cmd+Shift+G` -> pegar `~/.cache/opencode` * **Linux**: eliminar `~/.cache/opencode` (o ejecutar `rm -rf ~/.cache/opencode`) * **Windows**: Presione `WIN+R` y pegue `%USERPROFILE%\.cache\opencode` 3. Reinicie el escritorio OpenCode. * * * ### [Solucionar problemas de conexión del servidor](https://opencode.ai/docs/es/troubleshooting#solucionar-problemas-de-conexi%C3%B3n-del-servidor) OpenCode Desktop puede iniciar su propio servidor local (predeterminado) o conectarse a la URL de un servidor que haya configurado. Si ve un cuadro de diálogo **“Error de conexión”** (o la aplicación nunca pasa de la pantalla de inicio), busque una URL de servidor personalizada. #### [Borrar la URL del servidor predeterminado del escritorio](https://opencode.ai/docs/es/troubleshooting#borrar-la-url-del-servidor-predeterminado-del-escritorio) Desde la pantalla de inicio, haga clic en el nombre del servidor (con el punto de estado) para abrir el selector de servidor. En la sección **Servidor predeterminado**, haga clic en **Borrar**. #### [Elimina `server.port` / `server.hostname` de tu configuración](https://opencode.ai/docs/es/troubleshooting#elimina-serverport--serverhostname-de-tu-configuraci%C3%B3n) Si su `opencode.json(c)` contiene una sección `server`, elimínela temporalmente y reinicie la aplicación de escritorio. #### [Verificar variables de entorno](https://opencode.ai/docs/es/troubleshooting#verificar-variables-de-entorno) Si tiene `OPENCODE_PORT` configurado en su entorno, la aplicación de escritorio intentará usar ese puerto para el servidor local. * Desarme `OPENCODE_PORT` (o elija un puerto libre) y reinicie. * * * ### [Linux: Problemas con Wayland/X11](https://opencode.ai/docs/es/troubleshooting#linux-problemas-con-waylandx11) En Linux, algunas configuraciones de Wayland pueden causar ventanas en blanco o errores de compositor. * Si estás en Wayland y la aplicación está en blanco o falla, intenta iniciarla con `OC_ALLOW_WAYLAND=1`. * Si eso empeora las cosas, elimínelo e intente iniciarlo en una sesión X11. * * * ### [Windows: tiempo de ejecución de WebView2](https://opencode.ai/docs/es/troubleshooting#windows-tiempo-de-ejecuci%C3%B3n-de-webview2) En Windows, el escritorio OpenCode requiere Microsoft Edge **WebView2 Runtime**. Si la aplicación se abre en una ventana en blanco o no se inicia, instale/actualice WebView2 e inténtelo nuevamente. * * * ### [Windows: Problemas generales de rendimiento](https://opencode.ai/docs/es/troubleshooting#windows-problemas-generales-de-rendimiento) Si tiene un rendimiento lento, problemas de acceso a archivos o problemas de terminal en Windows, intente usar [WSL (Windows Subsistema para Linux)](https://opencode.ai/docs/windows-wsl) . WSL proporciona un entorno Linux que funciona de manera más fluida con las funciones de OpenCode. * * * ### [Notificaciones que no se muestran](https://opencode.ai/docs/es/troubleshooting#notificaciones-que-no-se-muestran) OpenCode Desktop solo muestra notificaciones del sistema cuando: * las notificaciones están habilitadas para OpenCode en la configuración de su sistema operativo, y * la ventana de la aplicación no está enfocada. * * * ### [Restablecer el almacenamiento de la aplicación de escritorio (último recurso)](https://opencode.ai/docs/es/troubleshooting#restablecer-el-almacenamiento-de-la-aplicaci%C3%B3n-de-escritorio-%C3%BAltimo-recurso) Si la aplicación no se inicia y no puede borrar la configuración desde la interfaz de usuario, restablezca el estado guardado de la aplicación de escritorio. 1. Salga del escritorio OpenCode. 2. Busque y elimine estos archivos (se encuentran en el directorio de datos de la aplicación de escritorio OpenCode): * `opencode.settings.dat` (URL del servidor predeterminado de escritorio) * `opencode.global.dat` y `opencode.workspace.*.dat` (estado de la interfaz de usuario como servidores/proyectos recientes) Para encontrar el directorio rápidamente: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (luego busque los nombres de archivo arriba) * **Linux**: busque en `~/.local/share` los nombres de archivo anteriores * **Windows**: Presione `WIN+R` -> `%APPDATA%` (luego busque los nombres de archivo arriba) * * * [Obtener ayuda](https://opencode.ai/docs/es/troubleshooting#obtener-ayuda) --------------------------------------------------------------------------- Si tiene problemas con OpenCode: 1. **Informar problemas el GitHub** La mejor manera de informar errores o solicitar funciones es a través de nuestro repositorio GitHub: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Antes de crear un nuevo problema, busque los problemas existentes para ver si su problema ya ha sido informado. 2. **Únete a nuestro Discord** Para obtener ayuda en tiempo real y debates comunitarios, únase a nuestro servidor de Discord: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Problemas comunes](https://opencode.ai/docs/es/troubleshooting#problemas-comunes) ----------------------------------------------------------------------------------- A continuación se detallan algunos problemas comunes y cómo resolverlos. * * * ### [OpenCode no se inicia](https://opencode.ai/docs/es/troubleshooting#opencode-no-se-inicia) 1. Verifique los registros en busca de mensajes de error. 2. Intente ejecutar con `--print-logs` para ver el resultado en la terminal. 3. Asegúrese de tener la última versión con `opencode upgrade` * * * ### [Problemas de autenticación](https://opencode.ai/docs/es/troubleshooting#problemas-de-autenticaci%C3%B3n) 1. Intente volver a autenticarse con el comando `/connect` en TUI 2. Verifique que sus claves API sean válidas 3. Asegúrese de que su red permita conexiones al API del proveedor. * * * ### [Modelo no disponible](https://opencode.ai/docs/es/troubleshooting#modelo-no-disponible) 1. Comprueba que te has autenticado con el proveedor. 2. Verifique que el nombre del modelo en su configuración sea correcto 3. Algunos modelos pueden requerir acceso o suscripciones específicas Si encuentra `ProviderModelNotFoundError`, lo más probable es que esté equivocado. haciendo referencia a un modelo en alguna parte. Se debe hacer referencia a los modelos así: `/` Ejemplos: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` Para saber a qué modelos tiene acceso, ejecute `opencode models` * * * ### [Error de inicio del proveedor](https://opencode.ai/docs/es/troubleshooting#error-de-inicio-del-proveedor) Si encuentra un ProviderInitError, es probable que tenga una configuración no válida o dañada. Para resolver esto: 1. Primero, verifique que su proveedor esté configurado correctamente siguiendo la [guía de proveedores](https://opencode.ai/docs/providers) 2. Si el problema persiste, intente borrar la configuración almacenada: rm -rf ~/.local/share/opencode En Windows, presione `WIN+R` y elimine: `%USERPROFILE%\.local\share\opencode` 3. Vuelva a autenticarse con su proveedor utilizando el comando `/connect` en TUI. * * * ### [AI\_APICallError y problemas con el paquete del proveedor](https://opencode.ai/docs/es/troubleshooting#ai_apicallerror-y-problemas-con-el-paquete-del-proveedor) Si encuentra errores de llamada API, esto puede deberse a paquetes de proveedores obsoletos. opencode instala dinámicamente paquetes de proveedores (OpenAI, Anthropic, Google, etc.) según sea necesario y los almacena en caché localmente. Para resolver problemas con el paquete del proveedor: 1. Borre la caché del paquete del proveedor: rm -rf ~/.cache/opencode En Windows, presione `WIN+R` y elimine: `%USERPROFILE%\.cache\opencode` 2. Reinicie opencode para reinstalar los paquetes del proveedor más recientes. Esto obligará a opencode a descargar las versiones más recientes de los paquetes del proveedor, lo que a menudo resuelve problemas de compatibilidad con los parámetros del modelo y los cambios de API. * * * ### [Copiar/pegar no funciona en Linux](https://opencode.ai/docs/es/troubleshooting#copiarpegar-no-funciona-en-linux) Los usuarios de Linux deben tener instalada una de las siguientes utilidades del portapapeles para que funcione la función copiar/pegar: **Para sistemas X11:** apt install -y xclip# orapt install -y xsel **Para sistemas Wayland:** apt install -y wl-clipboard **Para entornos sin cabeza:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode detectará si estás usando Wayland y prefieres `wl-clipboard`; de lo contrario, intentará encontrar herramientas del portapapeles en el orden de: `xclip` y `xsel`. --- # Solução de Problemas | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/troubleshooting#_top) Solução de Problemas ==================== Problemas comuns e como resolvê-los. Para depurar problemas com o opencode, comece verificando os logs e os dados locais que ele armazena no disco. * * * [Logs](https://opencode.ai/docs/pt-br/troubleshooting#logs) ------------------------------------------------------------ Os arquivos de log são gravados em: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.local\share\opencode\log` Os arquivos de log são nomeados com timestamps (por exemplo, `2025-01-09T123456.log`) e os 10 arquivos de log mais recentes são mantidos. Você pode definir o nível de log com a opção de linha de comando `--log-level` para obter informações de depuração mais detalhadas. Por exemplo, `opencode --log-level DEBUG`. * * * [Armazenamento](https://opencode.ai/docs/pt-br/troubleshooting#armazenamento) ------------------------------------------------------------------------------ O opencode armazena dados de sessão e outros dados do aplicativo no disco em: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.local\share\opencode` Este diretório contém: * `auth.json` - Dados de autenticação como chaves de API, tokens OAuth * `log/` - Logs do aplicativo * `project/` - Dados específicos do projeto, como dados de sessão e mensagens * Se o projeto estiver dentro de um repositório Git, ele é armazenado em `.//storage/` * Se não for um repositório Git, ele é armazenado em `./global/storage/` * * * [Aplicativo de Desktop](https://opencode.ai/docs/pt-br/troubleshooting#aplicativo-de-desktop) ---------------------------------------------------------------------------------------------- O opencode Desktop executa um servidor opencode local (o sidecar `opencode-cli`) em segundo plano. A maioria dos problemas é causada por um plugin com mau funcionamento, um cache corrompido ou uma configuração de servidor incorreta. ### [Verificações rápidas](https://opencode.ai/docs/pt-br/troubleshooting#verifica%C3%A7%C3%B5es-r%C3%A1pidas) * Saia completamente do aplicativo e reinicie-o. * Se o aplicativo mostrar uma tela de erro, clique em **Reiniciar** e copie os detalhes do erro. * Apenas macOS: menu `OpenCode` -> **Recarregar Webview** (ajuda se a interface estiver em branco/congelada). * * * ### [Desativando plugins](https://opencode.ai/docs/pt-br/troubleshooting#desativando-plugins) Se o aplicativo de desktop estiver travando ao iniciar, pendurado ou se comportando de maneira estranha, comece desativando os plugins. #### [Verificando a configuração global](https://opencode.ai/docs/pt-br/troubleshooting#verificando-a-configura%C3%A7%C3%A3o-global) Abra seu arquivo de configuração global e procure uma chave `plugin`. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (ou `~/.config/opencode/opencode.json`) * **macOS/Linux** (instalações mais antigas): `~/.local/share/opencode/opencode.jsonc` * **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.config\opencode\opencode.jsonc` Se você tiver plugins configurados, desative-os temporariamente removendo a chave ou definindo-a como um array vazio: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Verificando os diretórios de plugins](https://opencode.ai/docs/pt-br/troubleshooting#verificando-os-diret%C3%B3rios-de-plugins) O opencode também pode carregar plugins locais do disco. Mova-os temporariamente para fora do caminho (ou renomeie a pasta) e reinicie o aplicativo de desktop: * **Plugins globais** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.config\opencode\plugins` * **Plugins de projeto** (apenas se você usar configuração por projeto) * `/.opencode/plugins/` Se o aplicativo voltar a funcionar, reative os plugins um por um para descobrir qual está causando o problema. * * * ### [Limpando o cache](https://opencode.ai/docs/pt-br/troubleshooting#limpando-o-cache) Se desativar plugins não ajudar (ou se a instalação de um plugin estiver travada), limpe o cache para que o opencode possa reconstruí-lo. 1. Saia completamente do opencode Desktop. 2. Exclua o diretório de cache: * **macOS**: Finder -> `Cmd+Shift+G` -> cole `~/.cache/opencode` * **Linux**: exclua `~/.cache/opencode` (ou execute `rm -rf ~/.cache/opencode`) * **Windows**: Pressione `WIN+R` e cole `%USERPROFILE%\.cache\opencode` 3. Reinicie o opencode Desktop. * * * ### [Corrigindo problemas de conexão com o servidor](https://opencode.ai/docs/pt-br/troubleshooting#corrigindo-problemas-de-conex%C3%A3o-com-o-servidor) O opencode Desktop pode iniciar seu próprio servidor local (padrão) ou conectar-se a uma URL de servidor que você configurou. Se você ver um diálogo **“Conexão Falhou”** (ou o aplicativo nunca passa da tela de inicialização), verifique se há uma URL de servidor personalizada. #### [Limpando a URL do servidor padrão do desktop](https://opencode.ai/docs/pt-br/troubleshooting#limpando-a-url-do-servidor-padr%C3%A3o-do-desktop) Na tela inicial, clique no nome do servidor (com o ponto de status) para abrir o seletor de Servidor. Na seção **Servidor padrão**, clique em **Limpar**. #### [Removendo `server.port` / `server.hostname` da sua configuração](https://opencode.ai/docs/pt-br/troubleshooting#removendo-serverport--serverhostname-da-sua-configura%C3%A7%C3%A3o) Se seu `opencode.json(c)` contiver uma seção `server`, remova-a temporariamente e reinicie o aplicativo de desktop. #### [Verificando as variáveis de ambiente](https://opencode.ai/docs/pt-br/troubleshooting#verificando-as-vari%C3%A1veis-de-ambiente) Se você tiver `OPENCODE_PORT` definido em seu ambiente, o aplicativo de desktop tentará usar essa porta para o servidor local. * Desfaça `OPENCODE_PORT` (ou escolha uma porta livre) e reinicie. * * * ### [Linux: Problemas com Wayland / X11](https://opencode.ai/docs/pt-br/troubleshooting#linux-problemas-com-wayland--x11) No Linux, algumas configurações do Wayland podem causar janelas em branco ou erros de compositor. * Se você estiver no Wayland e o aplicativo estiver em branco/travando, tente iniciar com `OC_ALLOW_WAYLAND=1`. * Se isso piorar as coisas, remova e tente iniciar sob uma sessão X11. * * * ### [Windows: Runtime do WebView2](https://opencode.ai/docs/pt-br/troubleshooting#windows-runtime-do-webview2) No Windows, o opencode Desktop requer o **WebView2 Runtime** do Microsoft Edge. Se o aplicativo abrir em uma janela em branco ou não iniciar, instale/atualize o WebView2 e tente novamente. * * * ### [Windows: Problemas gerais de desempenho](https://opencode.ai/docs/pt-br/troubleshooting#windows-problemas-gerais-de-desempenho) Se você estiver enfrentando desempenho lento, problemas de acesso a arquivos ou problemas no terminal no Windows, tente usar [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) . O WSL fornece um ambiente Linux que funciona de forma mais integrada com os recursos do opencode. * * * ### [Notificações não aparecendo](https://opencode.ai/docs/pt-br/troubleshooting#notifica%C3%A7%C3%B5es-n%C3%A3o-aparecendo) O opencode Desktop só mostra notificações do sistema quando: * as notificações estão habilitadas para o opencode nas configurações do seu sistema operacional, e * a janela do aplicativo não está focada. * * * ### [Redefinindo o armazenamento do aplicativo de desktop (último recurso)](https://opencode.ai/docs/pt-br/troubleshooting#redefinindo-o-armazenamento-do-aplicativo-de-desktop-%C3%BAltimo-recurso) Se o aplicativo não iniciar e você não conseguir limpar as configurações pela interface, redefina o estado salvo do aplicativo de desktop. 1. Saia do opencode Desktop. 2. Encontre e exclua estes arquivos (eles estão no diretório de dados do aplicativo opencode Desktop): * `opencode.settings.dat` (URL do servidor padrão do desktop) * `opencode.global.dat` e `opencode.workspace.*.dat` (estado da interface como servidores/projetos recentes) Para encontrar o diretório rapidamente: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (depois pesquise pelos nomes dos arquivos acima) * **Linux**: pesquise em `~/.local/share` pelos nomes dos arquivos acima * **Windows**: Pressione `WIN+R` -> `%APPDATA%` (depois pesquise pelos nomes dos arquivos acima) * * * [Obtendo ajuda](https://opencode.ai/docs/pt-br/troubleshooting#obtendo-ajuda) ------------------------------------------------------------------------------ Se você estiver enfrentando problemas com o opencode: 1. **Relatar problemas no GitHub** A melhor maneira de relatar bugs ou solicitar recursos é através do nosso repositório no GitHub: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Antes de criar um novo problema, pesquise problemas existentes para ver se seu problema já foi relatado. 2. **Junte-se ao nosso Discord** Para ajuda em tempo real e discussão da comunidade, junte-se ao nosso servidor Discord: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Problemas comuns](https://opencode.ai/docs/pt-br/troubleshooting#problemas-comuns) ------------------------------------------------------------------------------------ Aqui estão alguns problemas comuns e como resolvê-los. * * * ### [O opencode não inicia](https://opencode.ai/docs/pt-br/troubleshooting#o-opencode-n%C3%A3o-inicia) 1. Verifique os logs em busca de mensagens de erro 2. Tente executar com `--print-logs` para ver a saída no terminal 3. Certifique-se de que você tem a versão mais recente com `opencode upgrade` * * * ### [Problemas de autenticação](https://opencode.ai/docs/pt-br/troubleshooting#problemas-de-autentica%C3%A7%C3%A3o) 1. Tente reautenticar com o comando `/connect` na TUI 2. Verifique se suas chaves de API são válidas 3. Certifique-se de que sua rede permite conexões com a API do provedor * * * ### [Modelo não disponível](https://opencode.ai/docs/pt-br/troubleshooting#modelo-n%C3%A3o-dispon%C3%ADvel) 1. Verifique se você se autenticou com o provedor 2. Verifique se o nome do modelo em sua configuração está correto 3. Alguns modelos podem exigir acesso ou assinaturas específicas Se você encontrar `ProviderModelNotFoundError`, é mais provável que você esteja referenciando um modelo incorretamente em algum lugar. Os modelos devem ser referenciados assim: `/` Exemplos: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` Para descobrir quais modelos você tem acesso, execute `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/pt-br/troubleshooting#provideriniterror) Se você encontrar um ProviderInitError, provavelmente você tem uma configuração inválida ou corrompida. Para resolver isso: 1. Primeiro, verifique se seu provedor está configurado corretamente seguindo o [guia de provedores](https://opencode.ai/docs/providers) 2. Se o problema persistir, tente limpar sua configuração armazenada: rm -rf ~/.local/share/opencode No Windows, pressione `WIN+R` e exclua: `%USERPROFILE%\.local\share\opencode` 3. Reautentique-se com seu provedor usando o comando `/connect` na TUI. * * * ### [AI\_APICallError e problemas com pacotes de provedores](https://opencode.ai/docs/pt-br/troubleshooting#ai_apicallerror-e-problemas-com-pacotes-de-provedores) Se você encontrar erros de chamada de API, isso pode ser devido a pacotes de provedores desatualizados. O opencode instala dinamicamente pacotes de provedores (OpenAI, Anthropic, Google, etc.) conforme necessário e os armazena em cache localmente. Para resolver problemas com pacotes de provedores: 1. Limpe o cache do pacote de provedores: rm -rf ~/.cache/opencode No Windows, pressione `WIN+R` e exclua: `%USERPROFILE%\.cache\opencode` 2. Reinicie o opencode para reinstalar os pacotes de provedores mais recentes Isso forçará o opencode a baixar as versões mais recentes dos pacotes de provedores, o que muitas vezes resolve problemas de compatibilidade com parâmetros de modelo e alterações na API. * * * ### [Copiar/colar não funciona no Linux](https://opencode.ai/docs/pt-br/troubleshooting#copiarcolar-n%C3%A3o-funciona-no-linux) Usuários do Linux precisam ter um dos seguintes utilitários de área de transferência instalados para que a funcionalidade de copiar/colar funcione: **Para sistemas X11:** apt install -y xclip# orapt install -y xsel **Para sistemas Wayland:** apt install -y wl-clipboard **Para ambientes sem cabeça:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 O opencode detectará se você está usando Wayland e preferirá `wl-clipboard`, caso contrário, tentará encontrar ferramentas de área de transferência na ordem: `xclip` e `xsel`. --- # Sorun giderme | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/troubleshooting#_top) Sorun giderme ============= Yaygin sorunlar ve cozum adimlari. opencode ile ilgili bir sorunu ayiklamak icin once loglari ve diskte tuttugu yerel verileri kontrol edin. * * * [Loglar](https://opencode.ai/docs/tr/troubleshooting#loglar) ------------------------------------------------------------- Log dosyalari su konuma yazilir: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.local\share\opencode\log` yapistirin Log dosyalari zaman damgasiyla adlandirilir (ornegin `2025-01-09T123456.log`) ve en yeni 10 log dosyasi tutulur. Daha ayrintili ayiklama bilgisi icin `--log-level` komut satiri secenegini kullanabilirsiniz. Ornek: `opencode --log-level DEBUG`. * * * [Depolama](https://opencode.ai/docs/tr/troubleshooting#depolama) ----------------------------------------------------------------- opencode, oturum verilerini ve diger uygulama verilerini diskte su konumda saklar: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.local\share\opencode` yapistirin Bu dizin sunlari icerir: * `auth.json` - API anahtarlari, OAuth tokenlari gibi kimlik dogrulama verileri * `log/` - Uygulama loglari * `project/` - Oturum ve mesaj verileri gibi projeye ozel veriler * Proje bir Git deposundaysa `.//storage/` altinda saklanir * Git deposu degilse `./global/storage/` altinda saklanir * * * [Masaüstü uygulaması](https://opencode.ai/docs/tr/troubleshooting#masa%C3%BCst%C3%BC-uygulamas%C4%B1) ------------------------------------------------------------------------------------------------------ opencode Desktop arka planda yerel bir opencode sunucusu (`opencode-cli` sidecar) calistirir. Sorunlarin cogu bozuk bir plugin, hasarli cache veya hatali sunucu ayarindan kaynaklanir. ### [Hızlı kontroller](https://opencode.ai/docs/tr/troubleshooting#h%C4%B1zl%C4%B1-kontroller) * Uygulamayi tamamen kapatip yeniden acin * Uygulama hata ekrani gosteriyorsa **Restart**’a tiklayip hata detaylarini kopyalayin * Yalnizca macOS: `opencode` menusu -> **Reload Webview** (arayuz bos/donukse yardimci olur) * * * ### [Eklentileri devre dışı bırakın](https://opencode.ai/docs/tr/troubleshooting#eklentileri-devre-d%C4%B1%C5%9F%C4%B1-b%C4%B1rak%C4%B1n) Desktop uygulamasi acilista cokuyorsa, takiliyorsa veya garip davranislar gosteriyorsa once pluginleri devre disi birakin. #### [Global config’i kontrol edin](https://opencode.ai/docs/tr/troubleshooting#global-configi-kontrol-edin) Global config dosyanizi acin ve `plugin` anahtarini arayin. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (veya `~/.config/opencode/opencode.json`) * **macOS/Linux** (eski kurulumlar): `~/.local/share/opencode/opencode.jsonc` * **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.config\opencode\opencode.jsonc` yapistirin Plugin tanimliysa anahtari kaldirarak veya bos bir diziye cekerek gecici olarak devre disi birakin: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Eklenti dizinlerini kontrol edin](https://opencode.ai/docs/tr/troubleshooting#eklenti-dizinlerini-kontrol-edin) opencode diskten yerel plugin de yukleyebilir. Bu dizinleri gecici olarak tasiyin (veya klasoru yeniden adlandirin) ve uygulamayi yeniden baslatin: * **Global plugins** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.config\opencode\plugins` yapistirin * **Project plugins** (sadece proje bazli config kullaniyorsaniz) * `/.opencode/plugins/` Uygulama duzelirse soruna neden olan plugini bulmak icin pluginleri tek tek yeniden etkinlestirin. * * * ### [Cache’i temizleyin](https://opencode.ai/docs/tr/troubleshooting#cachei-temizleyin) Pluginleri kapatmak ise yaramazsa (veya plugin kurulumu takili kaldiysa), opencode’un cache’i yeniden olusturmasi icin cache’i temizleyin. 1. opencode Desktop’u tamamen kapatin 2. Cache dizinini silin: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/.cache/opencode` * **Linux**: `~/.cache/opencode` dizinini silin (veya `rm -rf ~/.cache/opencode` calistirin) * **Windows**: `WIN+R` tuslayip `%USERPROFILE%\.cache\opencode` yapistirin 3. opencode Desktop’u yeniden baslatin * * * ### [Sunucu bağlantı sorunlarını düzeltin](https://opencode.ai/docs/tr/troubleshooting#sunucu-ba%C4%9Flant%C4%B1-sorunlar%C4%B1n%C4%B1-d%C3%BCzeltin) opencode Desktop ya kendi yerel sunucusunu baslatir (varsayilan) ya da sizin tanimladiginiz bir sunucu URL’sine baglanir. **“Connection Failed”** penceresi goruyorsaniz (veya uygulama acilis ekranini gecemiyorsa), ozel bir sunucu URL’si olup olmadigini kontrol edin. #### [Desktop varsayilan sunucu URL’sini temizleyin](https://opencode.ai/docs/tr/troubleshooting#desktop-varsayilan-sunucu-urlsini-temizleyin) Ana ekranda sunucu adina (durum noktali) tiklayarak Server secicisini acin. **Default server** bolumunde **Clear**’a tiklayin. #### [Config’ten `server.port` / `server.hostname` kaldirin](https://opencode.ai/docs/tr/troubleshooting#configten-serverport--serverhostname-kaldirin) `opencode.json(c)` dosyanizda `server` bolumu varsa gecici olarak kaldirin ve desktop uygulamasini yeniden baslatin. #### [Ortam degiskenlerini kontrol edin](https://opencode.ai/docs/tr/troubleshooting#ortam-degiskenlerini-kontrol-edin) Ortamda `OPENCODE_PORT` ayarliysa desktop uygulamasi yerel sunucu icin o portu kullanmaya calisir. * `OPENCODE_PORT` degerini kaldirin (veya bos bir port secin) ve yeniden baslatin * * * ### [Linux: Wayland / X11 sorunları](https://opencode.ai/docs/tr/troubleshooting#linux-wayland--x11-sorunlar%C4%B1) Linux’ta bazi Wayland kurulumlari bos pencere veya compositor hatalarina yol acabilir. * Wayland kullaniyorsaniz ve uygulama bos/acilmiyorsa `OC_ALLOW_WAYLAND=1` ile baslatin * Bu daha kotu olursa kaldirip X11 oturumunda baslatmayi deneyin * * * ### [Windows: WebView2 Çalışma Zamanı](https://opencode.ai/docs/tr/troubleshooting#windows-webview2-%C3%A7al%C4%B1%C5%9Fma-zaman%C4%B1) Windows’ta opencode Desktop, Microsoft Edge **WebView2 Runtime** gerektirir. Uygulama bos pencereyle aciliyorsa veya hic baslamiyorsa WebView2’yi kurup/guncelleyip tekrar deneyin. * * * ### [Windows: Genel performans sorunları](https://opencode.ai/docs/tr/troubleshooting#windows-genel-performans-sorunlar%C4%B1) Windows’ta yavaslik, dosya erisim sorunlari veya terminal problemleri yasiyorsaniz [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) kullanmayi deneyin. WSL, opencode ozellikleriyle daha sorunsuz calisan bir Linux ortami saglar. * * * ### [Bildirimler görünmüyor](https://opencode.ai/docs/tr/troubleshooting#bildirimler-g%C3%B6r%C3%BCnm%C3%BCyor) opencode Desktop sistem bildirimlerini yalnizca su durumlarda gosterir: * Isletim sistemi ayarlarinizda opencode icin bildirimler etkinse * Uygulama penceresi odakta degilse * * * ### [Desktop depolamasını sıfırlayın (son çare)](https://opencode.ai/docs/tr/troubleshooting#desktop-depolamas%C4%B1n%C4%B1-s%C4%B1f%C4%B1rlay%C4%B1n-son-%C3%A7are) Uygulama acilmiyorsa ve ayarlari arayuz icinden temizleyemiyorsaniz, desktop uygulamasinin kayitli durumunu sifirlayin. 1. opencode Desktop’u kapatin 2. Su dosyalari bulun ve silin (opencode Desktop uygulama veri dizininde yer alirlar): * `opencode.settings.dat` (desktop varsayilan sunucu URL’si) * `opencode.global.dat` ve `opencode.workspace.*.dat` (son sunucular/projeler gibi UI durumu) Dizini hizlica bulmak icin: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (ardindan yukaridaki dosya adlarini aratin) * **Linux**: `~/.local/share` altinda bu dosya adlarini aratin * **Windows**: `WIN+R` -> `%APPDATA%` (ardindan bu dosya adlarini aratin) * * * [Yardım alın](https://opencode.ai/docs/tr/troubleshooting#yard%C4%B1m-al%C4%B1n) --------------------------------------------------------------------------------- opencode ile ilgili bir sorun yasiyorsaniz: 1. **GitHub’da issue acin** Hata bildirmek veya ozellik talep etmek icin en iyi yol GitHub depomuzdur: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Yeni issue acmadan once sorununuzun daha once raporlanip raporlanmadigini kontrol edin. 2. **Discord’a katilin** Gercek zamanli yardim ve topluluk sohbeti icin Discord sunucumuza katilin: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Yaygın sorunlar](https://opencode.ai/docs/tr/troubleshooting#yayg%C4%B1n-sorunlar) ------------------------------------------------------------------------------------ Asagida yaygin sorunlar ve cozumleri yer aliyor. * * * ### [opencode başlamıyor](https://opencode.ai/docs/tr/troubleshooting#opencode-ba%C5%9Flam%C4%B1yor) 1. Hata mesaji icin loglari kontrol edin 2. Terminalde cikti gormek icin `--print-logs` ile calistirin 3. `opencode upgrade` ile en guncel surumu kullandiginizdan emin olun * * * ### [Kimlik doğrulama sorunları](https://opencode.ai/docs/tr/troubleshooting#kimlik-do%C4%9Frulama-sorunlar%C4%B1) 1. TUI’da `/connect` komutuyla yeniden kimlik dogrulamasi yapin 2. API anahtarlarinizin gecerli oldugunu kontrol edin 3. Aginizin provider API baglantilarina izin verdiginden emin olun * * * ### [Model kullanılamıyor](https://opencode.ai/docs/tr/troubleshooting#model-kullan%C4%B1lam%C4%B1yor) 1. Provider ile kimlik dogrulamasi yaptiginizi kontrol edin 2. Config’teki model adinin dogru oldugunu dogrulayin 3. Bazi modeller ozel erisim veya abonelik gerektirebilir `ProviderModelNotFoundError` aliyorsaniz buyuk olasilikla bir yerde model referansi yanlistir. Model referansi su formatta olmalidir: `/` Ornekler: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` Erisiminiz olan modelleri gormek icin `opencode models` calistirin. * * * ### [ProviderInitError](https://opencode.ai/docs/tr/troubleshooting#provideriniterror) `ProviderInitError` aliyorsaniz buyuk olasilikla config’iniz gecersiz veya bozulmustur. Cozum adimlari: 1. Once [providers rehberini](https://opencode.ai/docs/providers) izleyerek provider kurulumunun dogru oldugunu dogrulayin 2. Sorun surerse kayitli konfigurasyonu temizlemeyi deneyin: rm -rf ~/.local/share/opencode Windows’ta `WIN+R` tuslayip su konumu silin: `%USERPROFILE%\.local\share\opencode` 3. TUI’da `/connect` komutuyla provider kimlik dogrulamasini tekrar yapin * * * ### [AI\_APICallError ve provider paket sorunlari](https://opencode.ai/docs/tr/troubleshooting#ai_apicallerror-ve-provider-paket-sorunlari) API cagrisi hatalari aliyorsaniz bunun nedeni guncel olmayan provider paketleri olabilir. opencode, provider paketlerini (OpenAI, Anthropic, Google vb.) gerektikce dinamik yukler ve yerelde onbellekler. Provider paket sorunlarini gidermek icin: 1. Provider paket cache’ini temizleyin: rm -rf ~/.cache/opencode Windows’ta `WIN+R` tuslayip su konumu silin: `%USERPROFILE%\.cache\opencode` 2. En guncel provider paketlerini yeniden kurmak icin opencode’u yeniden baslatin Bu, opencode’un en yeni provider paket surumlerini indirmesini zorlar ve model parametresi/API degisikliklerinden kaynakli uyumsuzluklari cogu zaman cozer. * * * ### [Linux’ta kopyala/yapıştır çalışmıyor](https://opencode.ai/docs/tr/troubleshooting#linuxta-kopyalayap%C4%B1%C5%9Ft%C4%B1r-%C3%A7al%C4%B1%C5%9Fm%C4%B1yor) Linux kullanicilarinin kopyala/yapistir ozelliginin calismasi icin asagidaki pano araclarindan en az birini kurmasi gerekir: **X11 sistemleri icin:** apt install -y xclip# orapt install -y xsel **Wayland sistemleri icin:** apt install -y wl-clipboard **Headless ortamlar icin:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode, Wayland kullandiginizi algilarsa `wl-clipboard` tercihi yapar. Aksi halde sirayla `xclip` ve `xsel` araclarini arar. --- # 故障排除 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/troubleshooting#_top) 故障排除 ==== 常见问题及其解决方法。 要调试 OpenCode 的问题,请先检查其存储在磁盘上的日志和本地数据。 * * * [日志](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%97%A5%E5%BF%97) ------------------------------------------------------------------------ 日志文件写入位置: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: 按 `WIN+R` 并粘贴 `%USERPROFILE%\.local\share\opencode\log` 日志文件以时间戳命名(例如 `2025-01-09T123456.log`),并保留最近的 10 个日志文件。 你可以通过 `--log-level` 命令行选项设置日志级别以获取更详细的调试信息。例如:`opencode --log-level DEBUG`。 * * * [存储](https://opencode.ai/docs/zh-cn/troubleshooting#%E5%AD%98%E5%82%A8) ------------------------------------------------------------------------ OpenCode 将会话数据和其他应用数据存储在磁盘上: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: 按 `WIN+R` 并粘贴 `%USERPROFILE%\.local\share\opencode` 该目录包含: * `auth.json` - 身份验证数据,如 API 密钥、OAuth Token * `log/` - 应用日志 * `project/` - 项目特定数据,如会话和消息数据 * 如果项目位于 Git 仓库中,则存储在 `.//storage/` * 如果不是 Git 仓库,则存储在 `./global/storage/` * * * [桌面应用](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%A1%8C%E9%9D%A2%E5%BA%94%E7%94%A8) -------------------------------------------------------------------------------------------- OpenCode Desktop 会在后台运行一个本地 OpenCode 服务器(即 `opencode-cli` 附属进程)。大多数问题是由插件异常、缓存损坏或错误的服务器设置引起的。 ### [快速检查](https://opencode.ai/docs/zh-cn/troubleshooting#%E5%BF%AB%E9%80%9F%E6%A3%80%E6%9F%A5) * 完全退出并重新启动应用。 * 如果应用显示错误页面,请点击**重新启动**并复制错误详情。 * 仅限 macOS:`OpenCode` 菜单 -> **Reload Webview**(当 UI 空白或冻结时有效)。 * * * ### [禁用插件](https://opencode.ai/docs/zh-cn/troubleshooting#%E7%A6%81%E7%94%A8%E6%8F%92%E4%BB%B6) 如果桌面应用在启动时崩溃、卡住或行为异常,请先禁用插件。 #### [检查全局配置](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%A3%80%E6%9F%A5%E5%85%A8%E5%B1%80%E9%85%8D%E7%BD%AE) 打开你的全局配置文件,查找 `plugin` 键。 * **macOS/Linux**: `~/.config/opencode/opencode.jsonc`(或 `~/.config/opencode/opencode.json`) * **macOS/Linux**(旧版安装): `~/.local/share/opencode/opencode.jsonc` * **Windows**: 按 `WIN+R` 并粘贴 `%USERPROFILE%\.config\opencode\opencode.jsonc` 如果你配置了插件,请通过移除该键或将其设置为空数组来临时禁用它们: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [检查插件目录](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%A3%80%E6%9F%A5%E6%8F%92%E4%BB%B6%E7%9B%AE%E5%BD%95) OpenCode 还可以从磁盘加载本地插件。临时将这些插件移走(或重命名文件夹),然后重新启动桌面应用: * **全局插件** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: 按 `WIN+R` 并粘贴 `%USERPROFILE%\.config\opencode\plugins` * **项目插件**(仅当你使用了项目级配置时) * `/.opencode/plugins/` 如果应用恢复正常,请逐个重新启用插件,找出导致问题的那个。 * * * ### [清除缓存](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%B8%85%E9%99%A4%E7%BC%93%E5%AD%98) 如果禁用插件没有帮助(或插件安装卡住了),请清除缓存以便 OpenCode 重新构建。 1. 完全退出 OpenCode Desktop。 2. 删除缓存目录: * **macOS**: Finder -> `Cmd+Shift+G` -> 粘贴 `~/.cache/opencode` * **Linux**: 删除 `~/.cache/opencode`(或运行 `rm -rf ~/.cache/opencode`) * **Windows**: 按 `WIN+R` 并粘贴 `%USERPROFILE%\.cache\opencode` 3. 重新启动 OpenCode Desktop。 * * * ### [修复服务器连接问题](https://opencode.ai/docs/zh-cn/troubleshooting#%E4%BF%AE%E5%A4%8D%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9E%E6%8E%A5%E9%97%AE%E9%A2%98) OpenCode Desktop 可以启动自己的本地服务器(默认行为),也可以连接到你配置的服务器 URL。 如果你看到\*\*“Connection Failed”\*\*对话框(或应用始终停留在启动画面),请检查自定义服务器 URL。 #### [清除桌面默认服务器 URL](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%B8%85%E9%99%A4%E6%A1%8C%E9%9D%A2%E9%BB%98%E8%AE%A4%E6%9C%8D%E5%8A%A1%E5%99%A8-url) 在主页面上,点击服务器名称(带有状态指示点)以打开服务器选择器。在**默认服务器**部分,点击**清除**。 #### [从配置中移除 `server.port` / `server.hostname`](https://opencode.ai/docs/zh-cn/troubleshooting#%E4%BB%8E%E9%85%8D%E7%BD%AE%E4%B8%AD%E7%A7%BB%E9%99%A4-serverport--serverhostname) 如果你的 `opencode.json(c)` 包含 `server` 部分,请临时移除该部分并重新启动桌面应用。 #### [检查环境变量](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%A3%80%E6%9F%A5%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F) 如果你在环境中设置了 `OPENCODE_PORT`,桌面应用将尝试使用该端口作为本地服务器端口。 * 取消设置 `OPENCODE_PORT`(或选择一个空闲端口)并重新启动。 * * * ### [Linux: Wayland / X11 问题](https://opencode.ai/docs/zh-cn/troubleshooting#linux-wayland--x11-%E9%97%AE%E9%A2%98) 在 Linux 上,某些 Wayland 设置可能会导致窗口空白或合成器错误。 * 如果你使用 Wayland 且应用出现空白或崩溃,请尝试使用 `OC_ALLOW_WAYLAND=1` 启动。 * 如果情况变得更糟,请移除该设置并尝试在 X11 会话下启动。 * * * ### [Windows: WebView2 运行时](https://opencode.ai/docs/zh-cn/troubleshooting#windows-webview2-%E8%BF%90%E8%A1%8C%E6%97%B6) 在 Windows 上,OpenCode Desktop 需要 Microsoft Edge **WebView2 Runtime**。如果应用打开后是空白窗口或无法启动,请安装或更新 WebView2 后重试。 * * * ### [Windows: 常见性能问题](https://opencode.ai/docs/zh-cn/troubleshooting#windows-%E5%B8%B8%E8%A7%81%E6%80%A7%E8%83%BD%E9%97%AE%E9%A2%98) 如果你在 Windows 上遇到性能缓慢、文件访问问题或终端问题,请尝试使用 [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) 。WSL 提供了一个 Linux 环境,能更好地与 OpenCode 的功能兼容。 * * * ### [通知不显示](https://opencode.ai/docs/zh-cn/troubleshooting#%E9%80%9A%E7%9F%A5%E4%B8%8D%E6%98%BE%E7%A4%BA) OpenCode Desktop 仅在以下情况下显示系统通知: * 在操作系统设置中已为 OpenCode 启用通知,且 * 应用窗口未处于焦点状态。 * * * ### [重置桌面应用存储(最后手段)](https://opencode.ai/docs/zh-cn/troubleshooting#%E9%87%8D%E7%BD%AE%E6%A1%8C%E9%9D%A2%E5%BA%94%E7%94%A8%E5%AD%98%E5%82%A8%E6%9C%80%E5%90%8E%E6%89%8B%E6%AE%B5) 如果应用无法启动且你无法从 UI 内部清除设置,请重置桌面应用的保存状态。 1. 退出 OpenCode Desktop。 2. 找到并删除以下文件(它们位于 OpenCode Desktop 应用数据目录中): * `opencode.settings.dat`(桌面默认服务器 URL) * `opencode.global.dat` 和 `opencode.workspace.*.dat`(UI 状态,如最近的服务器/项目) 快速找到该目录: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support`(然后搜索上述文件名) * **Linux**: 在 `~/.local/share` 下搜索上述文件名 * **Windows**: 按 `WIN+R` -> `%APPDATA%`(然后搜索上述文件名) * * * [获取帮助](https://opencode.ai/docs/zh-cn/troubleshooting#%E8%8E%B7%E5%8F%96%E5%B8%AE%E5%8A%A9) -------------------------------------------------------------------------------------------- 如果你遇到 OpenCode 的问题: 1. **在 GitHub 上报告问题** 报告 Bug 或请求功能的最佳方式是通过我们的 GitHub 仓库: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) 在创建新 Issue 之前,请先搜索已有的 Issue,看看你的问题是否已被报告。 2. **加入我们的 Discord** 如需实时帮助和社区讨论,请加入我们的 Discord 服务器: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [常见问题](https://opencode.ai/docs/zh-cn/troubleshooting#%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) -------------------------------------------------------------------------------------------- 以下是一些常见问题及其解决方法。 * * * ### [OpenCode 无法启动](https://opencode.ai/docs/zh-cn/troubleshooting#opencode-%E6%97%A0%E6%B3%95%E5%90%AF%E5%8A%A8) 1. 检查日志中的错误消息 2. 尝试使用 `--print-logs` 运行以在终端中查看输出 3. 使用 `opencode upgrade` 确保你使用的是最新版本 * * * ### [身份验证问题](https://opencode.ai/docs/zh-cn/troubleshooting#%E8%BA%AB%E4%BB%BD%E9%AA%8C%E8%AF%81%E9%97%AE%E9%A2%98) 1. 尝试在 TUI 中使用 `/connect` 命令重新进行身份验证 2. 检查你的 API 密钥是否有效 3. 确保你的网络允许连接到提供商的 API * * * ### [模型不可用](https://opencode.ai/docs/zh-cn/troubleshooting#%E6%A8%A1%E5%9E%8B%E4%B8%8D%E5%8F%AF%E7%94%A8) 1. 检查你是否已通过提供商的身份验证 2. 验证配置中的模型名称是否正确 3. 某些模型可能需要特定的访问权限或订阅 如果你遇到 `ProviderModelNotFoundError`,很可能是在某处错误地引用了模型。 模型应按如下方式引用:`/` 示例: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` 要查看你有权访问哪些模型,请运行 `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/zh-cn/troubleshooting#provideriniterror) 如果你遇到 ProviderInitError,很可能是配置无效或已损坏。 要解决此问题: 1. 首先,按照[提供商指南](https://opencode.ai/docs/providers) 验证你的提供商是否已正确设置 2. 如果问题仍然存在,请尝试清除已存储的配置: rm -rf ~/.local/share/opencode 在 Windows 上,按 `WIN+R` 并删除:`%USERPROFILE%\.local\share\opencode` 3. 在 TUI 中使用 `/connect` 命令重新与提供商进行身份验证。 * * * ### [AI\_APICallError 和提供商包问题](https://opencode.ai/docs/zh-cn/troubleshooting#ai_apicallerror-%E5%92%8C%E6%8F%90%E4%BE%9B%E5%95%86%E5%8C%85%E9%97%AE%E9%A2%98) 如果你遇到 API 调用错误,可能是由于提供商包过期导致的。OpenCode 会根据需要动态安装提供商包(OpenAI、Anthropic、Google 等)并将它们缓存到本地。 要解决提供商包问题: 1. 清除提供商包缓存: rm -rf ~/.cache/opencode 在 Windows 上,按 `WIN+R` 并删除:`%USERPROFILE%\.cache\opencode` 2. 重新启动 OpenCode 以重新安装最新的提供商包 这将强制 OpenCode 下载最新版本的提供商包,通常可以解决模型参数和 API 变更带来的兼容性问题。 * * * ### [在 Linux 上复制/粘贴不可用](https://opencode.ai/docs/zh-cn/troubleshooting#%E5%9C%A8-linux-%E4%B8%8A%E5%A4%8D%E5%88%B6%E7%B2%98%E8%B4%B4%E4%B8%8D%E5%8F%AF%E7%94%A8) Linux 用户需要安装以下剪贴板工具之一,复制/粘贴功能才能正常工作: **对于 X11 系统:** apt install -y xclip# orapt install -y xsel **对于 Wayland 系统:** apt install -y wl-clipboard **对于无头环境:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 OpenCode 会检测你是否正在使用 Wayland 并优先使用 `wl-clipboard`,否则将按以下顺序尝试查找剪贴板工具:`xclip` 和 `xsel`。 --- # Custom Tools | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/custom-tools#_top) Custom Tools ============ Create tools the LLM can call in OpenCode. custom tool은 대화 중 LLM이 호출할 수 있도록 사용자가 직접 만든 함수입니다. `read`, `write`, `bash` 같은 OpenCode의 [built-in tools](https://opencode.ai/docs/tools) 와 함께 동작합니다. * * * [도구 만들기](https://opencode.ai/docs/ko/custom-tools#%EB%8F%84%EA%B5%AC-%EB%A7%8C%EB%93%A4%EA%B8%B0) -------------------------------------------------------------------------------------------------- tool은 **TypeScript** 또는 **JavaScript** 파일로 정의합니다. 다만 tool 정의에서 호출하는 스크립트는 **어떤 언어든** 사용할 수 있습니다. 즉, TypeScript/JavaScript는 tool 정의 자체에만 필요합니다. * * * ### [위치](https://opencode.ai/docs/ko/custom-tools#%EC%9C%84%EC%B9%98) tool은 다음 위치에 둘 수 있습니다. * 프로젝트의 `.opencode/tools/` 디렉토리(로컬) * `~/.config/opencode/tools/` 디렉토리(전역) * * * ### [구조](https://opencode.ai/docs/ko/custom-tools#%EA%B5%AC%EC%A1%B0) tool을 가장 쉽게 만드는 방법은 타입 안정성과 validation을 제공하는 `tool()` helper를 사용하는 것입니다. 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}` },}) **파일 이름**이 **tool 이름**이 됩니다. 위 예시는 `database` tool을 생성합니다. * * * #### [파일 하나에 여러 tool 정의](https://opencode.ai/docs/ko/custom-tools#%ED%8C%8C%EC%9D%BC-%ED%95%98%EB%82%98%EC%97%90-%EC%97%AC%EB%9F%AC-tool-%EC%A0%95%EC%9D%98) 하나의 파일에서 여러 tool을 export할 수도 있습니다. 각 export는 **별도의 tool**이 되며 이름은 **`_`** 형식을 사용합니다. 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 },}) 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 },}) 이 경우 `math_add`, `math_multiply` 두 tool이 생성됩니다. * * * #### [기본 도구와 이름 충돌](https://opencode.ai/docs/ko/custom-tools#%EA%B8%B0%EB%B3%B8-%EB%8F%84%EA%B5%AC%EC%99%80-%EC%9D%B4%EB%A6%84-%EC%B6%A9%EB%8F%8C) 커스텀 도구는 도구 이름으로 식별됩니다. 커스텀 도구가 기본 도구와 같은 이름을 사용하면 커스텀 도구가 우선순위를 갖습니다. 예를 들어, 이 파일은 기본 `bash` 도구를 대체합니다: import { tool } from "@opencode-ai/plugin" export default tool({ description: "Restricted bash wrapper", args: { command: tool.schema.string(), }, async execute(args) { return `blocked: ${args.command}` },}) * * * ### [인자](https://opencode.ai/docs/ko/custom-tools#%EC%9D%B8%EC%9E%90) 인자 타입은 `tool.schema`로 정의할 수 있습니다. `tool.schema`는 [Zod](https://zod.dev/) 기반입니다. args: { query: tool.schema.string().describe("SQL query to execute")} [Zod](https://zod.dev/) 를 직접 import해서 일반 객체를 반환하는 방식도 사용할 수 있습니다. 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](https://opencode.ai/docs/ko/custom-tools#context) tool은 현재 세션의 context 정보를 전달받습니다. 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}` },}) 세션 작업 디렉토리는 `context.directory`를 사용하세요. git worktree 루트는 `context.worktree`를 사용하세요. * * * [예시](https://opencode.ai/docs/ko/custom-tools#%EC%98%88%EC%8B%9C) ------------------------------------------------------------------ ### [Python으로 tool 작성](https://opencode.ai/docs/ko/custom-tools#python%EC%9C%BC%EB%A1%9C-tool-%EC%9E%91%EC%84%B1) tool은 원하는 언어로 작성할 수 있습니다. 아래는 Python으로 두 숫자를 더하는 예시입니다. 먼저 Python 스크립트로 tool을 만듭니다. import sys a = int(sys.argv[1])b = int(sys.argv[2])print(a + b) 그다음 이 스크립트를 호출하는 tool 정의를 만듭니다. 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() },}) 여기서는 Python 스크립트를 실행하기 위해 [`Bun.$`](https://bun.com/docs/runtime/shell) 유틸리티를 사용합니다. --- # Fehlerbehebung | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/troubleshooting#_top) Fehlerbehebung ============== Haeufige Probleme und schnelle Loesungen. Wenn OpenCode Probleme macht, starte mit Logs und lokal gespeicherten Daten auf der Festplatte. * * * [Logs](https://opencode.ai/docs/de/troubleshooting#logs) --------------------------------------------------------- Logdateien werden hier gespeichert: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: Druecke `WIN+R` und fuege ein: `%USERPROFILE%\.local\share\opencode\log` Dateinamen enthalten Zeitstempel (z. B. `2025-01-09T123456.log`) und es bleiben die letzten 10 Logs erhalten. Mit `--log-level` bekommst du detailliertere Diagnoseinfos, z. B. `opencode --log-level DEBUG`. * * * [Speicher](https://opencode.ai/docs/de/troubleshooting#speicher) ----------------------------------------------------------------- opencode speichert Sitzungs- und App-Daten auf der Festplatte unter: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: Druecke `WIN+R` und fuege ein: `%USERPROFILE%\.local\share\opencode` Dieses Verzeichnis enthaelt: * `auth.json` - Authentifizierungsdaten wie API-Keys und OAuth-Tokens * `log/` - Anwendungslogs * `project/` - Projektspezifische Daten wie Sitzungen und Nachrichten * In Git-Repositories unter `.//storage/` * Ohne Git unter `./global/storage/` * * * [Desktop-App](https://opencode.ai/docs/de/troubleshooting#desktop-app) ----------------------------------------------------------------------- OpenCode Desktop startet im Hintergrund einen lokalen OpenCode-Server (`opencode-cli`\-Sidecar). Viele Probleme kommen von fehlerhaften Plugins, kaputtem Cache oder falschen Server-Einstellungen. ### [Schnellchecks](https://opencode.ai/docs/de/troubleshooting#schnellchecks) * App komplett beenden und neu starten * Bei Fehlerbildschirm **Restart** klicken und Details kopieren * Nur macOS: `OpenCode`\-Menue -> **Reload Webview** (hilft bei leerer/eingefrorener UI) * * * ### [Plugins deaktivieren](https://opencode.ai/docs/de/troubleshooting#plugins-deaktivieren) Wenn die Desktop-App beim Start abstuerzt, haengt oder sich seltsam verhaelt, deaktiviere zunaechst Plugins. #### [Globale Konfiguration prüfen](https://opencode.ai/docs/de/troubleshooting#globale-konfiguration-pr%C3%BCfen) Oeffne deine globale Konfigurationsdatei und suche nach dem `plugin`\-Schluessel. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (oder `~/.config/opencode/opencode.json`) * **macOS/Linux** (aeltere Installationen): `~/.local/share/opencode/opencode.jsonc` * **Windows**: Druecke `WIN+R` und fuege ein: `%USERPROFILE%\.config\opencode\opencode.jsonc` Wenn du Plugins konfiguriert hast, deaktiviere sie voruebergehend, indem du den Schluessel entfernst oder auf ein leeres Array setzt: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Plugin-Verzeichnisse prüfen](https://opencode.ai/docs/de/troubleshooting#plugin-verzeichnisse-pr%C3%BCfen) OpenCode kann auch lokale Plugins von der Festplatte laden. Verschiebe diese voruebergehend (oder benenne den Ordner um) und starte die Desktop-App neu: * **Globale Plugins** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: Druecke `WIN+R` und fuege ein: `%USERPROFILE%\.config\opencode\plugins` * **Projekt-Plugins** (nur bei projektspezifischer Konfig) * `/.opencode/plugins/` Wenn die App wieder funktioniert, aktiviere Plugins nacheinander, um den Verursacher zu finden. * * * ### [Cache leeren](https://opencode.ai/docs/de/troubleshooting#cache-leeren) Wenn das Deaktivieren von Plugins nicht hilft (oder eine Plugin-Installation haengt), leere den Cache, damit OpenCode ihn neu aufbauen kann. 1. Beende OpenCode Desktop komplett. 2. Loesche das Cache-Verzeichnis: * **macOS**: Finder -> `Cmd+Shift+G` -> einfuegen: `~/.cache/opencode` * **Linux**: loesche `~/.cache/opencode` (oder fuehre aus: `rm -rf ~/.cache/opencode`) * **Windows**: Druecke `WIN+R` und fuege ein: `%USERPROFILE%\.cache\opencode` 3. Starte OpenCode Desktop neu. * * * ### [Server-Verbindungsprobleme beheben](https://opencode.ai/docs/de/troubleshooting#server-verbindungsprobleme-beheben) OpenCode Desktop kann entweder einen eigenen lokalen Server starten (Standard) oder sich mit einer konfigurierten Server-URL verbinden. Wenn du einen **“Connection Failed”**\-Dialog siehst (oder die App beim Splash-Screen haengen bleibt), pruefe auf eine benutzerdefinierte Server-URL. #### [Desktop-Standard-Server-URL löschen](https://opencode.ai/docs/de/troubleshooting#desktop-standard-server-url-l%C3%B6schen) Klicke im Startbildschirm auf den Servernamen (mit dem Statuspunkt), um die Serverauswahl zu oeffnen. Klicke im Bereich **Default server** auf **Clear**. #### [`server.port` / `server.hostname` aus Konfiguration entfernen](https://opencode.ai/docs/de/troubleshooting#serverport--serverhostname-aus-konfiguration-entfernen) Wenn deine `opencode.json(c)` einen `server`\-Abschnitt enthaelt, entferne ihn voruebergehend und starte die Desktop-App neu. #### [Umgebungsvariablen prüfen](https://opencode.ai/docs/de/troubleshooting#umgebungsvariablen-pr%C3%BCfen) Wenn du `OPENCODE_PORT` in deiner Umgebung gesetzt hast, versucht die Desktop-App diesen Port fuer den lokalen Server zu nutzen. * Setze `OPENCODE_PORT` zurueck (oder waehle einen freien Port) und starte neu. * * * ### [Linux: Wayland / X11-Probleme](https://opencode.ai/docs/de/troubleshooting#linux-wayland--x11-probleme) Unter Linux koennen manche Wayland-Setups leere Fenster oder Compositor-Fehler verursachen. * Wenn du Wayland nutzt und die App leer ist/abstuerzt, versuche den Start mit `OC_ALLOW_WAYLAND=1`. * Wenn das es verschlimmert, entferne es und versuche den Start in einer X11-Session. * * * ### [Windows: WebView2-Laufzeit](https://opencode.ai/docs/de/troubleshooting#windows-webview2-laufzeit) Unter Windows benoetigt OpenCode Desktop die Microsoft Edge **WebView2 Runtime**. Wenn die App ein leeres Fenster zeigt oder nicht startet, installiere/aktualisiere WebView2 und versuche es erneut. * * * ### [Windows: Allgemeine Performance-Probleme](https://opencode.ai/docs/de/troubleshooting#windows-allgemeine-performance-probleme) Wenn du langsame Performance, Dateizugriffsprobleme oder Terminal-Probleme unter Windows hast, versuche [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) . WSL bietet eine Linux-Umgebung, die nahtloser mit OpenCode-Features funktioniert. * * * ### [Benachrichtigungen werden nicht angezeigt](https://opencode.ai/docs/de/troubleshooting#benachrichtigungen-werden-nicht-angezeigt) OpenCode Desktop zeigt Systembenachrichtigungen nur wenn: * Benachrichtigungen fuer OpenCode in den OS-Einstellungen aktiviert sind, und * das App-Fenster nicht fokussiert ist. * * * ### [Desktop-App-Speicher zurücksetzen (letzter Ausweg)](https://opencode.ai/docs/de/troubleshooting#desktop-app-speicher-zur%C3%BCcksetzen-letzter-ausweg) Wenn die App nicht startet und du Einstellungen nicht in der UI loeschen kannst, setze den gespeicherten Zustand der Desktop-App zurueck. 1. Beende OpenCode Desktop. 2. Finde und loesche diese Dateien (im App-Data-Verzeichnis von OpenCode Desktop): * `opencode.settings.dat` (desktop default server URL) * `opencode.global.dat` und `opencode.workspace.*.dat` (UI state like recent servers/projects) So findest du das Verzeichnis schnell: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (dann suche nach den Dateinamen oben) * **Linux**: suche unter `~/.local/share` nach den Dateinamen oben * **Windows**: Druecke `WIN+R` -> `%APPDATA%` (dann suche nach den Dateinamen oben) * * * [Hilfe bekommen](https://opencode.ai/docs/de/troubleshooting#hilfe-bekommen) ----------------------------------------------------------------------------- Wenn du Probleme mit OpenCode hast: 1. **Probleme auf GitHub melden** Bugs und Feature-Wuensche meldest du am besten im GitHub-Repository: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Suche vor dem Erstellen nach bestehenden Issues, damit Duplikate vermieden werden. 2. **Unserem Discord beitreten** Fuer schnelle Hilfe und Austausch in der Community: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Haeufige Probleme](https://opencode.ai/docs/de/troubleshooting#haeufige-probleme) ----------------------------------------------------------------------------------- Hier sind typische Fehlerbilder und wie du sie loest. * * * ### [OpenCode startet nicht](https://opencode.ai/docs/de/troubleshooting#opencode-startet-nicht) 1. Pruefe die Logs auf Fehlermeldungen 2. Versuche den Start mit `--print-logs`, um Ausgaben im Terminal zu sehen 3. Stelle sicher, dass du die neueste Version hast: `opencode upgrade` * * * ### [Authentifizierungsprobleme](https://opencode.ai/docs/de/troubleshooting#authentifizierungsprobleme) 1. Versuche erneute Authentifizierung mit `/connect` in der TUI 2. Pruefe, ob deine API-Keys gueltig sind 3. Stelle sicher, dass dein Netzwerk Verbindungen zur Provider-API erlaubt * * * ### [Modell nicht verfügbar](https://opencode.ai/docs/de/troubleshooting#modell-nicht-verf%C3%BCgbar) 1. Pruefe, ob du dich beim Provider authentifiziert hast 2. Verifiziere, dass der Modellname in deiner Config korrekt ist 3. Manche Modelle erfordern speziellen Zugriff oder Abonnements Wenn du `ProviderModelNotFoundError` erhaeltst, referenzierst du ein Modell wahrscheinlich falsch. Modelle sollten so referenziert werden: `/` Beispiele: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` Um zu sehen, auf welche Modelle du Zugriff hast, fuehre `opencode models` aus. * * * ### [ProviderInitError](https://opencode.ai/docs/de/troubleshooting#provideriniterror) Wenn du einen ProviderInitError erhaeltst, hast du wahrscheinlich eine ungueltige oder korrupte Konfiguration. Zur Loesung: 1. Pruefe zuerst, ob dein Provider korrekt eingerichtet ist, gemaess dem [Provider-Guide](https://opencode.ai/docs/providers) 2. Wenn das Problem besteht, versuche deine gespeicherte Konfiguration zu loeschen: rm -rf ~/.local/share/opencode Unter Windows druecke `WIN+R` und loesche: `%USERPROFILE%\.local\share\opencode` 3. Authentifiziere dich erneut beim Provider mit dem `/connect`\-Befehl in der TUI. * * * ### [AI\_APICallError und Provider-Paket-Probleme](https://opencode.ai/docs/de/troubleshooting#ai_apicallerror-und-provider-paket-probleme) Wenn du API-Call-Fehler erhaeltst, kann das an veralteten Provider-Paketen liegen. opencode installiert Provider-Pakete (OpenAI, Anthropic, Google, etc.) dynamisch bei Bedarf und cached sie lokal. Um Provider-Paket-Probleme zu loesen: 1. Leere den Provider-Paket-Cache: rm -rf ~/.cache/opencode Unter Windows druecke `WIN+R` und loesche: `%USERPROFILE%\.cache\opencode` 2. Starte opencode neu, um die neuesten Provider-Pakete zu installieren Dies zwingt opencode, die neuesten Versionen der Provider-Pakete herunterzuladen, was oft Kompatibilitaetsprobleme mit Modellparametern und API-Aenderungen loest. * * * ### [Copy/Paste funktioniert nicht unter Linux](https://opencode.ai/docs/de/troubleshooting#copypaste-funktioniert-nicht-unter-linux) Linux-Nutzer muessen eines der folgenden Clipboard-Utilities installiert haben, damit Copy/Paste funktioniert: **Fuer X11-Systeme:** apt install -y xclip# orapt install -y xsel **Fuer Wayland-Systeme:** apt install -y wl-clipboard **Fuer Headless-Umgebungen:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode erkennt, ob du Wayland nutzt und bevorzugt `wl-clipboard`, sonst versucht es `xclip` und `xsel` (in dieser Reihenfolge). --- # Plugins | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/plugins#_top) Plugins ======= Écrivez vos propres plugins pour étendre OpenCode. Les plugins vous permettent d’étendre OpenCode en vous connectant à divers événements et en personnalisant le comportement. Vous pouvez créer des plugins pour ajouter de nouvelles fonctionnalités, intégrer des services externes ou modifier le comportement par défaut de OpenCode. Pour des exemples, consultez les [plugins](https://opencode.ai/docs/ecosystem#plugins) créés par la communauté. * * * [Utiliser un plugin](https://opencode.ai/docs/fr/plugins#utiliser-un-plugin) ----------------------------------------------------------------------------- Il existe deux manières de charger des plugins. * * * ### [À partir de fichiers locaux](https://opencode.ai/docs/fr/plugins#%C3%A0-partir-de-fichiers-locaux) Placez les fichiers JavaScript ou TypeScript dans le répertoire du plugin. * `.opencode/plugins/` - Plugins au niveau du projet * `~/.config/opencode/plugins/` - Plugins globaux Les fichiers de ces répertoires sont automatiquement chargés au démarrage. * * * ### [Depuis npm](https://opencode.ai/docs/fr/plugins#depuis-npm) Spécifiez les packages npm dans votre fichier de configuration. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Les packages npm scopés et standards sont pris en charge. Parcourez les plugins disponibles dans le [ecosystem](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Comment les plugins sont installés](https://opencode.ai/docs/fr/plugins#comment-les-plugins-sont-install%C3%A9s) Les **plugins npm** sont installés automatiquement à l’aide de Bun au démarrage. Les packages et leurs dépendances sont mis en cache dans `~/.cache/opencode/node_modules/`. Les **plugins locaux** sont chargés directement depuis le répertoire des plugins. Pour utiliser des packages externes, vous devez créer un `package.json` dans votre répertoire de configuration (voir [Dépendances](https://opencode.ai/docs/fr/plugins#dependencies) ), ou publier le plugin sur npm et [l’ajouter à votre config](https://opencode.ai/docs/config#plugins) . * * * ### [Ordre de chargement](https://opencode.ai/docs/fr/plugins#ordre-de-chargement) Les plugins sont chargés à partir de toutes les sources et tous les hooks s’exécutent dans l’ordre. L’ordre de chargement est le suivant : 1. Configuration globale (`~/.config/opencode/opencode.json`) 2. Configuration du projet (`opencode.json`) 3. Répertoire global des plugins (`~/.config/opencode/plugins/`) 4. Répertoire des plugins du projet (`.opencode/plugins/`) Les packages npm en double avec le même nom et la même version sont chargés une fois. Cependant, un plugin local et un plugin npm portant des noms similaires sont tous deux chargés séparément. * * * [Créer un plugin](https://opencode.ai/docs/fr/plugins#cr%C3%A9er-un-plugin) ---------------------------------------------------------------------------- Un plugin est un **module JavaScript/TypeScript** qui exporte une ou plusieurs fonctions de plugin. Chaque fonction reçoit un objet contextuel et renvoie un objet hooks. * * * ### [Dépendances](https://opencode.ai/docs/fr/plugins#d%C3%A9pendances) Les plugins locaux et les outils personnalisés peuvent utiliser des packages npm externes. Ajoutez un `package.json` à votre répertoire de configuration avec les dépendances dont vous avez besoin. { "dependencies": { "shescape": "^2.1.0" }} OpenCode exécute `bun install` au démarrage pour les installer. Vos plugins et outils peuvent ensuite les importer. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Structure de base](https://opencode.ai/docs/fr/plugins#structure-de-base) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} La fonction plugin reçoit : * `project` : informations sur le projet actuel. * `directory` : le répertoire de travail actuel. * `worktree` : le chemin de l’arbre de travail git. * `client` : un client SDK opencode pour interagir avec l’IA. * `$` : [shell API](https://bun.com/docs/runtime/shell) de Bun pour l’exécution de commandes. * * * ### [Prise en charge de TypeScript](https://opencode.ai/docs/fr/plugins#prise-en-charge-de-typescript) Pour les plugins TypeScript, vous pouvez importer des types à partir du package du plugin : import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Événements](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements) Les plugins peuvent s’abonner à des événements comme indiqué ci-dessous dans la section Exemples. Voici une liste des différents événements disponibles. #### [Événements de commande](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-de-commande) * `command.executed` #### [Événements de fichier](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-de-fichier) * `file.edited` * `file.watcher.updated` #### [Événements d’installation](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-dinstallation) * `installation.updated` #### [LSP Événements](https://opencode.ai/docs/fr/plugins#lsp-%C3%A9v%C3%A9nements) * `lsp.client.diagnostics` * `lsp.updated` #### [Événements de messages](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-de-messages) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Événements d’autorisation](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-dautorisation) * `permission.asked` * `permission.replied` #### [Événements du serveur](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-du-serveur) * `server.connected` #### [Événements de session](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-de-session) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Événements à faire](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-%C3%A0-faire) * `todo.updated` #### [Événements Shell](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-shell) * `shell.env` #### [Événements d’outils](https://opencode.ai/docs/fr/plugins#%C3%A9v%C3%A9nements-doutils) * `tool.execute.after` * `tool.execute.before` #### [TUI Événements](https://opencode.ai/docs/fr/plugins#tui-%C3%A9v%C3%A9nements) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Exemples](https://opencode.ai/docs/fr/plugins#exemples) --------------------------------------------------------- Voici quelques exemples de plugins que vous pouvez utiliser pour étendre opencode. * * * ### [Envoyer des notifications](https://opencode.ai/docs/fr/plugins#envoyer-des-notifications) Envoyez des notifications lorsque certains événements se produisent : 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"'` } }, }} Nous utilisons `osascript` pour exécuter AppleScript sur macOS. Ici, nous l’utilisons pour envoyer des notifications. * * * ### [Protection .env](https://opencode.ai/docs/fr/plugins#protection-env) Empêchez opencode de lire les fichiers `.env` : 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") } }, }} * * * ### [Injecter des variables d’environnement](https://opencode.ai/docs/fr/plugins#injecter-des-variables-denvironnement) Injectez des variables d’environnement dans toutes les exécutions du shell (outils d’IA et terminal utilisateur) : export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Outils personnalisés](https://opencode.ai/docs/fr/plugins#outils-personnalis%C3%A9s) Les plugins peuvent également ajouter des outils personnalisés à opencode : 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})` }, }), }, }} L’assistant `tool` crée un outil personnalisé que opencode peut appeler. Il prend une fonction de schéma Zod et renvoie une définition d’outil avec : * `description` : ce que fait l’outil * `args` : schéma Zod pour les arguments de l’outil * `execute` : Fonction qui s’exécute lorsque l’outil est appelé Vos outils personnalisés seront disponibles pour opencode aux côtés des outils intégrés. * * * ### [Journalisation](https://opencode.ai/docs/fr/plugins#journalisation) Utilisez `client.app.log()` au lieu de `console.log` pour la journalisation structurée : export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Niveaux : `debug`, `info`, `warn`, `error`. Voir la [documentation du SDK](https://opencode.ai/docs/sdk) pour plus de détails. * * * ### [Hooks de compactage](https://opencode.ai/docs/fr/plugins#hooks-de-compactage) Personnalisez le contexte inclus lorsqu’une session est compactée : 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`) }, }} Le hook `experimental.session.compacting` se déclenche avant que le LLM ne génère un résumé de continuation. Utilisez-le pour injecter un contexte spécifique au domaine que le prompt de compactage par défaut manquerait. Vous pouvez également remplacer entièrement le prompt de compactage en définissant `output.prompt` : 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Lorsque `output.prompt` est défini, il remplace complètement le prompt de compactage par défaut. Le tableau `output.context` est ignoré dans ce cas. --- # Scorciatoie | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/keybinds#_top) Scorciatoie =========== Personalizza le scorciatoie da tastiera. OpenCode ha una lista di scorciatoie che puoi personalizzare tramite `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Tasto leader](https://opencode.ai/docs/it/keybinds#tasto-leader) ------------------------------------------------------------------ OpenCode usa un tasto `leader` per la maggior parte delle scorciatoie. Questo evita conflitti nel terminale. Per impostazione predefinita, `ctrl+x` e il tasto leader e la maggior parte delle azioni richiede di premere prima il leader e poi la scorciatoia. Per esempio, per avviare una nuova sessione premi `ctrl+x` e poi `n`. Non sei obbligato a usare un tasto leader per le scorciatoie, ma lo consigliamo. * * * [Disabilitare una scorciatoia](https://opencode.ai/docs/it/keybinds#disabilitare-una-scorciatoia) -------------------------------------------------------------------------------------------------- Puoi disabilitare una scorciatoia aggiungendo la chiave in `tui.json` con valore “none”. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Scorciatoie del prompt desktop](https://opencode.ai/docs/it/keybinds#scorciatoie-del-prompt-desktop) ------------------------------------------------------------------------------------------------------ Il campo di input del prompt nell’app desktop di OpenCode supporta scorciatoie comuni in stile Readline/Emacs per modificare il testo. Sono integrate e al momento non configurabili tramite `opencode.json`. | Scorciatoia | Azione | | --- | --- | | `ctrl+a` | Vai all’inizio della riga corrente | | `ctrl+e` | Vai alla fine della riga corrente | | `ctrl+b` | Sposta il cursore indietro di un carattere | | `ctrl+f` | Sposta il cursore avanti di un carattere | | `alt+b` | Sposta il cursore indietro di una parola | | `alt+f` | Sposta il cursore avanti di una parola | | `ctrl+d` | Elimina il carattere sotto il cursore | | `ctrl+k` | Elimina fino alla fine della riga | | `ctrl+u` | Elimina fino all’inizio della riga | | `ctrl+w` | Elimina la parola precedente | | `alt+d` | Elimina la parola successiva | | `ctrl+t` | Scambia i caratteri | | `ctrl+g` | Annulla popover / interrompe la risposta | * * * [Shift+Enter](https://opencode.ai/docs/it/keybinds#shiftenter) --------------------------------------------------------------- Alcuni terminali non inviano di default i tasti modificatori insieme a Invio. Potrebbe essere necessario configurare il terminale per inviare `Shift+Enter` come sequenza di escape. ### [Windows Terminal](https://opencode.ai/docs/it/keybinds#windows-terminal) Apri il tuo `settings.json` in: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Aggiungi questo all’array `actions` a livello root: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Aggiungi questo all’array `keybindings` a livello root:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Salva il file e riavvia Windows Terminal oppure apri una nuova scheda. --- # Plugins | OpenCode [Skip to content](https://opencode.ai/docs/plugins#_top) Plugins ======= Write your own plugins to extend OpenCode. 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](https://opencode.ai/docs/ecosystem#plugins) created by the community. * * * [Use a plugin](https://opencode.ai/docs/plugins#use-a-plugin) -------------------------------------------------------------- There are two ways to load plugins. * * * ### [From local files](https://opencode.ai/docs/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](https://opencode.ai/docs/plugins#from-npm) Specify npm packages in your config file. { "$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](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [How plugins are installed](https://opencode.ai/docs/plugins#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](https://opencode.ai/docs/plugins#dependencies) ), or publish the plugin to npm and [add it to your config](https://opencode.ai/docs/config#plugins) . * * * ### [Load order](https://opencode.ai/docs/plugins#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](https://opencode.ai/docs/plugins#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](https://opencode.ai/docs/plugins#dependencies) Local plugins and custom tools can use external npm packages. Add a `package.json` to your config directory with the dependencies you need. { "dependencies": { "shescape": "^2.1.0" }} OpenCode runs `bun install` at startup to install these. Your plugins and tools can then import them. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Basic structure](https://opencode.ai/docs/plugins#basic-structure) 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](https://bun.com/docs/runtime/shell) for executing commands. * * * ### [TypeScript support](https://opencode.ai/docs/plugins#typescript-support) For TypeScript plugins, you can import types from the plugin package: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Events](https://opencode.ai/docs/plugins#events) Plugins can subscribe to events as seen below in the Examples section. Here is a list of the different events available. #### [Command Events](https://opencode.ai/docs/plugins#command-events) * `command.executed` #### [File Events](https://opencode.ai/docs/plugins#file-events) * `file.edited` * `file.watcher.updated` #### [Installation Events](https://opencode.ai/docs/plugins#installation-events) * `installation.updated` #### [LSP Events](https://opencode.ai/docs/plugins#lsp-events) * `lsp.client.diagnostics` * `lsp.updated` #### [Message Events](https://opencode.ai/docs/plugins#message-events) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Permission Events](https://opencode.ai/docs/plugins#permission-events) * `permission.asked` * `permission.replied` #### [Server Events](https://opencode.ai/docs/plugins#server-events) * `server.connected` #### [Session Events](https://opencode.ai/docs/plugins#session-events) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Todo Events](https://opencode.ai/docs/plugins#todo-events) * `todo.updated` #### [Shell Events](https://opencode.ai/docs/plugins#shell-events) * `shell.env` #### [Tool Events](https://opencode.ai/docs/plugins#tool-events) * `tool.execute.after` * `tool.execute.before` #### [TUI Events](https://opencode.ai/docs/plugins#tui-events) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Examples](https://opencode.ai/docs/plugins#examples) ------------------------------------------------------ Here are some examples of plugins you can use to extend opencode. * * * ### [Send notifications](https://opencode.ai/docs/plugins#send-notifications) Send notifications when certain events occur: 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. * * * ### [.env protection](https://opencode.ai/docs/plugins#env-protection) Prevent opencode from reading `.env` files: 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](https://opencode.ai/docs/plugins#inject-environment-variables) Inject environment variables into all shell execution (AI tools and user terminals): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Custom tools](https://opencode.ai/docs/plugins#custom-tools) Plugins can also add custom tools to opencode: 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. * * * ### [Logging](https://opencode.ai/docs/plugins#logging) Use `client.app.log()` instead of `console.log` for structured logging: 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](https://opencode.ai/docs/sdk) for details. * * * ### [Compaction hooks](https://opencode.ai/docs/plugins#compaction-hooks) Customize the context included when a session is compacted: 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`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. 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. --- # LSP Servers | OpenCode [Skip to content](https://opencode.ai/docs/lsp#_top) LSP Servers =========== OpenCode integrates with your LSP servers. OpenCode integrates with your Language Server Protocol (LSP) to help the LLM interact with your codebase. It uses diagnostics to provide feedback to the LLM. * * * [Built-in](https://opencode.ai/docs/lsp#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 | `.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 | | 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 servers are automatically enabled when one of the above file extensions are detected and the requirements are met. * * * [How It Works](https://opencode.ai/docs/lsp#how-it-works) ---------------------------------------------------------- When 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. * * * [Configure](https://opencode.ai/docs/lsp#configure) ---------------------------------------------------- You can customize LSP servers through the `lsp` section in your opencode config. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Each LSP server supports the following: | 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](https://opencode.ai/docs/lsp#environment-variables) Use the `env` property to set environment variables when starting the LSP server: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Initialization options](https://opencode.ai/docs/lsp#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: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Disabling LSP servers](https://opencode.ai/docs/lsp#disabling-lsp-servers) To disable **all** LSP servers globally, set `lsp` to `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} To disable a **specific** LSP server, set `disabled` to `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Custom LSP servers](https://opencode.ai/docs/lsp#custom-lsp-servers) You can add custom LSP servers by specifying the command and file extensions: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Additional Information](https://opencode.ai/docs/lsp#additional-information) ------------------------------------------------------------------------------ ### [PHP Intelephense](https://opencode.ai/docs/lsp#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. --- # TUI | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/tui#_top) TUI === Korzystanie z interfejsu użytkownika terminala opencode. opencode zapewnia interaktywny interfejs terminala lub TUI do pracy nad projektami za pomocą LLM. Uruchomienie opencode uruchamia TUI dla bieżącego katalogu. opencode Możesz też uruchomić go dla określonego katalogu roboczego. opencode /path/to/project Gdy znajdziesz się w TUI, możesz wyświetlić monit za pomocą komunikatu. Give me a quick summary of the codebase. * * * [Referencje plików](https://opencode.ai/docs/pl/tui#referencje-plik%C3%B3w) ---------------------------------------------------------------------------- Możesz odwoływać się do plików w swoich wiadomościach, używając `@`. Spowoduje to rozmyte wyszukiwanie plików w bieżącym katalogu roboczym. How is auth handled in @packages/functions/src/api/index.ts? Zawartość pliku jest automatycznie dodawana do rozmowy. * * * [Polecenia Bash](https://opencode.ai/docs/pl/tui#polecenia-bash) ----------------------------------------------------------------- Rozpocznij wiadomość od `!`, aby uruchomić polecenie shell. !ls -la Dane wyjściowe polecenia są dodawane do konwersacji jako wynik narzędzia. * * * [Komendy](https://opencode.ai/docs/pl/tui#komendy) --------------------------------------------------- Korzystając z TUI opencode, możesz wpisać `/`, po którym następuje nazwa polecenia, aby szybko wykonać działania. Na przykład: /help Większość poleceń ma również skrót klawiszowy wykorzystujący `ctrl+x` jako klucz wiodący, gdzie `ctrl+x` jest domyślnym klawiszem wiodącym. [Dowiedz się więcej](https://opencode.ai/docs/keybinds) . Oto wszystkie dostępne slash commands: * * * ### [connect](https://opencode.ai/docs/pl/tui#connect) Dodaj dostawcę do opencode. Umożliwia wybór dostępnych dostawców i dodanie ich kluczy API. /connect * * * ### [compact](https://opencode.ai/docs/pl/tui#compact) Kompaktuj bieżącą sesję. _Alias_: `/summarize` /compact **Keybind:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/pl/tui#details) Przełącz szczegóły wykonywania narzędzi. /details **Keybind:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/pl/tui#editor) Otwórz zewnętrzny edytor do tworzenia wiadomości. Używa edytora ustawionego w zmiennej środowiskowej `EDITOR`. [Dowiedz się więcej](https://opencode.ai/docs/pl/tui#editor-setup) . /editor **Keybind:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/pl/tui#exit) Zamknij opencode. _Aliasy_: `/quit`, `/q` /exit **Keybind:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/pl/tui#export) Wyeksportuj bieżącą rozmowę do Markdown i otwórz ją w domyślnym edytorze. Używa edytora ustawionego w zmiennej środowiskowej `EDITOR`. [Dowiedz się więcej](https://opencode.ai/docs/pl/tui#editor-setup) . /export **Keybind:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/pl/tui#help) Pokaż okno pomocy. /help **Keybind:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/pl/tui#init) Utwórz lub zaktualizuj plik `AGENTS.md`. [Dowiedz się więcej](https://opencode.ai/docs/rules) . /init **Keybind:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/pl/tui#models) Lista dostępnych modeli. /models **Keybind:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/pl/tui#new) Rozpocznij nową sesję. _Alias_: `/clear` /new **Keybind:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/pl/tui#redo) Ponów cofniętą wcześniej wiadomość. Dostępne tylko po użyciu `/undo`. Wewnętrznie używa Git do zarządzania zmianami plików. Więc Twój projekt \*\* musi be a Git repository\*\*. /redo **Keybind:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/pl/tui#sessions) Wyświetl listę i przełączaj się między sesjami. _Aliasy_: `/resume`, `/continue` /sessions **Keybind:** `ctrl+x l` * * * Udostępnij bieżącą sesję. [Dowiedz się więcej](https://opencode.ai/docs/share) . /share **Keybind:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/pl/tui#themes) Lista dostępnych motywów. /theme **Keybind:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/pl/tui#thinking) Przełącz widoczność bloków myślenia/rozumowania w rozmowie. Po włączeniu tej opcji można zobaczyć proces wnioskowania modelu w przypadku modeli obsługujących myślenie rozszerzone. /thinking * * * ### [undo](https://opencode.ai/docs/pl/tui#undo) Cofnij ostatnią wiadomość w rozmowie. Usuwa najnowszą wiadomość użytkownika, wszystkie kolejne odpowiedzi i wszelkie zmiany w plikach. Wewnętrznie używa Git do zarządzania zmianami plików. Więc Twój projekt \*\* musi be a Git repository\*\*. /undo **Keybind:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/pl/tui#unshare) Anuluj udostępnianie bieżącej sesji. [Dowiedz się więcej](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Konfiguracja edytora](https://opencode.ai/docs/pl/tui#konfiguracja-edytora) ----------------------------------------------------------------------------- Zarówno polecenia `/editor`, jak i `/export` korzystają z edytora określonego w zmiennej środowiskowej `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/pl/tui#tab-panel-81) * [Windows (CMD)](https://opencode.ai/docs/pl/tui#tab-panel-82) * [Windows (PowerShell)](https://opencode.ai/docs/pl/tui#tab-panel-83) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" Aby było to trwałe, dodaj to do swojego profilu shell; `~/.bashrc`, `~/.zshrc`, etc. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait Aby ustawić tę opcję na stałe, użyj opcji **Właściwości systemu** > **Środowisko Variables**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" Aby uczynić to trwałym, dodaj to do swojego profilu PowerShell. Popularne opcje edytora: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim editor * `vim` - Vim editor * `nano` - Nano editor * `notepad` - Windows Notepad * `subl` - Sublime Text Niektórzy edytory potrzebują argumentów wiersza poleceń, aby działać w trybie blokowania. Flaga `--wait` blokuje proces edytora aż do jego zamknięcia. * * * [Skonfiguruj](https://opencode.ai/docs/pl/tui#skonfiguruj) ----------------------------------------------------------- Możesz dostosować zachowanie TUI za pomocą pliku `tui.json` (lub `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Jest to oddzielny plik od `opencode.json`, który konfiguruje zachowanie serwera/runtime. ### [Opcje](https://opencode.ai/docs/pl/tui#opcje) * `theme` - Ustawia motyw interfejsu. [Dowiedz się więcej](https://opencode.ai/docs/themes) . * `keybinds` - Dostosowuje skróty klawiszowe. [Dowiedz się więcej](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` — Włącz przyspieszenie przewijania w stylu macOS, aby zapewnić płynne, naturalne przewijanie. Po włączeniu prędkość przewijania wzrasta wraz z szybkimi gestami przewijania i pozostaje precyzyjna w przypadku wolniejszych ruchów. **To ustawienie ma pierwszeństwo przed `scroll_speed` i zastępuje je, gdy jest włączone.** * `scroll_speed` - Kontroluje szybkość przewijania TUI podczas korzystania z poleceń przewijania (minimum: `0.001`, obsługuje wartości dziesiętne). Wartość domyślna to `3`. **Uwaga: jest to ignorowane, jeśli `scroll_acceleration.enabled` jest ustawione na `true`.** * `diff_style` - Steruje renderowaniem różnic. `"auto"` dostosowuje się do szerokości terminala, `"stacked"` zawsze pokazuje układ jednokolumnowy. Użyj `OPENCODE_TUI_CONFIG`, aby załadować niestandardową ścieżkę konfiguracji TUI. * * * [Personalizacja](https://opencode.ai/docs/pl/tui#personalizacja) ----------------------------------------------------------------- Za pomocą palety poleceń (`ctrl+x h` lub `/help`) można dostosować różne aspekty widoku TUI. Te ustawienia są zachowywane po ponownym uruchomieniu. * * * #### [Wyświetlanie nazwy użytkownika](https://opencode.ai/docs/pl/tui#wy%C5%9Bwietlanie-nazwy-u%C5%BCytkownika) Włącz lub wyłącz wyświetlanie Twojej nazwy użytkownika w wiadomościach na czacie. Dostęp do tego poprzez: * Paleta poleceń: Wyszukaj „nazwę użytkownika” lub „ukryj nazwę użytkownika” * Ustawienie zostanie zapamiętane automatycznie i będzie pamiętane podczas sesji TUI --- # TUI | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/tui#_top) TUI === 使用 OpenCode 終端機使用者介面。 OpenCode 提供了一個互動式終端機介面(TUI),用於配合 LLM 處理您的專案。 執行 OpenCode 即可啟動當前目錄的 TUI。 opencode 或者您可以為指定的工作目錄啟動它。 opencode /path/to/project 進入 TUI 後,您可以輸入訊息進行提示。 Give me a quick summary of the codebase. * * * [檔案參考](https://opencode.ai/docs/zh-tw/tui#%E6%AA%94%E6%A1%88%E5%8F%83%E8%80%83) -------------------------------------------------------------------------------- 您可以使用 `@` 在訊息中參考檔案。這會在當前工作目錄中進行模糊檔案搜尋。 How is auth handled in @packages/functions/src/api/index.ts? 檔案的內容會自動新增到對話中。 * * * [Bash 指令](https://opencode.ai/docs/zh-tw/tui#bash-%E6%8C%87%E4%BB%A4) ---------------------------------------------------------------------- 以 `!` 開頭的訊息會作為 shell 指令執行。 !ls -la 指令的輸出會作為工具結果新增到對話中。 * * * [指令](https://opencode.ai/docs/zh-tw/tui#%E6%8C%87%E4%BB%A4) ------------------------------------------------------------ 使用 OpenCode TUI 時,您可以輸入 `/` 後跟指令名稱來快速執行操作。例如: /help 大多數指令還支援以 `ctrl+x` 作為前導鍵的快速鍵,其中 `ctrl+x` 是預設前導鍵。[了解更多](https://opencode.ai/docs/keybinds) 。 以下是所有可用的斜線指令: * * * ### [connect](https://opencode.ai/docs/zh-tw/tui#connect) 將供應商新增到 OpenCode。允許您從可用的供應商中選擇並新增其 API 金鑰。 /connect * * * ### [compact](https://opencode.ai/docs/zh-tw/tui#compact) 壓縮當前工作階段。_別名_:`/summarize` /compact **快速鍵:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/zh-tw/tui#details) 切換工具執行詳情的顯示。 /details **快速鍵:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/zh-tw/tui#editor) 開啟外部編輯器來撰寫訊息。使用 `EDITOR` 環境變數中設定的編輯器。[了解更多](https://opencode.ai/docs/zh-tw/tui#editor-setup) 。 /editor **快速鍵:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/zh-tw/tui#exit) 退出 OpenCode。_別名_:`/quit`、`/q` /exit **快速鍵:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/zh-tw/tui#export) 將當前對話匯出為 Markdown 並在預設編輯器中開啟。使用 `EDITOR` 環境變數中設定的編輯器。[了解更多](https://opencode.ai/docs/zh-tw/tui#editor-setup) 。 /export **快速鍵:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/zh-tw/tui#help) 顯示說明對話框。 /help **快速鍵:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/zh-tw/tui#init) 建立或更新 `AGENTS.md` 檔案。[了解更多](https://opencode.ai/docs/rules) 。 /init **快速鍵:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/zh-tw/tui#models) 列出可用模型。 /models **快速鍵:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/zh-tw/tui#new) 開始新的工作階段。_別名_:`/clear` /new **快速鍵:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/zh-tw/tui#redo) 重做之前復原的訊息。僅在使用 `/undo` 後可用。 在內部,這使用 Git 來管理檔案變更。因此您的專案**需要是一個 Git 儲存庫**。 /redo **快速鍵:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/zh-tw/tui#sessions) 列出工作階段並在工作階段之間切換。_別名_:`/resume`、`/continue` /sessions **快速鍵:** `ctrl+x l` * * * 分享當前工作階段。[了解更多](https://opencode.ai/docs/share) 。 /share **快速鍵:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/zh-tw/tui#themes) 列出可用主題。 /theme **快速鍵:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/zh-tw/tui#thinking) 切換對話中思考/推理區塊的可見性。啟用後,您可以看到支援擴充思考的模型的推理過程。 /thinking * * * ### [undo](https://opencode.ai/docs/zh-tw/tui#undo) 復原對話中的最後一條訊息。移除最近的使用者訊息、所有後續回應以及所有檔案變更。 在內部,這使用 Git 來管理檔案變更。因此您的專案**需要是一個 Git 儲存庫**。 /undo **快速鍵:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/zh-tw/tui#unshare) 取消分享當前工作階段。[了解更多](https://opencode.ai/docs/share#un-sharing) 。 /unshare * * * [編輯器設定](https://opencode.ai/docs/zh-tw/tui#%E7%B7%A8%E8%BC%AF%E5%99%A8%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------------------------------------ `/editor` 和 `/export` 指令都使用 `EDITOR` 環境變數中指定的編輯器。 * [Linux/macOS](https://opencode.ai/docs/zh-tw/tui#tab-panel-123) * [Windows (CMD)](https://opencode.ai/docs/zh-tw/tui#tab-panel-124) * [Windows (PowerShell)](https://opencode.ai/docs/zh-tw/tui#tab-panel-125) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" 要使其永久生效,請將其新增到您的 shell 設定檔中; `~/.bashrc`、`~/.zshrc` 等。 set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait 要使其永久生效,請使用**系統內容** > **環境變數**。 $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" 要使其永久生效,請將其新增到您的 PowerShell 設定檔中。 常用的編輯器選項包括: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim 編輯器 * `vim` - Vim 編輯器 * `nano` - Nano 編輯器 * `notepad` - Notepad(Windows 記事本) * `subl` - Sublime Text 某些編輯器需要命令列參數才能以阻塞模式執行。`--wait` 旗標使編輯器程序阻塞直到關閉。 * * * [設定](https://opencode.ai/docs/zh-tw/tui#%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------ 您可以透過 `tui.json`(或 `tui.jsonc`)自訂 TUI 行為。 { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} 這與設定伺服器/執行時行為的 `opencode.json` 是分開的。 ### [選項](https://opencode.ai/docs/zh-tw/tui#%E9%81%B8%E9%A0%85) * `theme` - 設定您的 UI 主題。[了解更多](https://opencode.ai/docs/themes) 。 * `keybinds` - 自訂鍵盤快速鍵。[了解更多](https://opencode.ai/docs/keybinds) 。 * `scroll_acceleration.enabled` - 啟用 macOS 風格的捲動加速,實現平滑、自然的捲動體驗。啟用後,快速捲動時速度會增加,慢速移動時保持精確。**此設定優先於 `scroll_speed`,啟用時會覆蓋它。** * `scroll_speed` - 控制使用捲動指令時 TUI 的捲動速度(最小值:`0.001`,支援小數值)。預設為 `3`。**注意:如果 `scroll_acceleration.enabled` 設定為 `true`,則此設定會被忽略。** * `diff_style` - 控制差異呈現方式。`"auto"` 根據終端機寬度自適應,`"stacked"` 始終顯示單列。 使用 `OPENCODE_TUI_CONFIG` 載入自訂 TUI 設定路徑。 * * * [自訂](https://opencode.ai/docs/zh-tw/tui#%E8%87%AA%E8%A8%82) ------------------------------------------------------------ 您可以使用指令面板(`ctrl+x h` 或 `/help`)自訂 TUI 檢視的各個方面。這些設定在重新啟動後仍會保留。 * * * #### [使用者名稱顯示](https://opencode.ai/docs/zh-tw/tui#%E4%BD%BF%E7%94%A8%E8%80%85%E5%90%8D%E7%A8%B1%E9%A1%AF%E7%A4%BA) 切換您的使用者名稱是否顯示在聊天訊息中。透過以下方式存取: * 指令面板:搜尋「username」或「hide username」 * 該設定會自動儲存,並在各個 TUI 工作階段中保持記憶 --- # TUI | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/tui#_top) TUI === Bruke opencode-terminalbrukergrensesnittet. OpenCode gir et interaktivt terminalgrensesnitt (TUI) for å jobbe med prosjektene dine med en LLM. Å kjøre OpenCode starter TUI for gjeldende katalog. opencode Eller du kan starte den for en spesifikk arbeidskatalog. opencode /path/to/project Når du er i TUI, kan du stille den spørsmål med en prompt. Give me a quick summary of the codebase. * * * [Filreferanser](https://opencode.ai/docs/nb/tui#filreferanser) --------------------------------------------------------------- Du kan referere til filer i meldingene dine ved å bruke `@`. Dette gjør et fuzzy-filsøk i gjeldende arbeidskatalog. How is auth handled in @packages/functions/src/api/index.ts? Innholdet i filen legges automatisk til samtalen. * * * [Bash-kommandoer](https://opencode.ai/docs/nb/tui#bash-kommandoer) ------------------------------------------------------------------- Start en melding med `!` for å kjøre en skallkommando. !ls -la Utdataene fra kommandoen legges til samtalen som et verktøyresultat. * * * [Kommandoer](https://opencode.ai/docs/nb/tui#kommandoer) --------------------------------------------------------- Når du bruker OpenCode TUI, kan du skrive `/` etterfulgt av et kommandonavn for raskt å utføre handlinger. For eksempel: /help De fleste kommandoer har også tastebinding som bruker `ctrl+x` som leader-tast, der `ctrl+x` er standard leader-tast. [Finn ut mer](https://opencode.ai/docs/keybinds) . Her er alle tilgjengelige slash-kommandoer: * * * ### [connect](https://opencode.ai/docs/nb/tui#connect) Legg til en leverandør til OpenCode. Lar deg velge fra tilgjengelige leverandører og legge til deres API-nøkler. /connect * * * ### [compact](https://opencode.ai/docs/nb/tui#compact) Komprimer gjeldende økt. _Alias_: `/summarize` /compact **Nøkkelbinding:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/nb/tui#details) Veksle visning av verktøydetaljer. /details **Nøkkelbinding:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/nb/tui#editor) Åpne eksternt tekstredigeringsprogram for å skrive meldinger. Bruker redigeringssettet i miljøvariabelen `EDITOR`. [Finn ut mer](https://opencode.ai/docs/nb/tui#editor-setup) . /editor **Nøkkelbinding:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/nb/tui#exit) Avslutt OpenCode. _Aliaser_: `/quit`, `/q` /exit **Nøkkelbinding:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/nb/tui#export) Eksporter gjeldende samtale til Markdown og åpne i standardredigeringsprogrammet. Bruker redigeringssettet i miljøvariabelen `EDITOR`. [Finn ut mer](https://opencode.ai/docs/nb/tui#editor-setup) . /export **Nøkkelbinding:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/nb/tui#help) Vis hjelpedialogen. /help **Nøkkelbinding:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/nb/tui#init) Opprett eller oppdater `AGENTS.md`\-fil. [Finn ut mer](https://opencode.ai/docs/rules) . /init **Nøkkelbinding:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/nb/tui#models) Liste over tilgjengelige modeller. /models **Nøkkelbinding:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/nb/tui#new) Start en ny økt. _Alias_: `/clear` /new **Nøkkelbinding:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/nb/tui#redo) Gjenta en tidligere angret melding. Kun tilgjengelig etter bruk av `/undo`. Internt bruker dette Git til å administrere filendringene. Så ditt prosjekt **må være et Git-repo**. /redo **Nøkkelbinding:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/nb/tui#sessions) List opp og bytt mellom økter. _Aliaser_: `/resume`, `/continue` /sessions **Nøkkelbinding:** `ctrl+x l` * * * Del gjeldende økt. [Finn ut mer](https://opencode.ai/docs/share) . /share **Nøkkelbinding:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/nb/tui#themes) Liste over tilgjengelige temaer. /themes **Nøkkelbinding:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/nb/tui#thinking) Veksle mellom synligheten av tenke-/resonneringsblokker i samtalen. Når den er aktivert, kan du se modellens resonneringsprosess for modeller som støtter utvidet tenkning. /thinking * * * ### [undo](https://opencode.ai/docs/nb/tui#undo) Angre siste melding i samtalen. Fjerner den siste brukermeldingen, alle påfølgende svar og eventuelle filendringer. Internt bruker dette Git til å administrere filendringene. Så ditt prosjekt **må være et Git-repo**. /undo **Nøkkelbinding:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/nb/tui#unshare) Opphev deling av gjeldende økt. [Finn ut mer](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Oppsett av editor](https://opencode.ai/docs/nb/tui#oppsett-av-editor) ----------------------------------------------------------------------- Både kommandoene `/editor` og `/export` bruker editoren som er spesifisert i miljøvariabelen `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/nb/tui#tab-panel-74) * [Windows (CMD)](https://opencode.ai/docs/nb/tui#tab-panel-75) * [Windows (PowerShell)](https://opencode.ai/docs/nb/tui#tab-panel-76) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" For å gjøre det permanent, legg dette til i shell-profilen din; `~/.bashrc`, `~/.zshrc` osv. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait For å gjøre det permanent, bruk **Systemegenskaper** > **Miljø Variabler**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" For å gjøre det permanent, legg dette til i PowerShell-profilen din. Populære editor-alternativer inkluderer: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim-editor * `vim` - Vim editor * `nano` - Nano-editor * `notepad` - Windows Notisblokk * `subl` - Sublime Text Noen editorer trenger kommandolinjeargumenter for å kjøre i blokkeringsmodus. `--wait`\-flagget gjør at editor-prosessen blokkeres til den lukkes. * * * [Konfigurasjon](https://opencode.ai/docs/nb/tui#konfigurasjon) --------------------------------------------------------------- Du kan tilpasse TUI-oppførselen gjennom `tui.json` (eller `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Dette er atskilt fra `opencode.json`, som konfigurerer server-/kjøretidsoppførsel. ### [Alternativer](https://opencode.ai/docs/nb/tui#alternativer) * `theme` - Angir UI-temaet ditt. [Finn ut mer](https://opencode.ai/docs/themes) . * `keybinds` - Tilpasser hurtigtaster. [Finn ut mer](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Aktiver rulleakselerasjon i macOS-stil for jevn, naturlig rulling. Når aktivert, øker rullehastigheten med raske rullebevegelser og forblir presis for langsommere bevegelser. **Denne innstillingen har forrang over `scroll_speed` og overstyrer den når den er aktivert.** * `scroll_speed` - Styrer hvor raskt TUI ruller når du bruker rullekommandoer (minimum: `0.001`, støtter desimalverdier). Standard er `3`. **Merk: Dette ignoreres hvis `scroll_acceleration.enabled` er satt til `true`.** * `diff_style` - Kontrollerer diff-gjengivelse. `"auto"` tilpasser seg terminalbredden, `"stacked"` viser alltid en enkeltkolonneoppsett. Bruk `OPENCODE_TUI_CONFIG` for å laste en egendefinert TUI-konfigurasjonsbane. * * * [Tilpasning](https://opencode.ai/docs/nb/tui#tilpasning) --------------------------------------------------------- Du kan tilpasse ulike aspekter av TUI-visningen ved å bruke kommandopaletten (`ctrl+x h` eller `/help`). Disse innstillingene vedvarer ved omstarter. * * * #### [Visning av brukernavn](https://opencode.ai/docs/nb/tui#visning-av-brukernavn) Veksle om brukernavnet ditt vises i chat-meldinger. Få tilgang til dette gjennom: * Kommandopalett: Søk etter “brukernavn” eller “skjul brukernavn” * Innstillingen vedvarer automatisk og vil bli husket over TUI økter --- # TUI | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/tui#_top) TUI === Arbeite mit OpenCode in der Terminal-Oberflaeche. OpenCode bietet eine interaktive Terminaloberflaeche (TUI), um mit einem LLM an deinen Projekten zu arbeiten. Ohne weitere Argumente startet OpenCode die TUI im aktuellen Verzeichnis. opencode Oder du startest sie fuer ein bestimmtes Arbeitsverzeichnis. opencode /path/to/project In der TUI kannst du direkt mit einer Nachricht prompten. Give me a quick summary of the codebase. * * * [Datei-Referenzen](https://opencode.ai/docs/de/tui#datei-referenzen) --------------------------------------------------------------------- Mit `@` kannst du Dateien in Nachrichten referenzieren. Dabei wird im aktuellen Verzeichnis eine unscharfe Dateisuche genutzt. How is auth handled in @packages/functions/src/api/index.ts? Der Dateiinhalt wird automatisch zur Unterhaltung hinzugefuegt. * * * [Bash-Befehle](https://opencode.ai/docs/de/tui#bash-befehle) ------------------------------------------------------------- Beginne eine Nachricht mit `!`, um einen Shell-Befehl auszufuehren. !ls -la Die Ausgabe landet als Tool-Ergebnis in der Unterhaltung. * * * [Befehle](https://opencode.ai/docs/de/tui#befehle) --------------------------------------------------- In der OpenCode-TUI kannst du `/` plus Befehlsnamen eingeben, um Aktionen schnell auszufuehren. Zum Beispiel: /help Viele Befehle haben auch Tastenkombinationen mit `ctrl+x` als Leader-Key. [Mehr dazu](https://opencode.ai/docs/keybinds) . Hier sind alle verfuegbaren Slash-Commands: * * * ### [connect](https://opencode.ai/docs/de/tui#connect) Fuegt einen Provider zu OpenCode hinzu. Erlaubt die Auswahl aus verfuegbaren Providern und das Hinzufuegen ihrer API-Keys. /connect * * * ### [compact](https://opencode.ai/docs/de/tui#compact) Kompaktiert die aktuelle Session. _Alias_: `/summarize` /compact **Keybind:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/de/tui#details) Schaltet Tool-Ausfuehrungsdetails um. /details **Keybind:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/de/tui#editor) Oeffnet externen Editor zum Verfassen von Nachrichten. Nutzt den in der `EDITOR`\-Umgebungsvariable gesetzten Editor. [Mehr dazu](https://opencode.ai/docs/de/tui#editor-setup) . /editor **Keybind:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/de/tui#exit) Beendet OpenCode. _Aliase_: `/quit`, `/q` /exit **Keybind:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/de/tui#export) Exportiert die aktuelle Unterhaltung als Markdown und oeffnet sie in deinem Standard-Editor. Nutzt den in der `EDITOR`\-Umgebungsvariable gesetzten Editor. [Mehr dazu](https://opencode.ai/docs/de/tui#editor-setup) . /export **Keybind:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/de/tui#help) Zeigt den Hilfedialog. /help **Keybind:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/de/tui#init) Erstellt oder aktualisiert die `AGENTS.md`\-Datei. [Mehr dazu](https://opencode.ai/docs/rules) . /init **Keybind:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/de/tui#models) Listet verfuegbare Modelle. /models **Keybind:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/de/tui#new) Startet eine neue Session. _Alias_: `/clear` /new **Keybind:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/de/tui#redo) Wiederholt eine zuvor rueckgaengig gemachte Nachricht. Nur verfuegbar nach Verwendung von `/undo`. Intern nutzt dies Git, um die Dateiaenderungen zu verwalten. Dein Projekt muss also **ein Git-Repository sein**. /redo **Keybind:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/de/tui#sessions) Listet Sessions und wechselt zwischen ihnen. _Aliase_: `/resume`, `/continue` /sessions **Keybind:** `ctrl+x l` * * * Teilt die aktuelle Session. [Mehr dazu](https://opencode.ai/docs/share) . /share **Keybind:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/de/tui#themes) Listet verfuegbare Themes. /theme **Keybind:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/de/tui#thinking) Schaltet die Sichtbarkeit von Thinking/Reasoning-Bloecken in der Unterhaltung um. Wenn aktiviert, kannst du den Denkprozess des Modells sehen (bei Modellen, die das unterstuetzen). /thinking * * * ### [undo](https://opencode.ai/docs/de/tui#undo) Macht die letzte Nachricht in der Unterhaltung rueckgaengig. Entfernt die letzte Benutzernachricht, alle folgenden Antworten und alle Dateiaenderungen. Intern nutzt dies Git, um die Dateiaenderungen zu verwalten. Dein Projekt muss also **ein Git-Repository sein**. /undo **Keybind:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/de/tui#unshare) Hebt das Teilen der aktuellen Session auf. [Mehr dazu](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Editor-Einrichtung](https://opencode.ai/docs/de/tui#editor-einrichtung) ------------------------------------------------------------------------- Sowohl `/editor` als auch `/export` nutzen den in deiner `EDITOR`\-Umgebungsvariable spezifizierten Editor. * [Linux/macOS](https://opencode.ai/docs/de/tui#tab-panel-32) * [Windows (CMD)](https://opencode.ai/docs/de/tui#tab-panel-33) * [Windows (PowerShell)](https://opencode.ai/docs/de/tui#tab-panel-34) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" Um es dauerhaft zu machen, fuege dies zu deinem Shell-Profil hinzu; `~/.bashrc`, `~/.zshrc`, etc. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait Um es dauerhaft zu machen, nutze **Systemeigenschaften** > **Umgebungsvariablen**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" Um es dauerhaft zu machen, fuege dies zu deinem PowerShell-Profil hinzu. Beliebte Editoren sind: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim * `vim` - Vim * `nano` - Nano * `notepad` - Windows Notepad * `subl` - Sublime Text Einige Editoren benoetigen Befehlszeilenargumente, um im blockierenden Modus zu laufen. Das `--wait`\-Flag sorgt dafuer, dass der Editor-Prozess blockiert, bis er geschlossen wird. * * * [Konfiguration](https://opencode.ai/docs/de/tui#konfiguration) --------------------------------------------------------------- Du kannst das Verhalten der TUI ueber die Datei `tui.json` (oder `tui.jsonc`) anpassen. { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Dies ist getrennt von `opencode.json`, welche das Server-/Runtime-Verhalten konfiguriert. ### [Optionen](https://opencode.ai/docs/de/tui#optionen) * `theme` - Setzt dein UI-Theme. [Mehr dazu](https://opencode.ai/docs/themes) . * `keybinds` - Passt Tastenkombinationen an. [Mehr dazu](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Aktiviert Scroll-Beschleunigung im macOS-Stil fuer weiches, natuerliches Scrollen. Wenn aktiviert, erhoeht sich die Scroll-Geschwindigkeit bei schnellen Gesten und bleibt praezise bei langsamen Bewegungen. **Diese Einstellung hat Vorrang vor `scroll_speed` und ueberschreibt es, wenn aktiviert.** * `scroll_speed` - Steuert, wie schnell die TUI scrollt (Minimum: `0.001`, unterstuetzt Dezimalwerte). Standard ist `3`. **Hinweis: Wird ignoriert, wenn `scroll_acceleration.enabled` auf `true` gesetzt ist.** * `diff_style` - Steuert die Diff-Darstellung. `"auto"` passt sich der Terminalbreite an, `"stacked"` zeigt immer ein einspaltiges Layout. Verwende `OPENCODE_TUI_CONFIG`, um einen benutzerdefinierten TUI-Konfigurationspfad zu laden. * * * [Anpassung](https://opencode.ai/docs/de/tui#anpassung) ------------------------------------------------------- Du kannst verschiedene Aspekte der TUI-Ansicht ueber die Befehlspalette (`ctrl+x h` oder `/help`) anpassen. Diese Einstellungen bleiben ueber Neustarts hinweg erhalten. * * * #### [Benutzername-Anzeige](https://opencode.ai/docs/de/tui#benutzername-anzeige) Schaltet um, ob dein Benutzername in Chat-Nachrichten erscheint. Zugriff hierueber: * Befehlspalette: Suche nach “username” oder “hide username” * Die Einstellung wird automatisch gespeichert und bleibt ueber TUI-Sessions hinweg erhalten. --- # TUI | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/tui#_top) TUI === Использование TUI opencode. opencode предоставляет интерактивный terminal интерфейс или TUI для работы над вашими проектами с помощью LLM. Запуск opencode запускает TUI для текущего каталога. opencode Или вы можете запустить его для определенного рабочего каталога. opencode /path/to/project Как только вы окажетесь в TUI, вы можете запросить его с помощью сообщения. Give me a quick summary of the codebase. * * * [Ссылки на файлы](https://opencode.ai/docs/ru/tui#%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8-%D0%BD%D0%B0-%D1%84%D0%B0%D0%B9%D0%BB%D1%8B) ------------------------------------------------------------------------------------------------------------------------------------ Вы можете ссылаться на файлы в своих сообщениях, используя `@`. Это выполняет нечеткий поиск файлов в текущем рабочем каталоге. How is auth handled in @packages/functions/src/api/index.ts? Содержимое файла добавляется в беседу автоматически. * * * [Bash-команды](https://opencode.ai/docs/ru/tui#bash-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D1%8B) ------------------------------------------------------------------------------------------------ Начните сообщение с `!`, чтобы запустить shell-команду. !ls -la Вывод команды добавляется в диалог как результат работы инструмента. * * * [Команды](https://opencode.ai/docs/ru/tui#%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D1%8B) -------------------------------------------------------------------------------------- При использовании opencode TUI вы можете ввести `/`, а затем имя команды, чтобы быстро выполнить действия. Например: /help Большинство команд также имеют привязку клавиш с использованием `ctrl+x` в качестве ведущей клавиши, где `ctrl+x` — это ведущая клавиша по умолчанию. [Подробнее](https://opencode.ai/docs/keybinds) . Вот все доступные слэш-команды: * * * ### [connect](https://opencode.ai/docs/ru/tui#connect) Добавьте провайдера в opencode. Позволяет выбирать из доступных поставщиков и добавлять их ключи API. /connect * * * ### [compact](https://opencode.ai/docs/ru/tui#compact) Сжать текущий сеанс. _Псевдоним_: `/summarize` /compact **Привязка клавиш:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/ru/tui#details) Переключить детали выполнения инструмента. /details **Привязка клавиш:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/ru/tui#editor) Открыть внешний редактор для составления сообщений. Использует редактор, установленный в переменной среды `EDITOR`. [Подробнее](https://opencode.ai/docs/ru/tui#editor-setup) . /editor **Привязка клавиш:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/ru/tui#exit) Выйдите из opencode. _Псевдонимы_: `/quit`, `/q` /exit **Привязка клавиш:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/ru/tui#export) Экспортируйте текущий разговор в Markdown и откройте его в редакторе по умолчанию. Использует редактор, установленный в переменной среды `EDITOR`. [Подробнее](https://opencode.ai/docs/ru/tui#editor-setup) . /export **Привязка клавиш:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/ru/tui#help) Показать диалоговое окно помощи. /help **Привязка клавиш:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/ru/tui#init) Создайте или обновите файл `AGENTS.md`. [Подробнее](https://opencode.ai/docs/rules) . /init **Привязка клавиш:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/ru/tui#models) Перечислите доступные модели. /models **Привязка клавиш:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/ru/tui#new) Начать новый сеанс. _Псевдоним_: `/clear` /new **Привязка клавиш:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/ru/tui#redo) Повторить ранее отмененное сообщение. Доступно только после использования `/undo`. Внутри это использует Git для управления изменениями файлов. Итак, ваш проект \*\* должен быть репозиторием Git\*\*. /redo **Привязка клавиш:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/ru/tui#sessions) Составляйте список и переключайтесь между сеансами. _Псевдонимы_: `/resume`, `/continue` /sessions **Привязка клавиш:** `ctrl+x l` * * * Поделиться текущим сеансом. [Подробнее](https://opencode.ai/docs/share) . /share **Привязка клавиш:** `ctrl+x s` * * * ### [theme](https://opencode.ai/docs/ru/tui#theme) Список доступных тем. /theme **Привязка клавиш:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/ru/tui#thinking) Переключить видимость блоков мышления/рассуждения в разговоре. Если этот параметр включен, вы можете увидеть процесс рассуждения модели для моделей, поддерживающих расширенное мышление. /thinking * * * ### [undo](https://opencode.ai/docs/ru/tui#undo) Отменить последнее сообщение в разговоре. Удаляет самое последнее сообщение пользователя, все последующие ответы и любые изменения файлов. Внутри это использует Git для управления изменениями файлов. Итак, ваш проект \*\* должен быть репозиторием Git\*\*. /undo **Привязка клавиш:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/ru/tui#unshare) Отменить общий доступ к текущему сеансу. [Подробнее](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Настройка редактора](https://opencode.ai/docs/ru/tui#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0-%D1%80%D0%B5%D0%B4%D0%B0%D0%BA%D1%82%D0%BE%D1%80%D0%B0) --------------------------------------------------------------------------------------------------------------------------------------------------------------------- Команды `/editor` и `/export` используют редактор, указанный в переменной среды `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/ru/tui#tab-panel-95) * [Windows (CMD)](https://opencode.ai/docs/ru/tui#tab-panel-96) * [Windows (PowerShell)](https://opencode.ai/docs/ru/tui#tab-panel-97) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" Чтобы сделать его постоянным, добавьте это в свой профиль shell; `~/.bashrc`, `~/.zshrc` и т. д. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait Чтобы сделать его постоянным, используйте **Свойства системы** > **Среда Переменные**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" Чтобы сделать его постоянным, добавьте его в свой профиль PowerShell. Популярные варианты редактора включают в себя: * `code` — VS Code * `cursor` — Cursor * `windsurf` - Windsurf * `nvim` - Редактор Neovim * `vim` — редактор Vim * `nano` — Нано-редактор * `notepad` — Блокнот Windows * `subl` — Sublime Text Некоторым редакторам для работы в режиме блокировки необходимы CLI-аргументы. Флаг `--wait` блокирует процесс редактора до его закрытия. * * * [Настройка](https://opencode.ai/docs/ru/tui#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0) ---------------------------------------------------------------------------------------------------- Вы можете настроить поведение TUI через `tui.json` (или `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Это отдельный файл от `opencode.json`, который настраивает поведение сервера/выполнения. ### [Параметры](https://opencode.ai/docs/ru/tui#%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B) * `theme` — Устанавливает тему пользовательского интерфейса. [Подробнее](https://opencode.ai/docs/themes) . * `keybinds` — Настраивает сочетания клавиш. [Подробнее](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` — включите ускорение прокрутки в стиле macOS для плавной и естественной прокрутки. Если этот параметр включен, скорость прокрутки увеличивается при быстрой прокрутке и остается точной при более медленных движениях. **Этот параметр имеет приоритет над `scroll_speed` и переопределяет его, если он включен.** * `scroll_speed` — контролирует скорость прокрутки TUI при использовании команд прокрутки (минимум: `0.001`, поддерживает десятичные значения). По умолчанию `3`. **Примечание. Это игнорируется, если для `scroll_acceleration.enabled` установлено значение `true`.** * `diff_style` — Управляет отображением различий. `"auto"` адаптируется к ширине терминала, `"stacked"` всегда показывает одноколоночный макет. Используйте `OPENCODE_TUI_CONFIG` для загрузки пользовательского пути конфигурации TUI. * * * [Кастомизация](https://opencode.ai/docs/ru/tui#%D0%BA%D0%B0%D1%81%D1%82%D0%BE%D0%BC%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F) ------------------------------------------------------------------------------------------------------------------------- Вы можете настроить различные аспекты представления TUI, используя палитру команд (`ctrl+x h` или `/help`). Эти настройки сохраняются после перезапуска. * * * #### [Отображение имени пользователя](https://opencode.ai/docs/ru/tui#%D0%BE%D1%82%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B8%D0%BC%D0%B5%D0%BD%D0%B8-%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F) Включите, будет ли ваше имя пользователя отображаться в сообщениях чата. Доступ к этому через: * Палитра команд: поиск «имя пользователя» или «скрыть имя пользователя». * Настройка сохраняется автоматически и будет запоминаться во время сеансов TUI. --- # TUI | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/tui#_top) TUI === استخدام واجهة المستخدم TUI في OpenCode. يوفّر OpenCode واجهة terminal تفاعلية (TUI) للعمل على مشاريعك باستخدام LLM. يؤدي تشغيل OpenCode إلى بدء واجهة TUI للدليل الحالي. opencode أو يمكنك تشغيلها لدليل عمل محدد. opencode /path/to/project بعد الدخول إلى واجهة TUI، يمكنك إرسال رسالة كطلب. Give me a quick summary of the codebase. * * * [مراجع الملفات](https://opencode.ai/docs/ar/tui#%D9%85%D8%B1%D8%A7%D8%AC%D8%B9-%D8%A7%D9%84%D9%85%D9%84%D9%81%D8%A7%D8%AA) --------------------------------------------------------------------------------------------------------------------------- يمكنك الإشارة إلى الملفات في رسائلك باستخدام `@`. يُجري ذلك بحثا ضبابيا عن الملفات ضمن دليل العمل الحالي. How is auth handled in @packages/functions/src/api/index.ts? تُضاف محتويات الملف إلى المحادثة تلقائيا. * * * [أوامر Bash](https://opencode.ai/docs/ar/tui#%D8%A3%D9%88%D8%A7%D9%85%D8%B1-bash) ---------------------------------------------------------------------------------- ابدأ الرسالة بـ `!` لتشغيل أمر في shell. !ls -la يُضاف خرج الأمر إلى المحادثة كنتيجة أداة. * * * [الأوامر](https://opencode.ai/docs/ar/tui#%D8%A7%D9%84%D8%A3%D9%88%D8%A7%D9%85%D8%B1) -------------------------------------------------------------------------------------- عند استخدام واجهة OpenCode في terminal، يمكنك كتابة `/` متبوعة باسم أمر لتنفيذ الإجراءات بسرعة. مثلا: /help تملك معظم الأوامر أيضا اختصارا باستخدام `ctrl+x` كمفتاح قائد، حيث إن `ctrl+x` هو المفتاح القائد الافتراضي. [اعرف المزيد](https://opencode.ai/docs/keybinds) . فيما يلي جميع أوامر الشرطة المائلة المتاحة: * * * ### [connect](https://opencode.ai/docs/ar/tui#connect) أضف موفّرا إلى OpenCode. يتيح لك اختيار أحد الموفّرين المتاحين وإضافة مفاتيح API الخاصة بهم. /connect * * * ### [compact](https://opencode.ai/docs/ar/tui#compact) قم بضغط الجلسة الحالية. _الاسم المستعار_: `/summarize` /compact **اختصار لوحة المفاتيح:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/ar/tui#details) بدّل عرض تفاصيل تنفيذ الأدوات. /details **اختصار لوحة المفاتيح:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/ar/tui#editor) افتح محررا خارجيا لكتابة الرسائل. يستخدم المحرر المحدد في متغير البيئة `EDITOR`. [اعرف المزيد](https://opencode.ai/docs/ar/tui#editor-setup) . /editor **اختصار لوحة المفاتيح:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/ar/tui#exit) اخرج من OpenCode. _الأسماء المستعارة_: `/quit`, `/q` /exit **اختصار لوحة المفاتيح:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/ar/tui#export) صدّر المحادثة الحالية إلى Markdown وافتحها في المحرر الافتراضي لديك. يستخدم المحرر المحدد في متغير البيئة `EDITOR`. [اعرف المزيد](https://opencode.ai/docs/ar/tui#editor-setup) . /export **اختصار لوحة المفاتيح:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/ar/tui#help) اعرض مربع حوار المساعدة. /help **اختصار لوحة المفاتيح:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/ar/tui#init) أنشئ ملف `AGENTS.md` أو حدّثه. [اعرف المزيد](https://opencode.ai/docs/rules) . /init **اختصار لوحة المفاتيح:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/ar/tui#models) اعرض النماذج المتاحة. /models **اختصار لوحة المفاتيح:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/ar/tui#new) ابدأ جلسة جديدة. _الاسم المستعار_: `/clear` /new **اختصار لوحة المفاتيح:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/ar/tui#redo) أعِد تنفيذ رسالة تم التراجع عنها سابقا. متاح فقط بعد استخدام `/undo`. داخليا، يستخدم هذا Git لإدارة تغييرات الملفات. لذلك يجب أن يكون مشروعك **مستودع Git**. /redo **اختصار لوحة المفاتيح:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/ar/tui#sessions) اعرض الجلسات وبدّل بينها. _الأسماء المستعارة_: `/resume`, `/continue` /sessions **اختصار لوحة المفاتيح:** `ctrl+x l` * * * شارك الجلسة الحالية. [اعرف المزيد](https://opencode.ai/docs/share) . /share **اختصار لوحة المفاتيح:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/ar/tui#themes) اعرض السمات المتاحة. /theme **اختصار لوحة المفاتيح:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/ar/tui#thinking) بدّل إظهار كتل التفكير/الاستدلال في المحادثة. عند تفعيله، يمكنك رؤية عملية استدلال النموذج للنماذج التي تدعم التفكير الموسّع. /thinking * * * ### [undo](https://opencode.ai/docs/ar/tui#undo) تراجع عن آخر رسالة في المحادثة. يزيل أحدث رسالة للمستخدم، وكل الردود اللاحقة، وأي تغييرات على الملفات. داخليا، يستخدم هذا Git لإدارة تغييرات الملفات. لذلك يجب أن يكون مشروعك **مستودع Git**. /undo **اختصار لوحة المفاتيح:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/ar/tui#unshare) ألغِ مشاركة الجلسة الحالية. [اعرف المزيد](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [إعداد المحرر](https://opencode.ai/docs/ar/tui#%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF-%D8%A7%D9%84%D9%85%D8%AD%D8%B1%D8%B1) -------------------------------------------------------------------------------------------------------------------- يستخدم الأمران `/editor` و`/export` المحرر المحدد في متغير البيئة `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/ar/tui#tab-panel-11) * [Windows (CMD)](https://opencode.ai/docs/ar/tui#tab-panel-12) * [Windows (PowerShell)](https://opencode.ai/docs/ar/tui#tab-panel-13) # مثال لـ nano أو vimexport EDITOR=nanoexport EDITOR=vim # للمحررات الرسومية، VS Code، Cursor، VSCodium، Windsurf، Zed، إلخ.# قم بتضمين --waitexport EDITOR="code --wait" لجعل ذلك دائما، أضف هذا إلى ملف تهيئة shell لديك؛ `~/.bashrc`، `~/.zshrc`، إلخ. set EDITOR=notepad # للمحررات الرسومية، VS Code، Cursor، VSCodium، Windsurf، Zed، إلخ.# قم بتضمين --waitset EDITOR=code --wait لجعل ذلك دائما، استخدم **System Properties** > **Environment Variables**. $env:EDITOR = "notepad" # للمحررات الرسومية، VS Code، Cursor، VSCodium، Windsurf، Zed، إلخ.# قم بتضمين --wait$env:EDITOR = "code --wait" لجعل ذلك دائما، أضف هذا إلى ملف تهيئة PowerShell لديك. تتضمن خيارات المحررات الشائعة ما يلي: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - محرر Neovim * `vim` - محرر Vim * `nano` - محرر Nano * `notepad` - Windows Notepad * `subl` - Sublime Text تحتاج بعض المحررات إلى وسائط CLI لتعمل بوضع الحجب. يجعل الخيار `--wait` عملية المحرر تنتظر حتى يتم إغلاقها. * * * [الإعداد](https://opencode.ai/docs/ar/tui#%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF) -------------------------------------------------------------------------------------- يمكنك تخصيص سلوك واجهة TUI عبر ملف إعدادات OpenCode. { "$schema": "https://opencode.ai/config.json", "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true } }} ### [الخيارات](https://opencode.ai/docs/ar/tui#%D8%A7%D9%84%D8%AE%D9%8A%D8%A7%D8%B1%D8%A7%D8%AA) * `scroll_acceleration` - فعّل تسارع التمرير على نمط macOS لتمرير سلس وطبيعي. عند تفعيله، تزداد سرعة التمرير مع إيماءات التمرير السريعة وتبقى دقيقة للحركات الأبطأ. **يتقدّم هذا الإعداد على `scroll_speed` ويستبدله عند تفعيله.** * `scroll_speed` - يتحكم في سرعة تمرير واجهة TUI عند استخدام أوامر التمرير (الحد الأدنى: `1`). القيمة الافتراضية هي `3`. **ملاحظة: يتم تجاهل هذا إذا تم ضبط `scroll_acceleration.enabled` على `true`.** * `diff_style` - يتحكم في عرض الفروقات (diff). القيمة `"auto"` تتكيف مع عرض terminal، و`"stacked"` تعرض عمودًا واحدًا دائمًا. استخدم `OPENCODE_TUI_CONFIG` لتحميل مسار إعدادات TUI مخصص. * * * [التخصيص](https://opencode.ai/docs/ar/tui#%D8%A7%D9%84%D8%AA%D8%AE%D8%B5%D9%8A%D8%B5) -------------------------------------------------------------------------------------- يمكنك تخصيص جوانب مختلفة من عرض واجهة TUI باستخدام لوحة الأوامر (`ctrl+x h` أو `/help`). تبقى هذه الإعدادات محفوظة عبر عمليات إعادة التشغيل. * * * #### [عرض اسم المستخدم](https://opencode.ai/docs/ar/tui#%D8%B9%D8%B1%D8%B6-%D8%A7%D8%B3%D9%85-%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85) بدّل ما إذا كان اسم المستخدم يظهر في رسائل الدردشة. يمكنك الوصول إلى هذا عبر: * لوحة الأوامر: ابحث عن “username” أو “hide username” * يُحفظ الإعداد تلقائيا وسيتم تذكره عبر جلسات واجهة TUI --- # Fejlfinding | OpenCode [Gå til indhold](https://opencode.ai/docs/da/troubleshooting#_top) Fejlfinding =========== Almindelige problemer, og hvordan de løses. For at fejlfinde problemer med OpenCode, start med at tjekke logfilerne og de lokale data, den gemmer på disken. * * * [Logfiler](https://opencode.ai/docs/da/troubleshooting#logfiler) ----------------------------------------------------------------- Logfiler skrives til: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: Tryk `WIN+R` og indsæt `%USERPROFILE%\.local\share\opencode\log` Logfiler navngives med tidsstempler (f.eks. `2025-01-09T123456.log`) og de sidste 10 logfiler beholdes. Du kan angive logniveauet med kommandolinjeflaget `--log-level` for at få mere detaljeret fejlfindingsinformation. For eksempel `opencode --log-level DEBUG`. * * * [Lagring](https://opencode.ai/docs/da/troubleshooting#lagring) --------------------------------------------------------------- opencode gemmer sessionsdata og andre applikationsdata på disken på: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: Tryk `WIN+R` og indsæt `%USERPROFILE%\.local\share\opencode` Denne mappe indeholder: * `auth.json` - Godkendelsesdata som API-nøgler, OAuth-tokens * `log/` - Applikationslogs * `project/` - Projektspecifikke data som sessions- og beskeddata * Hvis projektet er inden for et Git-repo, gemmes det i `.//storage/` * Hvis det ikke er et Git-repo, gemmes det i `./global/storage/` * * * [Desktop-app](https://opencode.ai/docs/da/troubleshooting#desktop-app) ----------------------------------------------------------------------- OpenCode Desktop kører en lokal OpenCode-server (`opencode-cli` sidevognen) i baggrunden. De fleste problemer er forårsaget af et plugin, der fungerer dårligt, en ødelagt cache eller en dårlig serverindstilling. ### [Hurtige tjek](https://opencode.ai/docs/da/troubleshooting#hurtige-tjek) * Afslut og start appen på ny. * Hvis appen viser en fejlskærm, klikker du på **Start på ny** og kopierer fejldetaljerne. * Kun macOS: `OpenCode`\-menu -> **Genindlæs webvisning** (hjælper hvis UI er tom/frosset). * * * ### [Deaktiver plugins](https://opencode.ai/docs/da/troubleshooting#deaktiver-plugins) Hvis skrivebordsappen går ned ved opstart, hænger eller opfører sig mærkeligt, start med at deaktivere plugins. #### [Tjek den globale konfiguration](https://opencode.ai/docs/da/troubleshooting#tjek-den-globale-konfiguration) Åbn den globale konfigurationsfil og se efter en `plugin`\-nøgle. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (eller `~/.config/opencode/opencode.json`) * **macOS/Linux** (ældre installationer): `~/.local/share/opencode/opencode.jsonc` * **Windows**: Tryk `WIN+R` og indsæt `%USERPROFILE%\.config\opencode\opencode.jsonc` Hvis du har konfigureret plugins, deaktiver dem midlertidigt ved at fjerne nøglen eller sætte den til et tomt array: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Tjek plugin-mapper](https://opencode.ai/docs/da/troubleshooting#tjek-plugin-mapper) OpenCode kan også indlæse lokale plugins fra disken. Flyt disse midlertidigt væk (eller giv mappen nyt navn) og start skrivebordsappen på ny: * **Globale plugins** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: Tryk `WIN+R` og indsæt `%USERPROFILE%\.config\opencode\plugins` * **Projektplugins** (kun hvis du bruger konfiguration per projekt) * `/.opencode/plugins/` Hvis appen begynder at fungere igen, aktiverer du plugins én ad gangen for at finde ud af, hvilken som forårsager problemet. * * * ### [Ryd cachen](https://opencode.ai/docs/da/troubleshooting#ryd-cachen) Hvis deaktivering af plugins ikke hjælper (eller en plugin-installation sidder fast), tøm cachen så OpenCode kan genopbygge den. 1. Afslut OpenCode Desktop helt. 2. Slet cache-mappen: * **macOS**: Finder -> `Cmd+Shift+G` -> indsæt `~/.cache/opencode` * **Linux**: slet `~/.cache/opencode` (eller kør `rm -rf ~/.cache/opencode`) * **Windows**: Tryk `WIN+R` og indsæt `%USERPROFILE%\.cache\opencode` 3. Start OpenCode Desktop på ny. * * * ### [Løs problemer med serverforbindelse](https://opencode.ai/docs/da/troubleshooting#l%C3%B8s-problemer-med-serverforbindelse) OpenCode Desktop kan enten starte sin egen lokale server (standard) eller forbinde til en server URL, du har konfigureret. Hvis du ser en **“Forbindelse mislykkedes”**\-dialogboks (eller appen kommer aldrig forbi splash-skærmen), se efter en brugerdefineret server URL. #### [Slet standardserveren for skrivebordet URL](https://opencode.ai/docs/da/troubleshooting#slet-standardserveren-for-skrivebordet-url) Fra startskærmen klikker du på servernavnet (med statusprikken) for at åbne servervælgeren. I delen **Standardserver** klikker du på **Slet**. #### [Fjern `server.port` / `server.hostname` fra din konfiguration](https://opencode.ai/docs/da/troubleshooting#fjern-serverport--serverhostname-fra-din-konfiguration) Hvis `opencode.json(c)` indeholder en `server`\-del, fjern den midlertidigt og start skrivebordsappen på ny. #### [Tjek miljøvariabler](https://opencode.ai/docs/da/troubleshooting#tjek-milj%C3%B8variabler) Hvis du har `OPENCODE_PORT` sat i dit miljø, vil skrivebordsappen prøve at bruge den port for den lokale server. * Deaktiver `OPENCODE_PORT` (eller vælg en ledig port) og start på ny. * * * ### [Linux: Wayland / X11-problemer](https://opencode.ai/docs/da/troubleshooting#linux-wayland--x11-problemer) På Linux kan nogle Wayland-opsætninger forårsage tomme vinduer eller kompositorfejl. * Hvis du er på Wayland og appen er tom/crasher, prøv at starte med `OC_ALLOW_WAYLAND=1`. * Hvis det gør ting værre, fjern det og prøv at starte under en X11-session i stedet. * * * ### [Windows: WebView2-runtime](https://opencode.ai/docs/da/troubleshooting#windows-webview2-runtime) På Windows kræver OpenCode Desktop Microsoft Edge **WebView2 Runtime**. Hvis appen åbnes i et tomt vindue eller ikke starter, installer/opdater WebView2 og prøv igen. * * * ### [Windows: Generelle ydeevneproblemer](https://opencode.ai/docs/da/troubleshooting#windows-generelle-ydeevneproblemer) Hvis du oplever langsom ydeevne, problemer med filadgang eller terminalproblemer på Windows, kan du prøve at bruge [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) . WSL giver et Linux-miljø som fungerer mere sømløst med funktionerne i OpenCode. * * * ### [Meddelelser vises ikke](https://opencode.ai/docs/da/troubleshooting#meddelelser-vises-ikke) OpenCode Desktop viser kun systemvarsler når: * varsler er aktiveret for OpenCode i dine OS-indstillinger, og * appvinduet ikke er fokuseret. * * * ### [Nulstil desktop-applagring (sidste udvej)](https://opencode.ai/docs/da/troubleshooting#nulstil-desktop-applagring-sidste-udvej) Hvis appen ikke starter og du ikke kan slette indstillingerne fra UI, nulstil skrivebordsappens gemte tilstand. 1. Afslut OpenCode Desktop. 2. Find og slet disse filer (de findes i OpenCode Desktop-appens datamappe): * `opencode.settings.dat` (skrivebordsstandardserver URL) * `opencode.global.dat` og `opencode.workspace.*.dat` (UI tilstand som nylige servere/projekter) Sådan finder du mappen hurtigt: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (søg derefter efter filnavnene ovenfor) * **Linux**: søg under `~/.local/share` efter filnavnene ovenfor * **Windows**: Tryk `WIN+R` -> `%APPDATA%` (søg derefter efter filnavnene ovenfor) * * * [Få hjælp](https://opencode.ai/docs/da/troubleshooting#f%C3%A5-hj%C3%A6lp) --------------------------------------------------------------------------- Hvis du oplever problemer med OpenCode: 1. **Rapporter problemer på GitHub** Den bedste måde at rapportere fejl eller bede om funktioner på er gennem vores GitHub-repo: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Før du opretter et nyt issue, søg i eksisterende issues for at se om dit problem allerede er rapporteret. 2. **Bliv en del af vores Discord** For hjælp i realtid og fællesskabsdiskussion, bliv en del af vores Discord-server: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Almindelige problemer](https://opencode.ai/docs/da/troubleshooting#almindelige-problemer) ------------------------------------------------------------------------------------------- Her er nogle almindelige problemer og hvordan du kan løse dem. * * * ### [OpenCode vil ikke starte](https://opencode.ai/docs/da/troubleshooting#opencode-vil-ikke-starte) 1. Tjek logfilerne for fejlmeddelelser 2. Prøv at køre med `--print-logs` for at se output i terminalen 3. Sørg for at du har den nyeste version med `opencode upgrade` * * * ### [Godkendelsesproblemer](https://opencode.ai/docs/da/troubleshooting#godkendelsesproblemer) 1. Prøv at godkende på ny med kommandoen `/connect` i TUI 2. Tjek at dine API-nøgler er gyldige 3. Sørg for at dit netværk tillader forbindelser til udbyderens API * * * ### [Modellen er ikke tilgængelig](https://opencode.ai/docs/da/troubleshooting#modellen-er-ikke-tilg%C3%A6ngelig) 1. Tjek at du har godkendt dig med udbyderen 2. Kontroller at modelnavnet i konfigurationen er rigtigt 3. Nogle modeller kan kræve specifik adgang eller abonnement Hvis du støder på `ProviderModelNotFoundError` refererer du mest sandsynligt forkert til en model et sted. Modeller skal refereres sådan: `/` Eksempler: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` For at finde ud af hvilke modeller du har adgang til, kør `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/da/troubleshooting#provideriniterror) Hvis du støder på en ProviderInitError, har du sandsynligvis en ugyldig eller ødelagt konfiguration. For at løse dette: 1. Kontroller først at din udbyder er rigtigt konfigureret ved at følge [udbydervejledningen](https://opencode.ai/docs/providers) 2. Hvis problemet vedvarer, prøv at tømme den gemte konfiguration: rm -rf ~/.local/share/opencode På Windows, tryk `WIN+R` og slet: `%USERPROFILE%\.local\share\opencode` 3. Godkend på ny med din udbyder ved at bruge kommandoen `/connect` i TUI. * * * ### [AI\_APICallError og udbyderpakkeproblemer](https://opencode.ai/docs/da/troubleshooting#ai_apicallerror-og-udbyderpakkeproblemer) Hvis du støder på API-kaldsfejl, kan dette skyldes forældede udbyderpakker. opencode installerer dynamisk udbyderpakker (OpenAI, Anthropic, Google, etc.) efter behov og cacher dem lokalt. For at løse problemer med udbyderpakke: 1. Tøm udbyderens pakkecache: rm -rf ~/.cache/opencode På Windows, tryk `WIN+R` og slet: `%USERPROFILE%\.cache\opencode` 2. Start opencode på ny for at installere de nyeste udbyderpakker på ny Dette vil tvinge opencode til at downloade de nyeste versioner af udbyderpakkerne, som ofte løser kompatibilitetsproblemer med modelparametre og API-ændringer. * * * ### [Kopier/indsæt virker ikke på Linux](https://opencode.ai/docs/da/troubleshooting#kopierinds%C3%A6t-virker-ikke-p%C3%A5-linux) Linux-brugere skal have et af følgende udklipsholderværktøjer installeret for at kopier/indsæt-funktionalitet skal fungere: **For X11-systemer:** apt install -y xclip# orapt install -y xsel **For Wayland-systemer:** apt install -y wl-clipboard **For hovedløse miljøer:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode vil opdage om du bruger Wayland og foretrække `wl-clipboard`, ellers vil den prøve at finde udklipsholderværktøjer i rækkefølgen: `xclip` og `xsel`. --- # استكشاف الأخطاء وإصلاحها | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/troubleshooting#_top) استكشاف الأخطاء وإصلاحها ======================== المشكلات الشائعة وكيفية حلها. لاستكشاف المشكلات في OpenCode وإصلاحها، ابدأ بالتحقق من السجلات والبيانات المحلية التي يخزنها على القرص. * * * [السجلات](https://opencode.ai/docs/ar/troubleshooting#%D8%A7%D9%84%D8%B3%D8%AC%D9%84%D8%A7%D8%AA) -------------------------------------------------------------------------------------------------- يتم حفظ ملفات السجل في: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.local\share\opencode\log` تتم تسمية ملفات السجل بطوابع زمنية (مثل `2025-01-09T123456.log`) ويتم الاحتفاظ بأحدث 10 ملفات سجل. يمكنك ضبط مستوى السجل باستخدام خيار CLI `--log-level` للحصول على معلومات تصحيح أكثر تفصيلا. على سبيل المثال: `opencode --log-level DEBUG`. * * * [التخزين](https://opencode.ai/docs/ar/troubleshooting#%D8%A7%D9%84%D8%AA%D8%AE%D8%B2%D9%8A%D9%86) -------------------------------------------------------------------------------------------------- يخزن opencode بيانات الجلسات وبيانات التطبيق الأخرى على القرص في: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.local\share\opencode` يحتوي هذا الدليل على: * `auth.json` - بيانات المصادقة مثل مفاتيح API ورموز OAuth * `log/` - سجلات التطبيق * `project/` - بيانات خاصة بالمشروع مثل بيانات الجلسة والرسائل * إذا كان المشروع داخل مستودع Git، فسيتم تخزينه في `.//storage/` * إذا لم يكن داخل مستودع Git، فسيتم تخزينه في `./global/storage/` * * * [تطبيق سطح المكتب](https://opencode.ai/docs/ar/troubleshooting#%D8%AA%D8%B7%D8%A8%D9%8A%D9%82-%D8%B3%D8%B7%D8%AD-%D8%A7%D9%84%D9%85%D9%83%D8%AA%D8%A8) ------------------------------------------------------------------------------------------------------------------------------------------------------- يشغل OpenCode Desktop خادما محليا لـ OpenCode (العملية الجانبية `opencode-cli`) في الخلفية. معظم المشكلات سببها إضافة لا تعمل بشكل صحيح، أو ذاكرة تخزين مؤقت تالفة، أو إعداد خادم غير صحيح. ### [فحوصات سريعة](https://opencode.ai/docs/ar/troubleshooting#%D9%81%D8%AD%D9%88%D8%B5%D8%A7%D8%AA-%D8%B3%D8%B1%D9%8A%D8%B9%D8%A9) * أغلق التطبيق تماما ثم أعد تشغيله. * إذا عرض التطبيق شاشة خطأ، انقر **Restart** وانسخ تفاصيل الخطأ. * على macOS فقط: قائمة `OpenCode` -> **Reload Webview** (يفيد إذا كانت الواجهة فارغة/متجمدة). * * * ### [تعطيل الإضافات](https://opencode.ai/docs/ar/troubleshooting#%D8%AA%D8%B9%D8%B7%D9%8A%D9%84-%D8%A7%D9%84%D8%A5%D8%B6%D8%A7%D9%81%D8%A7%D8%AA) إذا كان تطبيق سطح المكتب يتعطل عند التشغيل، أو يتوقف عن الاستجابة، أو يتصرف بشكل غريب، فابدأ بتعطيل الإضافات. #### [تحقق من الإعدادات العامة](https://opencode.ai/docs/ar/troubleshooting#%D8%AA%D8%AD%D9%82%D9%82-%D9%85%D9%86-%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF%D8%A7%D8%AA-%D8%A7%D9%84%D8%B9%D8%A7%D9%85%D8%A9) افتح ملف الإعدادات العام وابحث عن المفتاح `plugin`. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (أو `~/.config/opencode/opencode.json`) * **macOS/Linux** (عمليات تثبيت أقدم): `~/.local/share/opencode/opencode.jsonc` * **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.config\opencode\opencode.jsonc` إذا كانت لديك إضافات مضبوطة، فقم بتعطيلها مؤقتا بإزالة المفتاح أو ضبطه على مصفوفة فارغة: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [تحقق من أدلة الإضافات](https://opencode.ai/docs/ar/troubleshooting#%D8%AA%D8%AD%D9%82%D9%82-%D9%85%D9%86-%D8%A3%D8%AF%D9%84%D8%A9-%D8%A7%D9%84%D8%A5%D8%B6%D8%A7%D9%81%D8%A7%D8%AA) يمكن لـ OpenCode أيضا تحميل إضافات محلية من القرص. انقلها مؤقتا إلى مكان آخر (أو أعد تسمية المجلد) ثم أعد تشغيل تطبيق سطح المكتب: * **إضافات عامة** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.config\opencode\plugins` * **إضافات المشروع** (فقط إذا كنت تستخدم إعدادات لكل مشروع) * `/.opencode/plugins/` إذا عاد التطبيق للعمل، فأعد تفعيل الإضافات واحدة تلو الأخرى لمعرفة أيها يسبب المشكلة. * * * ### [مسح ذاكرة التخزين المؤقت](https://opencode.ai/docs/ar/troubleshooting#%D9%85%D8%B3%D8%AD-%D8%B0%D8%A7%D9%83%D8%B1%D8%A9-%D8%A7%D9%84%D8%AA%D8%AE%D8%B2%D9%8A%D9%86-%D8%A7%D9%84%D9%85%D8%A4%D9%82%D8%AA) إذا لم يساعد تعطيل الإضافات (أو كانت عملية تثبيت إضافة عالقة)، فامسح ذاكرة التخزين المؤقت حتى يتمكن OpenCode من إعادة بنائها. 1. أغلق OpenCode Desktop تماما. 2. احذف دليل ذاكرة التخزين المؤقت: * **macOS**: Finder -> `Cmd+Shift+G` -> الصق `~/.cache/opencode` * **Linux**: احذف `~/.cache/opencode` (أو شغّل `rm -rf ~/.cache/opencode`) * **Windows**: اضغط `WIN+R` والصق `%USERPROFILE%\.cache\opencode` 3. أعد تشغيل OpenCode Desktop. * * * ### [إصلاح مشكلات اتصال الخادم](https://opencode.ai/docs/ar/troubleshooting#%D8%A5%D8%B5%D9%84%D8%A7%D8%AD-%D9%85%D8%B4%D9%83%D9%84%D8%A7%D8%AA-%D8%A7%D8%AA%D8%B5%D8%A7%D9%84-%D8%A7%D9%84%D8%AE%D8%A7%D8%AF%D9%85) يمكن لـ OpenCode Desktop إما تشغيل خادمه المحلي (افتراضيا) أو الاتصال بعنوان URL لخادم قمت بتهيئته. إذا ظهرت نافذة **“Connection Failed”** (أو لم يتجاوز التطبيق شاشة البداية)، فتحقق مما إذا كان هناك عنوان URL مخصص للخادم. #### [مسح عنوان URL الافتراضي لخادم سطح المكتب](https://opencode.ai/docs/ar/troubleshooting#%D9%85%D8%B3%D8%AD-%D8%B9%D9%86%D9%88%D8%A7%D9%86-url-%D8%A7%D9%84%D8%A7%D9%81%D8%AA%D8%B1%D8%A7%D8%B6%D9%8A-%D9%84%D8%AE%D8%A7%D8%AF%D9%85-%D8%B3%D8%B7%D8%AD-%D8%A7%D9%84%D9%85%D9%83%D8%AA%D8%A8) من شاشة Home، انقر اسم الخادم (مع نقطة الحالة) لفتح محدد الخوادم. في قسم **Default server**، انقر **Clear**. #### [إزالة `server.port` / `server.hostname` من الإعدادات](https://opencode.ai/docs/ar/troubleshooting#%D8%A5%D8%B2%D8%A7%D9%84%D8%A9-serverport--serverhostname-%D9%85%D9%86-%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF%D8%A7%D8%AA) إذا كان `opencode.json(c)` يحتوي على قسم `server`، فأزله مؤقتا ثم أعد تشغيل تطبيق سطح المكتب. #### [تحقق من متغيرات البيئة](https://opencode.ai/docs/ar/troubleshooting#%D8%AA%D8%AD%D9%82%D9%82-%D9%85%D9%86-%D9%85%D8%AA%D8%BA%D9%8A%D8%B1%D8%A7%D8%AA-%D8%A7%D9%84%D8%A8%D9%8A%D8%A6%D8%A9) إذا كان `OPENCODE_PORT` مضبوطا في بيئتك، فسيحاول تطبيق سطح المكتب استخدام ذلك المنفذ للخادم المحلي. * أزل ضبط `OPENCODE_PORT` (أو اختر منفذا متاحا) ثم أعد التشغيل. * * * ### [Linux: مشكلات Wayland / X11](https://opencode.ai/docs/ar/troubleshooting#linux-%D9%85%D8%B4%D9%83%D9%84%D8%A7%D8%AA-wayland--x11) على Linux، قد تتسبب بعض إعدادات Wayland في نوافذ فارغة أو أخطاء في مدير التركيب (compositor). * إذا كنت تستخدم Wayland وكانت نافذة التطبيق فارغة/يتعطل، فجرّب التشغيل مع `OC_ALLOW_WAYLAND=1`. * إذا جعل ذلك الأمور أسوأ، فأزل هذا المتغير وجرّب التشغيل ضمن جلسة X11 بدلا من ذلك. * * * ### [Windows: بيئة تشغيل WebView2](https://opencode.ai/docs/ar/troubleshooting#windows-%D8%A8%D9%8A%D8%A6%D8%A9-%D8%AA%D8%B4%D8%BA%D9%8A%D9%84-webview2) على Windows، يتطلب OpenCode Desktop وجود **WebView2 Runtime** الخاصة بـ Microsoft Edge. إذا فتح التطبيق نافذة فارغة أو لم يبدأ، فقم بتثبيت/تحديث WebView2 ثم جرّب مجددا. * * * ### [Windows: مشكلات الأداء العامة](https://opencode.ai/docs/ar/troubleshooting#windows-%D9%85%D8%B4%D9%83%D9%84%D8%A7%D8%AA-%D8%A7%D9%84%D8%A3%D8%AF%D8%A7%D8%A1-%D8%A7%D9%84%D8%B9%D8%A7%D9%85%D8%A9) إذا كنت تواجه بطءا في الأداء، أو مشكلات في الوصول إلى الملفات، أو مشكلات في terminal على Windows، فجرّب استخدام [WSL (نظام Windows الفرعي لـ Linux)](https://opencode.ai/docs/windows-wsl) . يوفر WSL بيئة Linux تعمل بسلاسة أكبر مع ميزات OpenCode. * * * ### [الإشعارات لا تظهر](https://opencode.ai/docs/ar/troubleshooting#%D8%A7%D9%84%D8%A5%D8%B4%D8%B9%D8%A7%D8%B1%D8%A7%D8%AA-%D9%84%D8%A7-%D8%AA%D8%B8%D9%87%D8%B1) لا يعرض OpenCode Desktop إشعارات النظام إلا عندما: * تكون الإشعارات مفعلة لـ OpenCode في إعدادات نظام التشغيل، و * تكون نافذة التطبيق غير نشطة. * * * ### [إعادة تعيين تخزين تطبيق سطح المكتب (كحل أخير)](https://opencode.ai/docs/ar/troubleshooting#%D8%A5%D8%B9%D8%A7%D8%AF%D8%A9-%D8%AA%D8%B9%D9%8A%D9%8A%D9%86-%D8%AA%D8%AE%D8%B2%D9%8A%D9%86-%D8%AA%D8%B7%D8%A8%D9%8A%D9%82-%D8%B3%D8%B7%D8%AD-%D8%A7%D9%84%D9%85%D9%83%D8%AA%D8%A8-%D9%83%D8%AD%D9%84-%D8%A3%D8%AE%D9%8A%D8%B1) إذا لم يبدأ التطبيق ولم تتمكن من مسح الإعدادات من داخل الواجهة، فأعد تعيين الحالة المحفوظة لتطبيق سطح المكتب. 1. أغلق OpenCode Desktop. 2. اعثر على هذه الملفات واحذفها (توجد في دليل بيانات تطبيق OpenCode Desktop): * `opencode.settings.dat` (عنوان URL الافتراضي لخادم سطح المكتب) * `opencode.global.dat` و `opencode.workspace.*.dat` (حالة الواجهة مثل الخوادم/المشاريع الأخيرة) للعثور على الدليل بسرعة: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (ثم ابحث عن أسماء الملفات أعلاه) * **Linux**: ابحث ضمن `~/.local/share` عن أسماء الملفات أعلاه * **Windows**: اضغط `WIN+R` -> `%APPDATA%` (ثم ابحث عن أسماء الملفات أعلاه) * * * [الحصول على المساعدة](https://opencode.ai/docs/ar/troubleshooting#%D8%A7%D9%84%D8%AD%D8%B5%D9%88%D9%84-%D8%B9%D9%84%D9%89-%D8%A7%D9%84%D9%85%D8%B3%D8%A7%D8%B9%D8%AF%D8%A9) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- إذا كنت تواجه مشكلات مع OpenCode: 1. **الإبلاغ عن المشكلات على GitHub** أفضل طريقة للإبلاغ عن الأخطاء أو طلب الميزات هي عبر مستودعنا على GitHub: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) قبل إنشاء مشكلة جديدة، ابحث في المشكلات الموجودة لمعرفة ما إذا كانت مشكلتك قد تم الإبلاغ عنها بالفعل. 2. **انضم إلى Discord** للحصول على مساعدة فورية ونقاشات المجتمع، انضم إلى خادم Discord الخاص بنا: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [مشكلات شائعة](https://opencode.ai/docs/ar/troubleshooting#%D9%85%D8%B4%D9%83%D9%84%D8%A7%D8%AA-%D8%B4%D8%A7%D8%A6%D8%B9%D8%A9) -------------------------------------------------------------------------------------------------------------------------------- فيما يلي بعض المشكلات الشائعة وكيفية حلها. * * * ### [OpenCode لا يبدأ](https://opencode.ai/docs/ar/troubleshooting#opencode-%D9%84%D8%A7-%D9%8A%D8%A8%D8%AF%D8%A3) 1. تحقق من السجلات بحثا عن رسائل الخطأ 2. جرّب التشغيل مع `--print-logs` لرؤية المخرجات في terminal 3. تأكد من أنك تستخدم أحدث إصدار عبر `opencode upgrade` * * * ### [مشكلات المصادقة](https://opencode.ai/docs/ar/troubleshooting#%D9%85%D8%B4%D9%83%D9%84%D8%A7%D8%AA-%D8%A7%D9%84%D9%85%D8%B5%D8%A7%D8%AF%D9%82%D8%A9) 1. جرّب إعادة المصادقة باستخدام الأمر `/connect` في واجهة TUI 2. تحقق من أن مفاتيح API الخاصة بك صالحة 3. تأكد من أن شبكتك تسمح بالاتصال بواجهة API الخاصة بالمزوّد * * * ### [النموذج غير متاح](https://opencode.ai/docs/ar/troubleshooting#%D8%A7%D9%84%D9%86%D9%85%D9%88%D8%B0%D8%AC-%D8%BA%D9%8A%D8%B1-%D9%85%D8%AA%D8%A7%D8%AD) 1. تحقق من أنك قمت بالمصادقة مع المزوّد 2. تأكد من أن اسم النموذج في الإعدادات صحيح 3. قد تتطلب بعض النماذج صلاحيات وصول محددة أو اشتراكات إذا واجهت `ProviderModelNotFoundError` فمن المرجح أنك تشير إلى نموذج بشكل غير صحيح في مكان ما. يجب الإشارة إلى النماذج بهذه الصيغة: `/` أمثلة: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` لمعرفة النماذج التي لديك صلاحية الوصول إليها، شغّل `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/ar/troubleshooting#provideriniterror) إذا واجهت ProviderInitError، فمن المحتمل أن إعداداتك غير صالحة أو تالفة. لحل ذلك: 1. أولا، تحقق من أن المزوّد مضبوط بشكل صحيح باتباع [دليل المزوّدين](https://opencode.ai/docs/providers) 2. إذا استمرت المشكلة، فجرّب مسح الإعدادات المخزنة لديك: rm -rf ~/.local/share/opencode على Windows، اضغط `WIN+R` واحذف: `%USERPROFILE%\.local\share\opencode` 3. أعد المصادقة مع المزوّد باستخدام الأمر `/connect` في واجهة TUI. * * * ### [AI\_APICallError ومشكلات حزم المزوّد](https://opencode.ai/docs/ar/troubleshooting#ai_apicallerror-%D9%88%D9%85%D8%B4%D9%83%D9%84%D8%A7%D8%AA-%D8%AD%D8%B2%D9%85-%D8%A7%D9%84%D9%85%D8%B2%D9%88%D9%91%D8%AF) إذا واجهت أخطاء في استدعاءات API، فقد يكون السبب حزم مزوّد قديمة. يقوم opencode بتثبيت حزم المزوّد (OpenAI و Anthropic و Google وغير ذلك) ديناميكيا عند الحاجة ويقوم بتخزينها مؤقتا محليا. لحل مشكلات حزم المزوّد: 1. امسح ذاكرة التخزين المؤقت لحزم المزوّد: rm -rf ~/.cache/opencode على Windows، اضغط `WIN+R` واحذف: `%USERPROFILE%\.cache\opencode` 2. أعد تشغيل opencode لإعادة تثبيت أحدث حزم المزوّد سيجبر ذلك opencode على تنزيل أحدث إصدارات حزم المزوّد، وهو ما يحل غالبا مشكلات التوافق مع معاملات النماذج وتغييرات API. * * * ### [النسخ/اللصق لا يعمل على Linux](https://opencode.ai/docs/ar/troubleshooting#%D8%A7%D9%84%D9%86%D8%B3%D8%AE%D8%A7%D9%84%D9%84%D8%B5%D9%82-%D9%84%D8%A7-%D9%8A%D8%B9%D9%85%D9%84-%D8%B9%D9%84%D9%89-linux) يحتاج مستخدمو Linux إلى تثبيت إحدى أدوات الحافظة التالية حتى تعمل ميزة النسخ/اللصق: **لأنظمة X11:** apt install -y xclip# orapt install -y xsel **لأنظمة Wayland:** apt install -y wl-clipboard **للبيئات بدون واجهة رسومية (Headless):** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 سيكتشف opencode ما إذا كنت تستخدم Wayland ويفضل `wl-clipboard`، وإلا فسيحاول العثور على أدوات الحافظة بالترتيب التالي: `xclip` ثم `xsel`. --- # 문제 해결 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/troubleshooting#_top) 문제 해결 ===== 일반적인 문제와 해결 방법. opencode와 문제를 디버그하려면 로그와 로컬 데이터를 확인하여 디스크에 저장합니다. * * * [로깅](https://opencode.ai/docs/ko/troubleshooting#%EB%A1%9C%EA%B9%85) --------------------------------------------------------------------- 로그 파일은 다음과 같습니다: \-**macOS/리눅스**: `~/.local/share/opencode/log/` * **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.local\share\opencode\log` 로그 파일은 타임스탬프 (예 : `2025-01-09T123456.log`)과 가장 최근 10 로그 파일이 보관됩니다. 자세한 디버그 정보를 얻기 위해 `--log-level` 명령줄 옵션을 사용하여 로그 레벨을 설정할 수 있습니다. 예를 들면, `opencode --log-level DEBUG`. * * * [저장소](https://opencode.ai/docs/ko/troubleshooting#%EC%A0%80%EC%9E%A5%EC%86%8C) ------------------------------------------------------------------------------- opencode 저장 세션 데이터 및 디스크에 다른 응용 데이터: \-**macOS/리눅스**: `~/.local/share/opencode/` * **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.local\share\opencode` 이 디렉토리는 다음과 같습니다: * `auth.json` - API 키, OAuth 토큰과 같은 인증 데이터 * `log/` - 응용 프로그램 로그 * `project/` - 세션 및 메시지 데이터와 같은 프로젝트별 데이터 * 프로젝트가 Git repo 안에 있는 경우에, 그것은 `.//storage/`에서 저장됩니다 * Git repo가 아닌 경우 `./global/storage/`에 저장됩니다. * * * [데스크톱 앱](https://opencode.ai/docs/ko/troubleshooting#%EB%8D%B0%EC%8A%A4%ED%81%AC%ED%86%B1-%EC%95%B1) ----------------------------------------------------------------------------------------------------- opencode 데스크톱은 배경에서 로컬 opencode 서버 (`opencode-cli` sidecar)를 실행합니다. 대부분의 문제는 misbehaving 플러그인, 손상된 캐시, 또는 나쁜 서버 설정에 의해 발생합니다. [빠른 확인](https://opencode.ai/docs/ko/troubleshooting#%EB%B9%A0%EB%A5%B8-%ED%99%95%EC%9D%B8) ------------------------------------------------------------------------------------------- * 완전히 종료하고 앱을 다시 시작. * 앱이 오류 화면을 보여 주면 \*\* Restart\*\*를 클릭하고 오류 세부 정보를 복사합니다. * macOS만: `OpenCode` 메뉴 -> \*\*웹뷰 \*\*(UI가 공백/frozen인 경우). * * * [플러그인 비활성화](https://opencode.ai/docs/ko/troubleshooting#%ED%94%8C%EB%9F%AC%EA%B7%B8%EC%9D%B8-%EB%B9%84%ED%99%9C%EC%84%B1%ED%99%94) ----------------------------------------------------------------------------------------------------------------------------------- 데스크톱 앱이 출시, 거는, 또는 이상한 것에서 충돌하면 플러그인을 비활성화하여 시작합니다. ### [전역 설정 확인](https://opencode.ai/docs/ko/troubleshooting#%EC%A0%84%EC%97%AD-%EC%84%A4%EC%A0%95-%ED%99%95%EC%9D%B8) 글로벌 설정 파일을 열고 `plugin` 키를 찾습니다. \-**macOS/리눅스**: `~/.config/opencode/opencode.jsonc` (또는 `~/.config/opencode/opencode.json`) -**macOS/Linux** (외부 설치): `~/.local/share/opencode/opencode.jsonc` * **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.config\opencode\opencode.jsonc` 구성 된 플러그인이있는 경우, 일시적으로 키를 제거하거나 빈 배열로 설정하여 비활성화하십시오. { "$schema": "https://opencode.ai/config.json", "plugin": [],} ### [플러그인 디렉터리 확인](https://opencode.ai/docs/ko/troubleshooting#%ED%94%8C%EB%9F%AC%EA%B7%B8%EC%9D%B8-%EB%94%94%EB%A0%89%ED%84%B0%EB%A6%AC-%ED%99%95%EC%9D%B8) opencode는 디스크에서 로컬 플러그인을로드 할 수 있습니다. Temporarily 이동 이러한 방법 (또는 폴더 이름을 변경) 및 데스크톱 응용 프로그램을 다시 시작: * **글로벌 플러그인** -**macOS/리눅스**: `~/.config/opencode/plugins/` * **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.config\opencode\plugins` * **프로젝트 플러그인** (프로젝트 설정만 사용) * `/.opencode/plugins/` 앱이 다시 일하는 경우, 재 활성화 플러그인은 한 번에 문제가 발생할 수 있습니다. * * * #### [캐시 삭제](https://opencode.ai/docs/ko/troubleshooting#%EC%BA%90%EC%8B%9C-%EC%82%AD%EC%A0%9C) 플러그인을 비활성화하는 경우 도움이되지 않습니다 (또는 플러그인 설치가 붙어있다), 캐시를 삭제 그래서 opencode는 그것을 재구성 할 수 있습니다. 1. Quit opencode 데스크톱 완전히. 2. 캐시 디렉토리 삭제: \-**macOS**: 찾기 -> `Cmd+Shift+G` -> 붙여넣기 `~/.cache/opencode` * **Linux**: `~/.cache/opencode` 삭제 (또는 `rm -rf ~/.cache/opencode` 실행) * **Windows**: 압박 `WIN+R`와 풀 `%USERPROFILE%\.cache\opencode` 3. Restart opencode 데스크탑. * * * [서버 연결 문제 수정](https://opencode.ai/docs/ko/troubleshooting#%EC%84%9C%EB%B2%84-%EC%97%B0%EA%B2%B0-%EB%AC%B8%EC%A0%9C-%EC%88%98%EC%A0%95) --------------------------------------------------------------------------------------------------------------------------------------- opencode 데스크톱은 자체 로컬 서버(기본)를 시작하거나 구성된 서버 URL에 연결할 수 있습니다. **“Connection Failed”** 대화 상자 (또는 앱이 스패시 화면을 지나지 않습니다), 사용자 정의 서버 URL을 확인합니다. ### [데스크톱 기본 서버 URL 삭제](https://opencode.ai/docs/ko/troubleshooting#%EB%8D%B0%EC%8A%A4%ED%81%AC%ED%86%B1-%EA%B8%B0%EB%B3%B8-%EC%84%9C%EB%B2%84-url-%EC%82%AD%EC%A0%9C) Home 화면에서 Server Picker를 열려면 서버 이름(상태 점)을 클릭하십시오. **기본 서버** 섹션에서 **Clear**를 클릭합니다. #### [설정에서 server.port/server.hostname 제거](https://opencode.ai/docs/ko/troubleshooting#%EC%84%A4%EC%A0%95%EC%97%90%EC%84%9C-serverportserverhostname-%EC%A0%9C%EA%B1%B0) `opencode.json(c)`가 `server` 섹션을 포함하면 일시적으로 제거하고 데스크톱 앱을 다시 시작합니다. ### [환경 변수 확인](https://opencode.ai/docs/ko/troubleshooting#%ED%99%98%EA%B2%BD-%EB%B3%80%EC%88%98-%ED%99%95%EC%9D%B8) `OPENCODE_PORT`가 있는 경우, 데스크탑 앱은 로컬 서버의 포트를 사용하려고 합니다. * `OPENCODE_PORT` (또는 무료 포트를 선택) 및 재시작. * * * [Linux: Wayland / X11 문제](https://opencode.ai/docs/ko/troubleshooting#linux-wayland--x11-%EB%AC%B8%EC%A0%9C) ------------------------------------------------------------------------------------------------------------- Linux에서 일부 Wayland 설정은 공백 창이나 compositor 오류를 일으킬 수 있습니다. * If you’re on Wayland and the app is blank/crashing, `OC_ALLOW_WAYLAND=1`로 출시하려고합니다. * 더 나쁜 것을 만드는 경우, 제거하고 X11 세션에서 실행하려고합니다. * * * [Windows: WebView2 런타임](https://opencode.ai/docs/ko/troubleshooting#windows-webview2-%EB%9F%B0%ED%83%80%EC%9E%84) ------------------------------------------------------------------------------------------------------------------ Windows에서 opencode 데스크톱은 Microsoft Edge \*\* WebView2 실행 시간 \*\*를 요구합니다. 앱이 공백 창에 열거나 시작하지 않을 경우, install/update WebView2를 설치하고 다시 시도하십시오. * * * [Windows: 일반 성능 문제](https://opencode.ai/docs/ko/troubleshooting#windows-%EC%9D%BC%EB%B0%98-%EC%84%B1%EB%8A%A5-%EB%AC%B8%EC%A0%9C) ---------------------------------------------------------------------------------------------------------------------------------- 느린 성능, 파일 액세스 문제 또는 Windows의 terminal 문제를 경험하는 경우 [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) 를 사용하여 시도하십시오. WSL은 opencode의 기능으로 더 원활하게 작동하는 Linux 환경을 제공합니다. * * * [알림이 표시되지 않음](https://opencode.ai/docs/ko/troubleshooting#%EC%95%8C%EB%A6%BC%EC%9D%B4-%ED%91%9C%EC%8B%9C%EB%90%98%EC%A7%80-%EC%95%8A%EC%9D%8C) ----------------------------------------------------------------------------------------------------------------------------------------------- opencode 데스크톱은 시스템 알림을 보여줍니다 : * OS 설정에서 opencode에 대한 알림이 활성화되고, * 앱 창이 집중되지 않습니다. * * * [데스크톱 앱 저장소 재설정 (최후의 수단)](https://opencode.ai/docs/ko/troubleshooting#%EB%8D%B0%EC%8A%A4%ED%81%AC%ED%86%B1-%EC%95%B1-%EC%A0%80%EC%9E%A5%EC%86%8C-%EC%9E%AC%EC%84%A4%EC%A0%95-%EC%B5%9C%ED%9B%84%EC%9D%98-%EC%88%98%EB%8B%A8) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 앱이 시작되지 않은 경우 UI 내부에서 설정을 취소할 수 없습니다. 데스크탑 앱의 저장된 상태를 재설정하십시오. 1. Quit opencode 데스크탑. 2. 이 파일을 찾아 삭제 (opencode 데스크톱 앱 데이터 디렉토리에서 라이브): * `opencode.settings.dat` (데스크톱 기본 서버 URL) * `opencode.global.dat` 및 `opencode.workspace.*.dat` (최근 서버/프로젝트와 같은 UI 국가) 빠른 디렉토리를 찾을 수: \-**macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (위의 파일명 검색) * \*\*리눅스 \*\*: 위의 파일명에 대한 `~/.local/share`의 밑에 검색 * **Windows**: `WIN+R` -> `%APPDATA%`를 눌러 (위의 파일 이름을 검색) * * * [도움 받기](https://opencode.ai/docs/ko/troubleshooting#%EB%8F%84%EC%9B%80-%EB%B0%9B%EA%B8%B0) ------------------------------------------------------------------------------------------- opencode와 문제가 발생하면: 1. \*\* GitHub의 문제 해결 \*\* 버그 또는 요청 기능을보고하는 가장 좋은 방법은 GitHub 저장소를 통해 다음과 같습니다. [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) 새로운 문제를 만들기 전에, 당신의 문제가 이미보고 된 경우 기존 문제를 검색. 2. \*\* 우리의 Discord \*\* 실시간 도움말 및 커뮤니티 토론을 위해 Discord 서버에 가입하십시오. [**opencode.ai/discord**](https://opencode.ai/discord) * * * [일반적인 문제](https://opencode.ai/docs/ko/troubleshooting#%EC%9D%BC%EB%B0%98%EC%A0%81%EC%9D%B8-%EB%AC%B8%EC%A0%9C) --------------------------------------------------------------------------------------------------------------- 몇 가지 일반적인 문제와 해결 방법. * * * [opencode가 시작되지 않습니다.](https://opencode.ai/docs/ko/troubleshooting#opencode%EA%B0%80-%EC%8B%9C%EC%9E%91%EB%90%98%EC%A7%80-%EC%95%8A%EC%8A%B5%EB%8B%88%EB%8B%A4) ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. 오류 메시지에 대한 로그 확인 2. terminal에 있는 산출을 보기 위하여 `--print-logs`로 달리기를 시도하십시오 3. 당신은 `opencode upgrade`를 가진 최신 버전이 있는 것을 지킵니다 * * * ### [인증 문제](https://opencode.ai/docs/ko/troubleshooting#%EC%9D%B8%EC%A6%9D-%EB%AC%B8%EC%A0%9C) 1. TUI에서 `/connect` 명령으로 다시 입력 시도 2. API 키가 유효하다는 것을 확인 3. 네트워크가 공급자의 API에 연결을 허용 * * * #### [모델을 사용할 수 없음](https://opencode.ai/docs/ko/troubleshooting#%EB%AA%A8%EB%8D%B8%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%A0-%EC%88%98-%EC%97%86%EC%9D%8C) 1. 공급자와 정통한 확인 2. config의 모델명을 수정한다. 3. 몇몇 모형은 특정한 접근 또는 구독을 요구할지도 모릅니다 만약 당신이 `ProviderModelNotFoundError`에 직면 하는 경우 가장 가능성이 잘못 모델 어딘가를 나타냅니다. 모형은 이렇게 참고되어야 합니다: `/` 예제: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` 당신이 액세스 할 수있는 모델을 파악하려면, `opencode models`를 실행 * * * [ProviderInitError](https://opencode.ai/docs/ko/troubleshooting#provideriniterror) ----------------------------------------------------------------------------------- ProviderInitError가 발생하면 잘못된 구성이나 손상된 구성이 있습니다. 해결하기: 1. 첫째로, 당신의 공급자는 [providers guide](https://opencode.ai/docs/ko/providers) 를 따르기 위하여 제대로 설치됩니다 2. 문제가 발생하면 저장된 구성을 삭제하십시오. rm -rf ~/.local/share/opencode Windows에서, `WIN+R`를 누르고 삭제하십시오: `%USERPROFILE%\.local\share\opencode` 3. TUI의 `/connect` 명령을 사용하여 공급자와 재해. * * * ### [AI\_APICallError 및 공급자 패키지 문제](https://opencode.ai/docs/ko/troubleshooting#ai_apicallerror-%EB%B0%8F-%EA%B3%B5%EA%B8%89%EC%9E%90-%ED%8C%A8%ED%82%A4%EC%A7%80-%EB%AC%B8%EC%A0%9C) API 호출 오류가 발생하면, 이 공급 업체 패키지로 인해 발생할 수 있습니다. opencode 동적 설치 공급자 패키지 (OpenAI, Anthropic, Google 등) 필요 하 고 로컬로 캐시. 공급자 패키지 문제를 해결하려면: 1. 공급자 포장 캐시를 지우십시오: rm -rf ~/.cache/opencode Windows에서, `WIN+R`를 누르고 삭제하십시오: `%USERPROFILE%\.cache\opencode` 2. 최신 공급자 포장을 재설치하는 Restart opencode 이것은 종종 모델 매개 변수와 API 변경과 호환성 문제를 해결하는 공급자 패키지의 가장 최근 버전을 다운로드하기 위해 opencode를 강제합니다. * * * #### [Linux에서 복사/붙여넣기 작동 안 함](https://opencode.ai/docs/ko/troubleshooting#linux%EC%97%90%EC%84%9C-%EB%B3%B5%EC%82%AC%EB%B6%99%EC%97%AC%EB%84%A3%EA%B8%B0-%EC%9E%91%EB%8F%99-%EC%95%88-%ED%95%A8) Linux 사용자는 다음과 같은 클립 보드 유틸리티 중 하나가 복사 / 붙여 넣기 기능에 설치해야합니다. \*\* X11 시스템:\*\* apt install -y xclip# orapt install -y xsel **웨이랜드 시스템:** apt install -y wl-clipboard \*\* 헤드리스 환경에 대한:\*\* apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode는 당신이 Wayland를 사용하고 `wl-clipboard`를 선호하는 경우에 검출할 것입니다, 그렇지 않으면의 순서에 있는 클립보드 공구를 찾아낼 것입니다: `xclip`와 `xsel`. --- # 插件 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/plugins#_top) 插件 == 编写自己的插件来扩展 OpenCode。 插件允许你通过挂钩各种事件和自定义行为来扩展 OpenCode。你可以创建插件来添加新功能、集成外部服务,或修改 OpenCode 的默认行为。 如需了解示例,请查看社区创建的[插件](https://opencode.ai/docs/ecosystem#plugins) 。 * * * [使用插件](https://opencode.ai/docs/zh-cn/plugins#%E4%BD%BF%E7%94%A8%E6%8F%92%E4%BB%B6) ------------------------------------------------------------------------------------ 有两种方式加载插件。 * * * ### [从本地文件加载](https://opencode.ai/docs/zh-cn/plugins#%E4%BB%8E%E6%9C%AC%E5%9C%B0%E6%96%87%E4%BB%B6%E5%8A%A0%E8%BD%BD) 将 JavaScript 或 TypeScript 文件放置在插件目录中。 * `.opencode/plugins/` - 项目级插件 * `~/.config/opencode/plugins/` - 全局插件 这些目录中的文件会在启动时自动加载。 * * * ### [从 npm 加载](https://opencode.ai/docs/zh-cn/plugins#%E4%BB%8E-npm-%E5%8A%A0%E8%BD%BD) 在配置文件中指定 npm 包。 { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} 支持常规和带作用域的 npm 包。 浏览[生态系统](https://opencode.ai/docs/ecosystem#plugins) 中的可用插件。 * * * ### [插件的安装方式](https://opencode.ai/docs/zh-cn/plugins#%E6%8F%92%E4%BB%B6%E7%9A%84%E5%AE%89%E8%A3%85%E6%96%B9%E5%BC%8F) **npm 插件**在启动时使用 Bun 自动安装。包及其依赖项会缓存在 `~/.cache/opencode/node_modules/` 中。 **本地插件**直接从插件目录加载。如果需要使用外部包,你必须在配置目录中创建 `package.json`(参见[依赖项](https://opencode.ai/docs/zh-cn/plugins#dependencies) ),或者将插件发布到 npm 并[将其添加到配置中](https://opencode.ai/docs/config#plugins) 。 * * * ### [加载顺序](https://opencode.ai/docs/zh-cn/plugins#%E5%8A%A0%E8%BD%BD%E9%A1%BA%E5%BA%8F) 插件从所有来源加载,所有钩子按顺序执行。加载顺序为: 1. 全局配置 (`~/.config/opencode/opencode.json`) 2. 项目配置 (`opencode.json`) 3. 全局插件目录 (`~/.config/opencode/plugins/`) 4. 项目插件目录 (`.opencode/plugins/`) 名称和版本相同的重复 npm 包只会加载一次。但本地插件和名称相似的 npm 插件会分别独立加载。 * * * [创建插件](https://opencode.ai/docs/zh-cn/plugins#%E5%88%9B%E5%BB%BA%E6%8F%92%E4%BB%B6) ------------------------------------------------------------------------------------ 插件是一个 **JavaScript/TypeScript 模块**,它导出一个或多个插件函数。每个函数接收一个上下文对象,并返回一个钩子对象。 * * * ### [依赖项](https://opencode.ai/docs/zh-cn/plugins#%E4%BE%9D%E8%B5%96%E9%A1%B9) 本地插件和自定义工具可以使用外部 npm 包。在配置目录中添加一个 `package.json`,列出所需的依赖项。 { "dependencies": { "shescape": "^2.1.0" }} OpenCode 会在启动时运行 `bun install` 来安装这些依赖项。之后你的插件和工具就可以导入它们了。 import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [基本结构](https://opencode.ai/docs/zh-cn/plugins#%E5%9F%BA%E6%9C%AC%E7%BB%93%E6%9E%84) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} 插件函数接收以下参数: * `project`:当前项目信息。 * `directory`:当前工作目录。 * `worktree`:git 工作树路径。 * `client`:用于与 AI 交互的 OpenCode SDK 客户端。 * `$`:Bun 的 [Shell API](https://bun.com/docs/runtime/shell) ,用于执行命令。 * * * ### [TypeScript 支持](https://opencode.ai/docs/zh-cn/plugins#typescript-%E6%94%AF%E6%8C%81) 对于 TypeScript 插件,你可以从插件包中导入类型: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [事件](https://opencode.ai/docs/zh-cn/plugins#%E4%BA%8B%E4%BB%B6) 插件可以订阅事件,如下方示例部分所示。以下是所有可用事件的列表。 #### [命令事件](https://opencode.ai/docs/zh-cn/plugins#%E5%91%BD%E4%BB%A4%E4%BA%8B%E4%BB%B6) * `command.executed` #### [文件事件](https://opencode.ai/docs/zh-cn/plugins#%E6%96%87%E4%BB%B6%E4%BA%8B%E4%BB%B6) * `file.edited` * `file.watcher.updated` #### [安装事件](https://opencode.ai/docs/zh-cn/plugins#%E5%AE%89%E8%A3%85%E4%BA%8B%E4%BB%B6) * `installation.updated` #### [LSP 事件](https://opencode.ai/docs/zh-cn/plugins#lsp-%E4%BA%8B%E4%BB%B6) * `lsp.client.diagnostics` * `lsp.updated` #### [消息事件](https://opencode.ai/docs/zh-cn/plugins#%E6%B6%88%E6%81%AF%E4%BA%8B%E4%BB%B6) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [权限事件](https://opencode.ai/docs/zh-cn/plugins#%E6%9D%83%E9%99%90%E4%BA%8B%E4%BB%B6) * `permission.asked` * `permission.replied` #### [服务器事件](https://opencode.ai/docs/zh-cn/plugins#%E6%9C%8D%E5%8A%A1%E5%99%A8%E4%BA%8B%E4%BB%B6) * `server.connected` #### [会话事件](https://opencode.ai/docs/zh-cn/plugins#%E4%BC%9A%E8%AF%9D%E4%BA%8B%E4%BB%B6) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [待办事项事件](https://opencode.ai/docs/zh-cn/plugins#%E5%BE%85%E5%8A%9E%E4%BA%8B%E9%A1%B9%E4%BA%8B%E4%BB%B6) * `todo.updated` #### [Shell 事件](https://opencode.ai/docs/zh-cn/plugins#shell-%E4%BA%8B%E4%BB%B6) * `shell.env` #### [工具事件](https://opencode.ai/docs/zh-cn/plugins#%E5%B7%A5%E5%85%B7%E4%BA%8B%E4%BB%B6) * `tool.execute.after` * `tool.execute.before` #### [TUI 事件](https://opencode.ai/docs/zh-cn/plugins#tui-%E4%BA%8B%E4%BB%B6) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [示例](https://opencode.ai/docs/zh-cn/plugins#%E7%A4%BA%E4%BE%8B) ---------------------------------------------------------------- 以下是一些可用于扩展 OpenCode 的插件示例。 * * * ### [发送通知](https://opencode.ai/docs/zh-cn/plugins#%E5%8F%91%E9%80%81%E9%80%9A%E7%9F%A5) 在特定事件发生时发送通知: 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"'` } }, }} 这里使用 `osascript` 在 macOS 上运行 AppleScript 来发送通知。 * * * ### [.env 保护](https://opencode.ai/docs/zh-cn/plugins#env-%E4%BF%9D%E6%8A%A4) 阻止 OpenCode 读取 `.env` 文件: 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") } }, }} * * * ### [注入环境变量](https://opencode.ai/docs/zh-cn/plugins#%E6%B3%A8%E5%85%A5%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F) 将环境变量注入所有 Shell 执行(AI 工具和用户终端): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [自定义工具](https://opencode.ai/docs/zh-cn/plugins#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%B7%A5%E5%85%B7) 插件还可以为 OpenCode 添加自定义工具: 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})` }, }), }, }} `tool` 辅助函数用于创建 OpenCode 可调用的自定义工具。它接受一个 Zod schema 函数,并返回一个工具定义,包含: * `description`:工具的功能描述 * `args`:工具参数的 Zod schema * `execute`:工具被调用时执行的函数 你的自定义工具将与内置工具一起在 OpenCode 中可用。 * * * ### [日志记录](https://opencode.ai/docs/zh-cn/plugins#%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95) 使用 `client.app.log()` 代替 `console.log` 进行结构化日志记录: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} 日志级别:`debug`、`info`、`warn`、`error`。详情请参阅 [SDK 文档](https://opencode.ai/docs/sdk) 。 * * * ### [压缩钩子](https://opencode.ai/docs/zh-cn/plugins#%E5%8E%8B%E7%BC%A9%E9%92%A9%E5%AD%90) 自定义会话压缩时包含的上下文: 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`) }, }} `experimental.session.compacting` 钩子在 LLM 生成续接摘要之前触发。使用它来注入默认压缩提示词可能遗漏的领域特定上下文。 你还可以通过设置 `output.prompt` 来完全替换压缩提示词: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} 当设置了 `output.prompt` 时,它会完全替换默认的压缩提示词。在这种情况下,`output.context` 数组将被忽略。 --- # Complementos | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/plugins#_top) Complementos ============ Escriba sus propios complementos para extender OpenCode. Los complementos le permiten extender OpenCode al conectarse a varios eventos y personalizar el comportamiento. Puede crear complementos para agregar nuevas funciones, integrarlos con servicios externos o modificar el comportamiento predeterminado de OpenCode. Para ver ejemplos, consulte los [complementos](https://opencode.ai/docs/ecosystem#plugins) creados por la comunidad. * * * [Usar un complemento](https://opencode.ai/docs/es/plugins#usar-un-complemento) ------------------------------------------------------------------------------- Hay dos formas de cargar complementos. * * * ### [Desde archivos locales](https://opencode.ai/docs/es/plugins#desde-archivos-locales) Coloque los archivos JavaScript o TypeScript en el directorio del complemento. * `.opencode/plugins/` - Complementos a nivel de proyecto * `~/.config/opencode/plugins/` - Complementos globales Los archivos en estos directorios se cargan automáticamente al inicio. * * * ### [Desde npm](https://opencode.ai/docs/es/plugins#desde-npm) Especifique paquetes npm en su archivo de configuración. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Se admiten paquetes npm regulares y de alcance. Explore los complementos disponibles en el [ecosistema](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Cómo se instalan los complementos](https://opencode.ai/docs/es/plugins#c%C3%B3mo-se-instalan-los-complementos) Los **complementos npm** se instalan automáticamente usando Bun al inicio. Los paquetes y sus dependencias se almacenan en caché en `~/.cache/opencode/node_modules/`. **Los complementos locales** se cargan directamente desde el directorio de complementos. Para usar paquetes externos, debe crear un `package.json` dentro de su directorio de configuración (consulte [Dependencias](https://opencode.ai/docs/es/plugins#dependencies) ), o publicar el complemento en npm y [agregarlo a su configuración](https://opencode.ai/docs/config#plugins) . * * * ### [Orden de carga](https://opencode.ai/docs/es/plugins#orden-de-carga) Los complementos se cargan desde todas las fuentes y todos los enlaces se ejecutan en secuencia. El orden de carga es: 1. Configuración global (`~/.config/opencode/opencode.json`) 2. Configuración del proyecto (`opencode.json`) 3. Directorio global de complementos (`~/.config/opencode/plugins/`) 4. Directorio de complementos del proyecto (`.opencode/plugins/`) Los paquetes npm duplicados con el mismo nombre y versión se cargan una vez. Sin embargo, un complemento local y un complemento npm con nombres similares se cargan por separado. * * * [Crear un complemento](https://opencode.ai/docs/es/plugins#crear-un-complemento) --------------------------------------------------------------------------------- Un complemento es un módulo **JavaScript/TypeScript** que exporta uno o más complementos. funciones. Cada función recibe un objeto de contexto y devuelve un objeto de enlace. * * * ### [Dependencias](https://opencode.ai/docs/es/plugins#dependencias) Los complementos locales y las herramientas personalizadas pueden utilizar paquetes npm externos. Agregue un `package.json` a su directorio de configuración con las dependencias que necesita. { "dependencies": { "shescape": "^2.1.0" }} OpenCode ejecuta `bun install` al inicio para instalarlos. Luego, sus complementos y herramientas pueden importarlos. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Estructura básica](https://opencode.ai/docs/es/plugins#estructura-b%C3%A1sica) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} La función del complemento recibe: * `project`: La información actual del proyecto. * `directory`: El directorio de trabajo actual. * `worktree`: La ruta del árbol de trabajo de git. * `client`: Un cliente SDK opencode para interactuar con la IA. * `$`: [shell API](https://bun.com/docs/runtime/shell) de Bun para ejecutar comandos. * * * ### [Soporte TypeScript](https://opencode.ai/docs/es/plugins#soporte-typescript) Para los complementos TypeScript, puede importar tipos desde el paquete de complementos: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Eventos](https://opencode.ai/docs/es/plugins#eventos) Los complementos pueden suscribirse a eventos como se ve a continuación en la sección Ejemplos. Aquí hay una lista de los diferentes eventos disponibles. #### [Eventos de comando](https://opencode.ai/docs/es/plugins#eventos-de-comando) * `command.executed` #### [Eventos de archivo](https://opencode.ai/docs/es/plugins#eventos-de-archivo) * `file.edited` * `file.watcher.updated` #### [Eventos de instalación](https://opencode.ai/docs/es/plugins#eventos-de-instalaci%C3%B3n) * `installation.updated` #### [Eventos LSP](https://opencode.ai/docs/es/plugins#eventos-lsp) * `lsp.client.diagnostics` * `lsp.updated` #### [Eventos de mensajes](https://opencode.ai/docs/es/plugins#eventos-de-mensajes) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Eventos de permiso](https://opencode.ai/docs/es/plugins#eventos-de-permiso) * `permission.asked` * `permission.replied` #### [Eventos del servidor](https://opencode.ai/docs/es/plugins#eventos-del-servidor) * `server.connected` #### [Eventos de sesión](https://opencode.ai/docs/es/plugins#eventos-de-sesi%C3%B3n) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Eventos de Todo](https://opencode.ai/docs/es/plugins#eventos-de-todo) * `todo.updated` #### [Eventos de Shell](https://opencode.ai/docs/es/plugins#eventos-de-shell) * `shell.env` #### [Eventos de herramientas](https://opencode.ai/docs/es/plugins#eventos-de-herramientas) * `tool.execute.after` * `tool.execute.before` #### [Eventos TUI](https://opencode.ai/docs/es/plugins#eventos-tui) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Ejemplos](https://opencode.ai/docs/es/plugins#ejemplos) --------------------------------------------------------- A continuación se muestran algunos ejemplos de complementos que puede utilizar para ampliar opencode. * * * ### [Enviar notificaciones](https://opencode.ai/docs/es/plugins#enviar-notificaciones) Enviar notificaciones cuando ocurran ciertos eventos: 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"'` } }, }} Estamos usando `osascript` para ejecutar AppleScript en macOS. Aquí lo estamos usando para enviar notificaciones. * * * ### [Protección .env](https://opencode.ai/docs/es/plugins#protecci%C3%B3n-env) Evite que opencode lea archivos `.env`: 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") } }, }} * * * ### [Inyectar variables de entorno](https://opencode.ai/docs/es/plugins#inyectar-variables-de-entorno) Inyecte variables de entorno en toda la ejecución del shell (herramientas de inteligencia artificial y terminales de usuario): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Herramientas personalizadas](https://opencode.ai/docs/es/plugins#herramientas-personalizadas) Los complementos también pueden agregar herramientas personalizadas a opencode: 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})` }, }), }, }} El ayudante `tool` crea una herramienta personalizada a la que opencode puede llamar. Toma una función de esquema Zod y devuelve una definición de herramienta con: * `description`: Qué hace la herramienta * `args`: Esquema Zod para los argumentos de la herramienta. * `execute`: Función que se ejecuta cuando se llama a la herramienta Sus herramientas personalizadas estarán disponibles para opencode junto con las herramientas integradas. * * * ### [Registro](https://opencode.ai/docs/es/plugins#registro) Utilice `client.app.log()` en lugar de `console.log` para el registro estructurado: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Niveles: `debug`, `info`, `warn`, `error`. Consulte la [documentación del SDK](https://opencode.ai/docs/sdk) para obtener más detalles. * * * ### [Hooks de compactación](https://opencode.ai/docs/es/plugins#hooks-de-compactaci%C3%B3n) Personalice el contexto incluido cuando se compacta una sesión: 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`) }, }} El hook `experimental.session.compacting` se activa antes de que LLM genere un resumen de continuación. Úselo para inyectar contexto específico del dominio que el mensaje de compactación predeterminado omitiría. También puede reemplazar completamente el mensaje de compactación configurando `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Cuando se configura `output.prompt`, reemplaza completamente el mensaje de compactación predeterminado. En este caso, se ignora la matriz `output.context`. --- # Raccourcis clavier | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/keybinds#_top) Raccourcis clavier ================== Personnalisez vos raccourcis clavier. OpenCode a une liste de raccourcis clavier que vous pouvez personnaliser via la configuration OpenCode. { "$schema": "https://opencode.ai/config.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Touche Leader](https://opencode.ai/docs/fr/keybinds#touche-leader) -------------------------------------------------------------------- OpenCode utilise une touche `leader` pour la plupart des raccourcis clavier. Cela évite les conflits dans votre terminal. Par défaut, `ctrl+x` est la touche leader et la plupart des actions nécessitent que vous appuyiez d’abord sur la touche leader, puis sur le raccourci. Par exemple, pour démarrer une nouvelle session, appuyez d’abord sur `ctrl+x`, puis sur `n`. Vous n’avez pas besoin d’utiliser une touche leader pour vos raccourcis clavier, mais nous vous recommandons de le faire. * * * [Désactiver le raccourci clavier](https://opencode.ai/docs/fr/keybinds#d%C3%A9sactiver-le-raccourci-clavier) ------------------------------------------------------------------------------------------------------------- Vous pouvez désactiver un raccourci clavier en ajoutant la clé à votre configuration avec la valeur `none`. { "$schema": "https://opencode.ai/config.json", "keybinds": { "session_compact": "none" }} * * * [Raccourcis de saisie desktop](https://opencode.ai/docs/fr/keybinds#raccourcis-de-saisie-desktop) -------------------------------------------------------------------------------------------------- Le champ de saisie de l’application de bureau OpenCode prend en charge les raccourcis courants de style Readline/Emacs pour l’édition de texte. Ceux-ci sont intégrés et actuellement non configurables via `opencode.json`. | Raccourci | Actions | | --- | --- | | `ctrl+a` | Déplacer au début de la ligne actuelle | | `ctrl+e` | Aller à la fin de la ligne actuelle | | `ctrl+b` | Reculer le curseur d’un caractère | | `ctrl+f` | Avancer le curseur d’un caractère | | `alt+b` | Reculer le curseur d’un mot | | `alt+f` | Avancer le curseur d’un mot | | `ctrl+d` | Supprimer le caractère sous le curseur | | `ctrl+k` | Couper jusqu’à la fin de la ligne | | `ctrl+u` | Couper jusqu’au début de la ligne | | `ctrl+w` | Couper le mot précédent | | `alt+d` | Couper le mot suivant | | `ctrl+t` | Transposer les caractères | | `ctrl+g` | Annuler les popovers/abandonner l’exécution de la réponse | * * * [Maj+Entrée](https://opencode.ai/docs/fr/keybinds#majentr%C3%A9e) ------------------------------------------------------------------ Certains terminaux n’envoient pas de touches de modification avec Entrée par défaut. Vous devrez peut-être configurer votre terminal pour envoyer `Shift+Enter` comme séquence d’échappement. ### [Windows Terminal](https://opencode.ai/docs/fr/keybinds#windows-terminal) Ouvrez votre `settings.json` à : %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Ajoutez ceci au tableau `actions` de niveau racine : "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Ajoutez ceci au tableau `keybindings` de niveau racine :\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Enregistrez le fichier et redémarrez le terminal Windows ou ouvrez un nouvel onglet. --- # Сочетания клавиш | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/keybinds#_top) Сочетания клавиш ================ Настройте свои сочетания клавиш. opencode имеет список сочетаний клавиш, которые вы можете настроить через `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Клавиша Leader](https://opencode.ai/docs/ru/keybinds#%D0%BA%D0%BB%D0%B0%D0%B2%D0%B8%D1%88%D0%B0-leader) --------------------------------------------------------------------------------------------------------- opencode использует клавишу `leader` для большинства сочетаний клавиш. Это позволяет избежать конфликтов в вашем терминале. По умолчанию `ctrl+x` является клавишей leader, и для большинства действий требуется сначала нажать клавишу leader, а затем сочетание клавиш. Например, чтобы начать новый сеанс, сначала нажмите `ctrl+x`, а затем нажмите `n`. Вам не обязательно использовать клавишу leader для привязок клавиш, но мы рекомендуем это сделать. * * * [Отключение привязки клавиш](https://opencode.ai/docs/ru/keybinds#%D0%BE%D1%82%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BF%D1%80%D0%B8%D0%B2%D1%8F%D0%B7%D0%BA%D0%B8-%D0%BA%D0%BB%D0%B0%D0%B2%D0%B8%D1%88) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Вы можете отключить привязку клавиш, добавив ключ в `tui.json` со значением «none». { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Шорткаты в Desktop-приложении](https://opencode.ai/docs/ru/keybinds#%D1%88%D0%BE%D1%80%D1%82%D0%BA%D0%B0%D1%82%D1%8B-%D0%B2-desktop-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B8) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Ввод приглашения настольного приложения opencode поддерживает распространенные сочетания клавиш в стиле Readline/Emacs для редактирования текста. Они встроены и в настоящее время не настраиваются через `opencode.json`. | Ярлык | Действие | | --- | --- | | `ctrl+a` | Перейти к началу текущей строки | | `ctrl+e` | Перейти к концу текущей строки | | `ctrl+b` | Переместить курсор на один символ назад | | `ctrl+f` | Переместить курсор на один символ вперед | | `alt+b` | Переместить курсор на одно слово назад | | `alt+f` | Переместить курсор вперед на одно слово | | `ctrl+d` | Удалить символ под курсором | | `ctrl+k` | Удалить до конца строки | | `ctrl+u` | Удалить до начала строки | | `ctrl+w` | Удалить предыдущее слово | | `alt+d` | Удалить следующее слово | | `ctrl+t` | Поменять местами символы | | `ctrl+g` | Отменить всплывающие окна/прервать выполнение ответа | * * * [Shift+Enter](https://opencode.ai/docs/ru/keybinds#shiftenter) --------------------------------------------------------------- Некоторые терминалы по умолчанию не отправляют клавиши-модификаторы с Enter. Возможно, вам придется настроить терминал на отправку `Shift+Enter` в качестве escape-последовательности. ### [Windows Terminal](https://opencode.ai/docs/ru/keybinds#windows-terminal) Откройте свой `settings.json` по адресу: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Добавьте это в массив `actions` корневого уровня: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Добавьте это в массив `keybindings` корневого уровня:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Сохраните файл и перезапустите Windows Terminal или откройте новую вкладку. --- # Atalhos de Teclado | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/keybinds#_top) Atalhos de Teclado ================== Personalize seus atalhos de teclado. O opencode tem uma lista de atalhos de teclado que você pode personalizar através de `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Tecla líder](https://opencode.ai/docs/pt-br/keybinds#tecla-l%C3%ADder) ------------------------------------------------------------------------ O opencode usa uma tecla `leader` para a maioria dos atalhos de teclado. Isso evita conflitos no seu terminal. Por padrão, `ctrl+x` é a tecla líder e a maioria das ações requer que você primeiro pressione a tecla líder e depois o atalho. Por exemplo, para iniciar uma nova sessão, você primeiro pressiona `ctrl+x` e depois pressiona `n`. Você não precisa usar uma tecla líder para seus atalhos, mas recomendamos que o faça. * * * [Desativar atalho](https://opencode.ai/docs/pt-br/keybinds#desativar-atalho) ----------------------------------------------------------------------------- Você pode desativar um atalho adicionando a tecla à sua configuração com um valor de “none”. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Atalhos do prompt do desktop](https://opencode.ai/docs/pt-br/keybinds#atalhos-do-prompt-do-desktop) ----------------------------------------------------------------------------------------------------- O prompt de entrada do aplicativo desktop opencode suporta atalhos comuns de estilo Readline/Emacs para edição de texto. Estes são embutidos e atualmente não são configuráveis via `opencode.json`. | Atalho | Ação | | --- | --- | | `ctrl+a` | Mover para o início da linha atual | | `ctrl+e` | Mover para o final da linha atual | | `ctrl+b` | Mover o cursor uma posição para trás | | `ctrl+f` | Mover o cursor uma posição para frente | | `alt+b` | Mover o cursor uma palavra para trás | | `alt+f` | Mover o cursor uma palavra para frente | | `ctrl+d` | Deletar o caractere sob o cursor | | `ctrl+k` | Matar até o final da linha | | `ctrl+u` | Matar até o início da linha | | `ctrl+w` | Matar a palavra anterior | | `alt+d` | Matar a próxima palavra | | `ctrl+t` | Transpor caracteres | | `ctrl+g` | Cancelar popovers / abortar resposta em execução | * * * [Shift+Enter](https://opencode.ai/docs/pt-br/keybinds#shiftenter) ------------------------------------------------------------------ Alguns terminais não enviam teclas modificadoras com Enter por padrão. Você pode precisar configurar seu terminal para enviar `Shift+Enter` como uma sequência de escape. ### [Windows Terminal](https://opencode.ai/docs/pt-br/keybinds#windows-terminal) Abra seu `settings.json` em: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Adicione isso ao array `actions` de nível raiz: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Adicione isso ao array `keybindings` de nível raiz:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Salve o arquivo e reinicie o Windows Terminal ou abra uma nova aba. --- # اختصارات لوحة المفاتيح | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/keybinds#_top) اختصارات لوحة المفاتيح ====================== خصّص اختصارات لوحة المفاتيح. يوفّر OpenCode قائمة باختصارات لوحة المفاتيح يمكنك تخصيصها عبر إعدادات OpenCode. { "$schema": "https://opencode.ai/config.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [مفتاح القائد](https://opencode.ai/docs/ar/keybinds#%D9%85%D9%81%D8%AA%D8%A7%D8%AD-%D8%A7%D9%84%D9%82%D8%A7%D8%A6%D8%AF) ------------------------------------------------------------------------------------------------------------------------- يستخدم OpenCode مفتاح `leader` لمعظم اختصارات لوحة المفاتيح. يساعد ذلك على تجنّب التعارضات في terminal لديك. افتراضيا، يكون `ctrl+x` هو مفتاح القائد، وتتطلّب معظم الإجراءات أن تضغط أولا مفتاح القائد ثم الاختصار. على سبيل المثال، لبدء جلسة جديدة اضغط `ctrl+x` أولا ثم اضغط `n`. لا يلزم استخدام مفتاح قائد لاختصاراتك، لكننا نوصي بذلك. * * * [تعطيل اختصار](https://opencode.ai/docs/ar/keybinds#%D8%AA%D8%B9%D8%B7%D9%8A%D9%84-%D8%A7%D8%AE%D8%AA%D8%B5%D8%A7%D8%B1) ------------------------------------------------------------------------------------------------------------------------- يمكنك تعطيل أي اختصار بإضافة معرّف الاختصار إلى ملف الإعدادات بقيمة “none”. { "$schema": "https://opencode.ai/config.json", "keybinds": { "session_compact": "none" }} * * * [اختصارات موجّه سطح المكتب](https://opencode.ai/docs/ar/keybinds#%D8%A7%D8%AE%D8%AA%D8%B5%D8%A7%D8%B1%D8%A7%D8%AA-%D9%85%D9%88%D8%AC%D9%91%D9%87-%D8%B3%D8%B7%D8%AD-%D8%A7%D9%84%D9%85%D9%83%D8%AA%D8%A8) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- يدعم حقل إدخال الموجّه في تطبيق OpenCode لسطح المكتب اختصارات شائعة لتحرير النص على نمط Readline/Emacs. هذه الاختصارات مدمجة حاليا ولا يمكن تخصيصها عبر `opencode.json`. | الاختصار | الإجراء | | --- | --- | | `ctrl+a` | الانتقال إلى بداية السطر الحالي | | `ctrl+e` | الانتقال إلى نهاية السطر الحالي | | `ctrl+b` | تحريك المؤشر للخلف حرفا واحدا | | `ctrl+f` | تحريك المؤشر للأمام حرفا واحدا | | `alt+b` | تحريك المؤشر للخلف كلمة واحدة | | `alt+f` | تحريك المؤشر للأمام كلمة واحدة | | `ctrl+d` | حذف الحرف الموجود تحت المؤشر | | `ctrl+k` | حذف حتى نهاية السطر | | `ctrl+u` | حذف حتى بداية السطر | | `ctrl+w` | حذف الكلمة السابقة | | `alt+d` | حذف الكلمة التالية | | `ctrl+t` | تبديل موضعي حرفين | | `ctrl+g` | إلغاء النوافذ المنبثقة / إيقاف الرد الجاري | * * * [مفتاح Shift+Enter](https://opencode.ai/docs/ar/keybinds#%D9%85%D9%81%D8%AA%D8%A7%D8%AD-shiftenter) ---------------------------------------------------------------------------------------------------- بعض تطبيقات terminal لا ترسل مفاتيح التعديل مع Enter افتراضيا. قد تحتاج إلى ضبط terminal لإرسال `Shift+Enter` كسلسلة هروب. ### [Windows Terminal](https://opencode.ai/docs/ar/keybinds#windows-terminal) افتح ملف `settings.json` الموجود في: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json أضف هذا إلى مصفوفة `actions` على مستوى الجذر: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ أضف هذا إلى مصفوفة `keybindings` على مستوى الجذر:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ احفظ الملف ثم أعد تشغيل Windows Terminal أو افتح علامة تبويب جديدة. --- # ปุ่มลัด | OpenCode [Skip to content](https://opencode.ai/docs/th/keybinds#_top) ปุ่มลัด ======= ปรับแต่งปุ่มลัดของคุณ OpenCode มีรายการปุ่มลัดที่คุณปรับแต่งได้ผ่าน `tui.json` { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [ปุ่ม Leader](https://opencode.ai/docs/th/keybinds#%E0%B8%9B%E0%B8%B8%E0%B9%88%E0%B8%A1-leader) ------------------------------------------------------------------------------------------------ OpenCode ใช้ปุ่ม `leader` สำหรับการเชื่อมโยงคีย์ส่วนใหญ่ วิธีนี้จะหลีกเลี่ยงความขัดแย้งใน terminal ของคุณ ตามค่าเริ่มต้น `ctrl+x` จะเป็นปุ่ม leader และการดำเนินการส่วนใหญ่ต้องการให้คุณกดปุ่ม leader ก่อน จากนั้นจึงกดทางลัด ตัวอย่างเช่น หากต้องการเริ่มเซสชันใหม่ คุณต้องกด `ctrl+x` ก่อน จากนั้นจึงกด `n` คุณไม่จำเป็นต้องใช้ปุ่ม leader สำหรับการผูกคีย์ แต่เราขอแนะนำให้ทำเช่นนั้น * * * [ปิดการใช้งานการผูกปุ่ม](https://opencode.ai/docs/th/keybinds#%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9C%E0%B8%B9%E0%B8%81%E0%B8%9B%E0%B8%B8%E0%B9%88%E0%B8%A1) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- คุณสามารถปิดการใช้งานการผูกปุ่มได้โดยการเพิ่มคีย์ลงใน `tui.json` ด้วยค่า “none” { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [ทางลัดพร้อมท์เดสก์ท็อป](https://opencode.ai/docs/th/keybinds#%E0%B8%97%E0%B8%B2%E0%B8%87%E0%B8%A5%E0%B8%B1%E0%B8%94%E0%B8%9E%E0%B8%A3%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%97%E0%B9%8C%E0%B9%80%E0%B8%94%E0%B8%AA%E0%B8%81%E0%B9%8C%E0%B8%97%E0%B9%87%E0%B8%AD%E0%B8%9B) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- การป้อนข้อมูลพร้อมท์ของแอป OpenCode บนเดสก์ท็อปรองรับทางลัด Readline/Emacs-style ทั่วไปสำหรับการแก้ไขข้อความ สิ่งเหล่านี้มีอยู่แล้วภายในและปัจจุบันไม่สามารถกำหนดค่าผ่าน `opencode.json` ได้ | ทางลัด | การกระทำ | | --- | --- | | `ctrl+a` | ย้ายไปที่จุดเริ่มต้นของบรรทัดปัจจุบัน | | `ctrl+e` | ย้ายไปที่จุดสิ้นสุดของบรรทัดปัจจุบัน | | `ctrl+b` | เลื่อนเคอร์เซอร์กลับไปหนึ่งอักขระ | | `ctrl+f` | เลื่อนเคอร์เซอร์ไปข้างหน้าหนึ่งอักขระ | | `alt+b` | เลื่อนเคอร์เซอร์กลับไปหนึ่งคำ | | `alt+f` | เลื่อนเคอร์เซอร์ไปข้างหน้าหนึ่งคำ | | `ctrl+d` | ลบอักขระใต้เคอร์เซอร์ | | `ctrl+k` | ลบจนจบแถว | | `ctrl+u` | ลบจนถึงต้นบรรทัด | | `ctrl+w` | ลบคำก่อนหน้า | | `alt+d` | ลบคำถัดไป | | `ctrl+t` | ย้ายอักขระ | | `ctrl+g` | ยกเลิกป๊อปโอเวอร์ / ยกเลิกการตอบกลับที่ทำงานอยู่ | * * * [Shift+Enter](https://opencode.ai/docs/th/keybinds#shiftenter) --------------------------------------------------------------- terminal บางตัวไม่ส่งคีย์ตัวปรับแต่งพร้อม Enter เป็นค่าเริ่มต้น คุณอาจต้องกำหนดค่า terminal ของคุณให้ส่ง `Shift+Enter` เป็นลำดับหลีก ### [Windows Terminal](https://opencode.ai/docs/th/keybinds#windows-terminal) เปิด `settings.json` ของคุณที่: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json เพิ่มสิ่งนี้ลงในอาร์เรย์ `actions` ระดับรูท: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ เพิ่มสิ่งนี้ลงในอาร์เรย์ `keybindings` ระดับรูท:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ บันทึกไฟล์และรีสตาร์ท Windows Terminal หรือเปิดแท็บใหม่ --- # Web | OpenCode [Skip to content](https://opencode.ai/docs/web#_top) Web === Using OpenCode in your browser. OpenCode can run as a web application in your browser, providing the same powerful AI coding experience without needing a terminal. ![OpenCode Web - New Session](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Getting Started](https://opencode.ai/docs/web#getting-started) ---------------------------------------------------------------- Start the web interface by running: opencode web This starts a local server on `127.0.0.1` with a random available port and automatically opens OpenCode in your default browser. * * * [Configuration](https://opencode.ai/docs/web#configuration) ------------------------------------------------------------ You can configure the web server using command line flags or in your [config file](https://opencode.ai/docs/config) . ### [Port](https://opencode.ai/docs/web#port) By default, OpenCode picks an available port. You can specify a port: opencode web --port 4096 ### [Hostname](https://opencode.ai/docs/web#hostname) By default, the server binds to `127.0.0.1` (localhost only). To make OpenCode accessible on your network: opencode web --hostname 0.0.0.0 When using `0.0.0.0`, OpenCode will display both local and network addresses: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS Discovery](https://opencode.ai/docs/web#mdns-discovery) Enable mDNS to make your server discoverable on the local network: opencode web --mdns This automatically sets the hostname to `0.0.0.0` and advertises the server as `opencode.local`. You can customize the mDNS domain name to run multiple instances on the same network: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/web#cors) To allow additional domains for CORS (useful for custom frontends): opencode web --cors https://example.com ### [Authentication](https://opencode.ai/docs/web#authentication) To protect access, set a password using the `OPENCODE_SERVER_PASSWORD` environment variable: OPENCODE_SERVER_PASSWORD=secret opencode web The username defaults to `opencode` but can be changed with `OPENCODE_SERVER_USERNAME`. * * * [Using the Web Interface](https://opencode.ai/docs/web#using-the-web-interface) -------------------------------------------------------------------------------- Once started, the web interface provides access to your OpenCode sessions. ### [Sessions](https://opencode.ai/docs/web#sessions) View and manage your sessions from the homepage. You can see active sessions and start new ones. ![OpenCode Web - Active Session](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Server Status](https://opencode.ai/docs/web#server-status) Click “See Servers” to view connected servers and their status. ![OpenCode Web - See Servers](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Attaching a Terminal](https://opencode.ai/docs/web#attaching-a-terminal) -------------------------------------------------------------------------- You can attach a terminal TUI to a running web server: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 This allows you to use both the web interface and terminal simultaneously, sharing the same sessions and state. * * * [Config File](https://opencode.ai/docs/web#config-file) -------------------------------------------------------- You can also configure server settings in your `opencode.json` config file: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Command line flags take precedence over config file settings. --- # ウェブ | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/web#_top) ウェブ === ブラウザで OpenCode を使用する。 OpenCode はブラウザで Web アプリケーションとして実行でき、ターミナルを必要とせずに同じ強力な AI コーディングエクスペリエンスを提供します。 ![OpenCode Web - 新しいセッション](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) * * * [はじめる](https://opencode.ai/docs/ja/web#%E3%81%AF%E3%81%98%E3%82%81%E3%82%8B) ----------------------------------------------------------------------------- 以下を実行して Web インターフェースを開始します。 opencode web これにより、利用可能なランダムなポートを使用して `127.0.0.1` でローカルサーバーが起動され、デフォルトのブラウザで OpenCode が自動的に開きます。 * * * [設定](https://opencode.ai/docs/ja/web#%E8%A8%AD%E5%AE%9A) --------------------------------------------------------- コマンドラインフラグを使用するか、[設定ファイル](https://opencode.ai/docs/config) で Web サーバーを設定できます。 ### [ポート](https://opencode.ai/docs/ja/web#%E3%83%9D%E3%83%BC%E3%83%88) デフォルトでは、OpenCode は使用可能なポートを選択します。ポートを指定できます。 opencode web --port 4096 ### [ホスト名](https://opencode.ai/docs/ja/web#%E3%83%9B%E3%82%B9%E3%83%88%E5%90%8D) デフォルトでは、サーバーは `127.0.0.1` (localhost のみ) にバインドされます。ネットワーク上で OpenCode にアクセスできるようにするには: opencode web --hostname 0.0.0.0 `0.0.0.0` を使用すると、OpenCode はローカルアドレスとネットワークアドレスの両方を表示します。 Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS 検出](https://opencode.ai/docs/ja/web#mdns-%E6%A4%9C%E5%87%BA) mDNS を有効にして、ローカルネットワーク上でサーバーを検出できるようにします。 opencode web --mdns これにより、ホスト名が自動的に `0.0.0.0` に設定され、サーバーが `opencode.local` としてアドバタイズされます。 mDNS ドメイン名をカスタマイズして、同じネットワーク上で複数のインスタンスを実行できます。 opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/ja/web#cors) CORS の追加ドメインを許可するには (カスタムフロントエンドに便利): opencode web --cors https://example.com ### [認証](https://opencode.ai/docs/ja/web#%E8%AA%8D%E8%A8%BC) アクセスを保護するには、`OPENCODE_SERVER_PASSWORD` 環境変数を使用してパスワードを設定します。 OPENCODE_SERVER_PASSWORD=secret opencode web ユーザー名のデフォルトは `opencode` ですが、`OPENCODE_SERVER_USERNAME` で変更できます。 * * * [Web インターフェースの使用](https://opencode.ai/docs/ja/web#web-%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%83%95%E3%82%A7%E3%83%BC%E3%82%B9%E3%81%AE%E4%BD%BF%E7%94%A8) ----------------------------------------------------------------------------------------------------------------------------------------------------------- 開始すると、Web インターフェイスから OpenCode セッションにアクセスできるようになります。 ### [セッション](https://opencode.ai/docs/ja/web#%E3%82%BB%E3%83%83%E3%82%B7%E3%83%A7%E3%83%B3) ホームページからセッションを表示および管理します。アクティブなセッションを確認したり、新しいセッションを開始したりできます。 ![OpenCode Web - アクティブなセッション](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [サーバーステータス](https://opencode.ai/docs/ja/web#%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E3%82%B9%E3%83%86%E3%83%BC%E3%82%BF%E3%82%B9) 「サーバーを表示」をクリックすると、接続されているサーバーとそのステータスが表示されます。 ![OpenCode Web - サーバー](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [ターミナルの接続](https://opencode.ai/docs/ja/web#%E3%82%BF%E3%83%BC%E3%83%9F%E3%83%8A%E3%83%AB%E3%81%AE%E6%8E%A5%E7%B6%9A) --------------------------------------------------------------------------------------------------------------------- 実行中の Web サーバーにターミナル TUI を接続できます。 # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 これにより、Web インターフェイスとターミナルの両方を同時に使用し、同じセッションと状態を共有できるようになります。 * * * [設定ファイル](https://opencode.ai/docs/ja/web#%E8%A8%AD%E5%AE%9A%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB) ------------------------------------------------------------------------------------------------- `opencode.json` 設定ファイルでサーバー設定を構成することもできます。 { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} コマンドラインフラグは、設定ファイルの設定よりも優先されます。 --- # TUI | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/tui#_top) TUI === Usando a interface de usuário de terminal opencode. O opencode fornece uma interface de terminal interativa ou TUI para trabalhar em seus projetos com um LLM. Executar opencode inicia o TUI para o diretório atual. opencode Ou você pode iniciá-lo para um diretório de trabalho específico. opencode /path/to/project Uma vez que você esteja no TUI, você pode solicitar com uma mensagem. Faça um resumo rápido da base de código. * * * [Referências de arquivos](https://opencode.ai/docs/pt-br/tui#refer%C3%AAncias-de-arquivos) ------------------------------------------------------------------------------------------- Você pode referenciar arquivos em suas mensagens usando `@`. Isso faz uma busca difusa de arquivos no diretório de trabalho atual. Como a autenticação é tratada em @packages/functions/src/api/index.ts? O conteúdo do arquivo é adicionado à conversa automaticamente. * * * [Comandos Bash](https://opencode.ai/docs/pt-br/tui#comandos-bash) ------------------------------------------------------------------ Comece uma mensagem com `!` para executar um comando de shell. !ls -la A saída do comando é adicionada à conversa como um resultado de ferramenta. * * * [Comandos](https://opencode.ai/docs/pt-br/tui#comandos) -------------------------------------------------------- Ao usar o TUI do opencode, você pode digitar `/` seguido pelo nome de um comando para executar ações rapidamente. Por exemplo: /help A maioria dos comandos também possui atalhos usando `ctrl+x` como a tecla líder, onde `ctrl+x` é a tecla líder padrão. [Saiba mais](https://opencode.ai/docs/keybinds) . Aqui estão todos os comandos de barra disponíveis: * * * ### [connect](https://opencode.ai/docs/pt-br/tui#connect) Adicione um provedor ao opencode. Permite que você selecione entre os provedores disponíveis e adicione suas chaves de API. /connect * * * ### [compact](https://opencode.ai/docs/pt-br/tui#compact) Compacte a sessão atual. _Alias_: `/summarize` /compact **Atalho:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/pt-br/tui#details) Alternar detalhes da execução da ferramenta. /details **Atalho:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/pt-br/tui#editor) Abra um editor externo para compor mensagens. Usa o editor definido na sua variável de ambiente `EDITOR`. [Saiba mais](https://opencode.ai/docs/pt-br/tui#editor-setup) . /editor **Atalho:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/pt-br/tui#exit) Saia do opencode. _Aliases_: `/quit`, `/q` /exit **Atalho:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/pt-br/tui#export) Exporte a conversa atual para Markdown e abra no seu editor padrão. Usa o editor definido na sua variável de ambiente `EDITOR`. [Saiba mais](https://opencode.ai/docs/pt-br/tui#editor-setup) . /export **Atalho:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/pt-br/tui#help) Mostre o diálogo de ajuda. /help **Atalho:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/pt-br/tui#init) Crie ou atualize o arquivo `AGENTS.md`. [Saiba mais](https://opencode.ai/docs/rules) . /init **Atalho:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/pt-br/tui#models) Liste os modelos disponíveis. /models **Atalho:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/pt-br/tui#new) Inicie uma nova sessão. _Alias_: `/clear` /new **Atalho:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/pt-br/tui#redo) Refaça uma mensagem anteriormente desfeita. Disponível apenas após usar `/undo`. Internamente, isso usa Git para gerenciar as alterações de arquivo. Portanto, seu projeto **precisa ser um repositório Git**. /redo **Atalho:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/pt-br/tui#sessions) Liste e alterne entre sessões. _Aliases_: `/resume`, `/continue` /sessions **Atalho:** `ctrl+x l` * * * Compartilhe a sessão atual. [Saiba mais](https://opencode.ai/docs/share) . /share **Atalho:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/pt-br/tui#themes) Liste os temas disponíveis. /themes **Atalho:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/pt-br/tui#thinking) Alternar a visibilidade dos blocos de pensamento/razão na conversa. Quando ativado, você pode ver o processo de raciocínio do modelo para modelos que suportam pensamento estendido. /thinking * * * ### [undo](https://opencode.ai/docs/pt-br/tui#undo) Desfaça a última mensagem na conversa. Remove a mensagem mais recente do usuário, todas as respostas subsequentes e quaisquer alterações de arquivo. Internamente, isso usa Git para gerenciar as alterações de arquivo. Portanto, seu projeto **precisa ser um repositório Git**. /undo **Atalho:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/pt-br/tui#unshare) Descompartilhe a sessão atual. [Saiba mais](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Configuração do Editor](https://opencode.ai/docs/pt-br/tui#configura%C3%A7%C3%A3o-do-editor) ---------------------------------------------------------------------------------------------- Tanto os comandos `/editor` quanto `/export` usam o editor especificado na sua variável de ambiente `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/pt-br/tui#tab-panel-88) * [Windows (CMD)](https://opencode.ai/docs/pt-br/tui#tab-panel-89) * [Windows (PowerShell)](https://opencode.ai/docs/pt-br/tui#tab-panel-90) # Exemplo para nano ou vimexport EDITOR=nanoexport EDITOR=vim # Para editores GUI, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# inclua --waitexport EDITOR="code --wait" Para torná-lo permanente, adicione isso ao seu perfil de shell; `~/.bashrc`, `~/.zshrc`, etc. set EDITOR=notepad # Para editores GUI, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# inclua --waitset EDITOR=code --wait Para torná-lo permanente, use **Propriedades do Sistema** > **Variáveis de Ambiente**. $env:EDITOR = "notepad" # Para editores GUI, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# inclua --wait$env:EDITOR = "code --wait" Para torná-lo permanente, adicione isso ao seu perfil do PowerShell. As opções de editor populares incluem: * `code` - VS Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Editor Neovim * `vim` - Editor Vim * `nano` - Editor Nano * `notepad` - Bloco de Notas do Windows * `subl` - Sublime Text Alguns editores precisam de argumentos de linha de comando para rodar em modo bloqueante. A flag `--wait` faz com que o processo do editor bloqueie até ser fechado. * * * [Configuração](https://opencode.ai/docs/pt-br/tui#configura%C3%A7%C3%A3o) -------------------------------------------------------------------------- Você pode personalizar o comportamento do TUI através de `tui.json` (ou `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Isso é separado do `opencode.json`, que configura o comportamento do servidor/runtime. ### [Opções](https://opencode.ai/docs/pt-br/tui#op%C3%A7%C3%B5es) * `theme` - Define o tema da sua interface. [Saiba mais](https://opencode.ai/docs/themes) . * `keybinds` - Personaliza atalhos de teclado. [Saiba mais](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Ative a aceleração de rolagem no estilo macOS para uma rolagem suave e natural. Quando ativado, a velocidade de rolagem aumenta com gestos de rolagem rápidos e permanece precisa para movimentos mais lentos. **Esta configuração tem precedência sobre `scroll_speed` e a substitui quando ativada.** * `scroll_speed` - Controla quão rápido o TUI rola ao usar comandos de rolagem (mínimo: `0.001`, suporta valores decimais). O padrão é `3`. **Nota: Isso é ignorado se `scroll_acceleration.enabled` estiver definido como `true`.** * `diff_style` - Controla a renderização de diffs. `"auto"` se adapta à largura do terminal, `"stacked"` sempre mostra um layout de coluna única. Use `OPENCODE_TUI_CONFIG` para carregar um caminho de configuração TUI personalizado. * * * [Personalização](https://opencode.ai/docs/pt-br/tui#personaliza%C3%A7%C3%A3o) ------------------------------------------------------------------------------ Você pode personalizar vários aspectos da visualização do TUI usando a paleta de comandos (`ctrl+x h` ou `/help`). Essas configurações persistem entre reinicializações. * * * #### [Exibição do nome de usuário](https://opencode.ai/docs/pt-br/tui#exibi%C3%A7%C3%A3o-do-nome-de-usu%C3%A1rio) Alternar se seu nome de usuário aparece nas mensagens de chat. Acesse isso através de: * Paleta de comandos: Pesquise por “username” ou “hide username” * A configuração persiste automaticamente e será lembrada entre as sessões do TUI --- # TUI | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/tui#_top) TUI === Usando la interfaz de usuario del terminal OpenCode. OpenCode proporciona una interfaz de terminal interactiva o TUI para trabajar en sus proyectos con un LLM. Al ejecutar OpenCode se inicia TUI para el directorio actual. opencode O puede iniciarlo para un directorio de trabajo específico. opencode /path/to/project Una vez que esté en TUI, puede indicarlo con un mensaje. Give me a quick summary of the codebase. * * * [Referencias de archivos](https://opencode.ai/docs/es/tui#referencias-de-archivos) ----------------------------------------------------------------------------------- Puede hacer referencia a archivos en sus mensajes usando `@`. Esto realiza una búsqueda difusa de archivos en el directorio de trabajo actual. How is auth handled in @packages/functions/src/api/index.ts? El contenido del archivo se agrega a la conversación automáticamente. * * * [Comandos bash](https://opencode.ai/docs/es/tui#comandos-bash) --------------------------------------------------------------- Inicie un mensaje con `!` para ejecutar un comando de shell. !ls -la El resultado del comando se agrega a la conversación como resultado de la herramienta. * * * [Comandos](https://opencode.ai/docs/es/tui#comandos) ----------------------------------------------------- Cuando utilice OpenCode TUI, puede escribir `/` seguido de un nombre de comando para ejecutar acciones rápidamente. Por ejemplo: /help La mayoría de los comandos también tienen una combinación de teclas que utiliza `ctrl+x` como tecla principal, donde `ctrl+x` es la tecla principal predeterminada. [Más información](https://opencode.ai/docs/keybinds) . Aquí están todos los comandos de barra diagonal disponibles: * * * ### [connect](https://opencode.ai/docs/es/tui#connect) Agregue un proveedor a OpenCode. Le permite seleccionar entre proveedores disponibles y agregar sus claves API. /connect * * * ### [compact](https://opencode.ai/docs/es/tui#compact) Compacta la sesión actual. _Alias_: `/summarize` /compact **Combinación de teclas:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/es/tui#details) Alternar detalles de ejecución de la herramienta. /details **Combinación de teclas:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/es/tui#editor) Abra un editor externo para redactar mensajes. Utiliza el editor configurado en su variable de entorno `EDITOR`. [Más información](https://opencode.ai/docs/es/tui#editor-setup) . /editor **Combinación de teclas:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/es/tui#exit) Salga de OpenCode. _Alias_: `/quit`, `/q` /exit **Combinación de teclas:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/es/tui#export) Exporte la conversación actual a Markdown y ábrala en su editor predeterminado. Utiliza el editor configurado en su variable de entorno `EDITOR`. [Más información](https://opencode.ai/docs/es/tui#editor-setup) . /export **Combinación de teclas:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/es/tui#help) Muestra el cuadro de diálogo de ayuda. /help **Combinación de teclas:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/es/tui#init) Cree o actualice el archivo `AGENTS.md`. [Más información](https://opencode.ai/docs/rules) . /init **Combinación de teclas:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/es/tui#models) Listar modelos disponibles. /models **Combinación de teclas:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/es/tui#new) Iniciar una nueva sesión. _Alias_: `/clear` /new **Combinación de teclas:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/es/tui#redo) Rehacer un mensaje previamente deshecho. Solo disponible después de usar `/undo`. Internamente, esto utiliza Git para gestionar los cambios de archivos. Entonces tu proyecto **necesita ser un repositorio Git**. /redo **Combinación de teclas:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/es/tui#sessions) Enumere y cambie entre sesiones. _Alias_: `/resume`, `/continue` /sessions **Combinación de teclas:** `ctrl+x l` * * * Compartir la sesión actual. [Más información](https://opencode.ai/docs/share) . /share **Combinación de teclas:** `ctrl+x s` * * * ### [theme](https://opencode.ai/docs/es/tui#theme) Listar temas disponibles. /theme **Combinación de teclas:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/es/tui#thinking) Alterna la visibilidad de los bloques de pensamiento/razonamiento en la conversación. Cuando está habilitado, puede ver el proceso de razonamiento del modelo para los modelos que admiten el pensamiento extendido. /thinking * * * ### [undo](https://opencode.ai/docs/es/tui#undo) Deshacer el último mensaje de la conversación. Elimina el mensaje de usuario más reciente, todas las respuestas posteriores y cualquier cambio de archivo. Internamente, esto utiliza Git para gestionar los cambios de archivos. Entonces tu proyecto **necesita ser un repositorio Git**. /undo **Combinación de teclas:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/es/tui#unshare) Dejar de compartir la sesión actual. [Más información](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Configuración del editor](https://opencode.ai/docs/es/tui#configuraci%C3%B3n-del-editor) ------------------------------------------------------------------------------------------ Tanto el comando `/editor` como el `/export` usan el editor especificado en su variable de entorno `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/es/tui#tab-panel-39) * [Windows (CMD)](https://opencode.ai/docs/es/tui#tab-panel-40) * [Windows (PowerShell)](https://opencode.ai/docs/es/tui#tab-panel-41) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" Para hacerlo permanente, agréguelo a su perfil de shell; `~/.bashrc`, `~/.zshrc`, etc. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait Para hacerlo permanente, use **Propiedades del sistema** > **Entorno Variables**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" Para hacerlo permanente, agréguelo a su perfil de PowerShell. Las opciones de editor populares incluyen: * `code` - Código de Visual Studio * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Editor Neovim * `vim` - Editor Vim * `nano` - Nanoeditor * `notepad` - Windows Bloc de notas * `subl` - Texto sublime Algunos editores necesitan argumentos de línea de comandos para ejecutarse en modo de bloqueo. El indicador `--wait` hace que el proceso del editor se bloquee hasta que se cierre. * * * [Configurar](https://opencode.ai/docs/es/tui#configurar) --------------------------------------------------------- Puede personalizar el comportamiento de TUI a través de `tui.json` (o `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Esto es independiente de `opencode.json`, que configura el comportamiento del servidor/tiempo de ejecución. ### [Opciones](https://opencode.ai/docs/es/tui#opciones) * `theme`: establece su tema de interfaz de usuario. [Más información](https://opencode.ai/docs/themes) . * `keybinds`: personaliza los atajos de teclado. [Más información](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled`: habilite la aceleración de desplazamiento estilo macOS para un desplazamiento suave y natural. Cuando está habilitado, la velocidad de desplazamiento aumenta con gestos de desplazamiento rápido y se mantiene precisa para movimientos más lentos. **Esta configuración tiene prioridad sobre `scroll_speed` y la anula cuando está habilitada.** * `scroll_speed`: controla la rapidez con la que se desplaza el TUI cuando se utilizan comandos de desplazamiento (mínimo: `0.001`, admite valores decimales). El valor predeterminado es `3`. **Nota: Esto se ignora si `scroll_acceleration.enabled` está configurado en `true`.** * `diff_style`: controla la representación de diferencias. `"auto"` se adapta al ancho del terminal, `"stacked"` siempre muestra un diseño de una sola columna. Utilice `OPENCODE_TUI_CONFIG` para cargar una ruta de configuración de TUI personalizada. * * * [Personalización](https://opencode.ai/docs/es/tui#personalizaci%C3%B3n) ------------------------------------------------------------------------ Puede personalizar varios aspectos de la vista TUI usando la paleta de comandos (`ctrl+x h` o `/help`). Estas configuraciones persisten después de los reinicios. * * * #### [Visualización del nombre de usuario](https://opencode.ai/docs/es/tui#visualizaci%C3%B3n-del-nombre-de-usuario) Alterna si tu nombre de usuario aparece en los mensajes de chat. Accede a este a través de: * Paleta de comandos: busque “nombre de usuario” u “ocultar nombre de usuario” * La configuración persiste automáticamente y se recordará en TUI sesiones --- # TUI | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/tui#_top) TUI === OpenCode ターミナルユーザーインターフェイスの使用。 OpenCode は、LLM を使用してプロジェクトを作業するための対話型ターミナルインターフェイスまたは TUI を提供します。 OpenCode を実行すると、現在のディレクトリの TUI が開始されます。 opencode または、特定の作業ディレクトリに対して起動することもできます。 opencode /path/to/project TUI に入ったら、メッセージを表示することができます。 Give me a quick summary of the codebase. * * * [ファイル参照](https://opencode.ai/docs/ja/tui#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%8F%82%E7%85%A7) ------------------------------------------------------------------------------------------------- `@` を使用してメッセージ内のファイルを参照できます。これにより、現在の作業ディレクトリ内であいまいなファイル検索が行われます。 How is auth handled in @packages/functions/src/api/index.ts? ファイルの内容は会話に自動的に追加されます。 * * * [Bash コマンド](https://opencode.ai/docs/ja/tui#bash-%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89) --------------------------------------------------------------------------------------- メッセージを `!` で開始して、シェルコマンドを実行します。 !ls -la コマンドの出力は、ツールの結果として会話に追加されます。 * * * [コマンド](https://opencode.ai/docs/ja/tui#%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89) ----------------------------------------------------------------------------- OpenCode TUI を使用する場合、「`/`」に続いてコマンド名を入力すると、アクションをすばやく実行できます。例えば: /help ほとんどのコマンドには、`ctrl+x` をリーダーキーとして使用するキーバインドもあります。`ctrl+x` がデフォルトのリーダーキーです。 [詳細はこちら](https://opencode.ai/docs/keybinds) 。 利用可能なすべてのスラッシュコマンドは次のとおりです。 * * * ### [接続](https://opencode.ai/docs/ja/tui#%E6%8E%A5%E7%B6%9A) OpenCode にプロバイダーを追加します。利用可能なプロバイダーから選択し、その API キーを追加できます。 /connect * * * ### [コンパクト](https://opencode.ai/docs/ja/tui#%E3%82%B3%E3%83%B3%E3%83%91%E3%82%AF%E3%83%88) 現在のセッションを圧縮します。 _別名_: `/summarize` /compact **キーバインド:** `ctrl+x c` * * * ### [詳細](https://opencode.ai/docs/ja/tui#%E8%A9%B3%E7%B4%B0) ツール実行の詳細を切り替えます。 /details **キーバインド:** `ctrl+x d` * * * ### [エディタ](https://opencode.ai/docs/ja/tui#%E3%82%A8%E3%83%87%E3%82%A3%E3%82%BF) メッセージを作成するために外部エディタを開きます。 `EDITOR` 環境変数に設定されたエディタを使用します。 [詳細はこちら](https://opencode.ai/docs/ja/tui#editor-setup) 。 /editor **キーバインド:** `ctrl+x e` * * * ### [終了](https://opencode.ai/docs/ja/tui#%E7%B5%82%E4%BA%86) OpenCode を終了します。 _エイリアス_: `/quit`、`/q` /exit **キーバインド:** `ctrl+x q` * * * ### [エクスポート](https://opencode.ai/docs/ja/tui#%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88) 現在の会話を Markdown にエクスポートし、デフォルトのエディターで開きます。 `EDITOR` 環境変数に設定されたエディタを使用します。 [詳細はこちら](https://opencode.ai/docs/ja/tui#editor-setup) 。 /export **キーバインド:** `ctrl+x x` * * * ### [ヘルプ](https://opencode.ai/docs/ja/tui#%E3%83%98%E3%83%AB%E3%83%97) ヘルプダイアログを表示します。 /help **キーバインド:** `ctrl+x h` * * * ### [初期化](https://opencode.ai/docs/ja/tui#%E5%88%9D%E6%9C%9F%E5%8C%96) `AGENTS.md` ファイルを作成または更新します。 [詳細はこちら](https://opencode.ai/docs/rules) 。 /init **キーバインド:** `ctrl+x i` * * * ### [モデル](https://opencode.ai/docs/ja/tui#%E3%83%A2%E3%83%87%E3%83%AB) 利用可能なモデルをリストします。 /models **キーバインド:** `ctrl+x m` * * * ### [新規セッション](https://opencode.ai/docs/ja/tui#%E6%96%B0%E8%A6%8F%E3%82%BB%E3%83%83%E3%82%B7%E3%83%A7%E3%83%B3) 新しいセッションを開始します。 _別名_: `/clear` /new **キーバインド:** `ctrl+x n` * * * ### [やり直し](https://opencode.ai/docs/ja/tui#%E3%82%84%E3%82%8A%E7%9B%B4%E3%81%97) 以前に取り消したメッセージをやり直します。 `/undo` を使用した後にのみ使用できます。 内部的には、`undo` を使用してファイルの変更を管理します。したがって、あなたのプロジェクトは **Git リポジトリ** である必要があります。 /redo **キーバインド:** `ctrl+x r` * * * ### [セッション](https://opencode.ai/docs/ja/tui#%E3%82%BB%E3%83%83%E3%82%B7%E3%83%A7%E3%83%B3) セッションを一覧表示して切り替えます。 _エイリアス_: `/resume`、`/continue` /sessions **キーバインド:** `ctrl+x l` * * * ### [共有](https://opencode.ai/docs/ja/tui#%E5%85%B1%E6%9C%89) 現在のセッションを共有します。 [詳細はこちら](https://opencode.ai/docs/share) 。 /share **キーバインド:** `ctrl+x s` * * * ### [テーマ](https://opencode.ai/docs/ja/tui#%E3%83%86%E3%83%BC%E3%83%9E) 利用可能なテーマをリストします。 /theme **キーバインド:** `ctrl+x t` * * * ### [思考](https://opencode.ai/docs/ja/tui#%E6%80%9D%E8%80%83) 会話内の思考/推論ブロックの表示を切り替えます。有効にすると、拡張思考をサポートするモデルの推論プロセスを確認できます。 /thinking * * * ### [元に戻す](https://opencode.ai/docs/ja/tui#%E5%85%83%E3%81%AB%E6%88%BB%E3%81%99) 会話の最後のメッセージを元に戻します。最新のユーザーメッセージ、その後のすべての応答、およびファイルの変更を削除します。 内部的には、`undo` を使用してファイルの変更を管理します。したがって、あなたのプロジェクトは **Git リポジトリ** である必要があります。 /undo **キーバインド:** `ctrl+x u` * * * ### [共有の解除](https://opencode.ai/docs/ja/tui#%E5%85%B1%E6%9C%89%E3%81%AE%E8%A7%A3%E9%99%A4) 現在のセッションの共有を解除します。 [詳細はこちら](https://opencode.ai/docs/share#un-sharing) 。 /unshare * * * [エディタのセットアップ](https://opencode.ai/docs/ja/tui#%E3%82%A8%E3%83%87%E3%82%A3%E3%82%BF%E3%81%AE%E3%82%BB%E3%83%83%E3%83%88%E3%82%A2%E3%83%83%E3%83%97) --------------------------------------------------------------------------------------------------------------------------------------------------- `/editor` および `/export` コマンドはどちらも、`EDITOR` 環境変数で指定されたエディターを使用します。 * [Linux/macOS](https://opencode.ai/docs/ja/tui#tab-panel-60) * [Windows (CMD)](https://opencode.ai/docs/ja/tui#tab-panel-61) * [Windows (PowerShell)](https://opencode.ai/docs/ja/tui#tab-panel-62) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" これを永続的にするには、これをシェルプロファイルに追加します。 `~/.bashrc`、`~/.zshrc`など set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait これを永続的にするには、**システムプロパティ** > **環境変数**を使用します。 $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" これを永続的にするには、これを PowerShell プロファイルに追加します。 一般的なエディターオプションには次のものがあります。 * `code` - VS Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim エディター * `vim` - Vim エディター * `nano` - ナノエディター * `notepad` - Windows メモ帳 * `subl` - Sublime Text 一部のモードでは実行にコマンドライン引数が必要です。`--wait` フラグを使うと、エディターが閉じるまでプロセスが待機します。 * * * [設定](https://opencode.ai/docs/ja/tui#%E8%A8%AD%E5%AE%9A) --------------------------------------------------------- `tui.json` (または `tui.jsonc`) ファイルを通じて TUI の動作をカスタマイズできます。 { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} これは、サーバー/ランタイムの動作を構成する `opencode.json` とは別です。 ### [オプション](https://opencode.ai/docs/ja/tui#%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%B3) * `theme` - UI テーマを設定します。[詳細はこちら](https://opencode.ai/docs/themes) 。 * `keybinds` - キーボードショートカットをカスタマイズします。[詳細はこちら](https://opencode.ai/docs/keybinds) 。 * `scroll_acceleration.enabled` - macOS スタイルのスクロールアクセラレーションを有効にして、スムーズで自然なスクロールを実現します。有効にすると、高速スクロールジェスチャではスクロール速度が向上し、ゆっくりとした動きでは正確なままになります。 **この設定は `scroll_speed` よりも優先され、有効になっている場合は上書きされます。** * `scroll_speed` - スクロールコマンドを使用するときに TUI がスクロールする速度を制御します (最小: `0.001`、小数をサポート)。デフォルトは `3` です。 **注: `scroll_acceleration.enabled` が `true` に設定されている場合、これは無視されます。** * `diff_style` - 差分レンダリングを制御します。 `"auto"` はターミナルの幅に適応し、`"stacked"` は常に 1 列のレイアウトを表示します。 カスタム TUI 設定パスをロードするには、`OPENCODE_TUI_CONFIG` を使用します。 * * * [カスタマイズ](https://opencode.ai/docs/ja/tui#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%9E%E3%82%A4%E3%82%BA) ------------------------------------------------------------------------------------------------- コマンドパレット (`ctrl+x h` または `/help`) を使用して、TUI ビューのさまざまな側面をカスタマイズできます。これらの設定は再起動後も維持されます。 * * * #### [ユーザー名の表示](https://opencode.ai/docs/ja/tui#%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%BC%E5%90%8D%E3%81%AE%E8%A1%A8%E7%A4%BA) チャットメッセージにユーザー名を表示するかどうかを切り替えます。これには次の方法でアクセスします。 * コマンドパレット:「ユーザー名」または「ユーザー名を隠す」を検索します。 * 設定は自動的に保持され、TUI セッション全体で記憶されます。 --- # TUI | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/tui#_top) TUI === OpenCode 터미널 사용자 인터페이스 사용. OpenCode는 LLM과 함께 프로젝트 작업을 하기 위한 대화형 터미널 인터페이스(TUI)를 제공합니다. OpenCode를 실행하면 현재 디렉토리에서 TUI가 시작됩니다. opencode 또는 특정 작업 디렉토리에 대해 시작할 수 있습니다. opencode /path/to/project TUI에 들어가면 메시지를 입력하여 프롬프트할 수 있습니다. Give me a quick summary of the codebase. * * * [파일 참조](https://opencode.ai/docs/ko/tui#%ED%8C%8C%EC%9D%BC-%EC%B0%B8%EC%A1%B0) ------------------------------------------------------------------------------- `@`를 사용하여 메시지에서 파일을 참조할 수 있습니다. 이것은 현재 작업 디렉토리에서 퍼지(fuzzy) 파일 검색을 수행합니다. How is auth handled in @packages/functions/src/api/index.ts? 파일의 내용이 자동으로 대화에 추가됩니다. * * * [Bash 명령](https://opencode.ai/docs/ko/tui#bash-%EB%AA%85%EB%A0%B9) ------------------------------------------------------------------- `!`로 메시지를 시작하여 셸 명령을 실행합니다. !ls -la 명령의 출력은 도구 결과로 대화에 추가됩니다. * * * [명령](https://opencode.ai/docs/ko/tui#%EB%AA%85%EB%A0%B9) --------------------------------------------------------- OpenCode TUI를 사용할 때 `/` 뒤에 명령 이름을 입력하여 작업을 빠르게 실행할 수 있습니다. 예를 들어: /help 대부분의 명령에는 기본 리더 키인 `ctrl+x`를 사용하는 키바인드도 있습니다. [더 알아보기](https://opencode.ai/docs/keybinds) . 사용 가능한 모든 슬래시 명령은 다음과 같습니다: * * * ### [connect](https://opencode.ai/docs/ko/tui#connect) OpenCode에 공급자를 추가합니다. 사용 가능한 공급자 중에서 선택하고 API 키를 추가할 수 있습니다. /connect * * * ### [compact](https://opencode.ai/docs/ko/tui#compact) 현재 세션을 압축합니다. _별칭_: `/summarize` /compact **키바인드:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/ko/tui#details) 도구 실행 세부 정보 토글. /details **키바인드:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/ko/tui#editor) 메시지 작성을 위한 외부 편집기를 엽니다. `EDITOR` 환경 변수에 설정된 편집기를 사용합니다. [더 알아보기](https://opencode.ai/docs/ko/tui#editor-setup) . /editor **키바인드:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/ko/tui#exit) OpenCode를 종료합니다. _별칭_: `/quit`, `/q` /exit **키바인드:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/ko/tui#export) 현재 대화를 Markdown으로 내보내고 기본 편집기에서 엽니다. `EDITOR` 환경 변수에 설정된 편집기를 사용합니다. [더 알아보기](https://opencode.ai/docs/ko/tui#editor-setup) . /export **키바인드:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/ko/tui#help) 도움말 대화 상자를 표시합니다. /help **키바인드:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/ko/tui#init) `AGENTS.md` 파일을 생성하거나 업데이트합니다. [더 알아보기](https://opencode.ai/docs/rules) . /init **키바인드:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/ko/tui#models) 사용 가능한 모델 목록을 표시합니다. /models **키바인드:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/ko/tui#new) 새 세션을 시작합니다. _별칭_: `/clear` /new **키바인드:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/ko/tui#redo) 이전에 실행 취소한 메시지를 다시 실행합니다. `/undo`를 사용한 후에만 사용할 수 있습니다. 내부적으로 Git을 사용하여 파일 변경 사항을 관리합니다. 따라서 프로젝트가 **Git 저장소**여야 합니다. /redo **키바인드:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/ko/tui#sessions) 세션 목록을 표시하고 세션 간을 전환합니다. _별칭_: `/resume`, `/continue` /sessions **키바인드:** `ctrl+x l` * * * 현재 세션을 공유합니다. [더 알아보기](https://opencode.ai/docs/share) . /share **키바인드:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/ko/tui#themes) 사용 가능한 테마 목록을 표시합니다. /themes **키바인드:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/ko/tui#thinking) 대화에서 생각/추론 블록의 가시성을 토글합니다. 활성화하면 확장된 사고를 지원하는 모델의 추론 과정을 볼 수 있습니다. /thinking * * * ### [undo](https://opencode.ai/docs/ko/tui#undo) 대화의 마지막 메시지를 실행 취소합니다. 가장 최근의 사용자 메시지, 모든 후속 응답 및 모든 파일 변경 사항을 제거합니다. 내부적으로 Git을 사용하여 파일 변경 사항을 관리합니다. 따라서 프로젝트가 **Git 저장소**여야 합니다. /undo **키바인드:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/ko/tui#unshare) 현재 세션 공유를 취소합니다. [더 알아보기](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Editor setup](https://opencode.ai/docs/ko/tui#editor-setup) ------------------------------------------------------------- `/editor`와 `/export` 명령 모두 `EDITOR` 환경 변수에 지정된 편집기를 사용합니다. * [Linux/macOS](https://opencode.ai/docs/ko/tui#tab-panel-67) * [Windows (CMD)](https://opencode.ai/docs/ko/tui#tab-panel-68) * [Windows (PowerShell)](https://opencode.ai/docs/ko/tui#tab-panel-69) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" 영구적으로 설정하려면 셸 프로필(`~/.bashrc`, `~/.zshrc` 등)에 추가하십시오. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait 영구적으로 설정하려면 **시스템 속성** > **환경 변수**를 사용하십시오. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" 영구적으로 설정하려면 PowerShell 프로필에 추가하십시오. 인기 있는 편집기 옵션은 다음과 같습니다: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim editor * `vim` - Vim editor * `nano` - Nano editor * `notepad` - Windows Notepad * `subl` - Sublime Text 일부 편집기는 차단 모드에서 실행하려면 명령줄 인수가 필요합니다. `--wait` 플래그는 편집기 프로세스가 닫힐 때까지 차단되도록 합니다. * * * [구성](https://opencode.ai/docs/ko/tui#%EA%B5%AC%EC%84%B1) --------------------------------------------------------- `tui.json` (또는 `tui.jsonc`) 파일을 통해 TUI 동작을 사용자 정의할 수 있습니다. { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} 이는 서버/런타임 동작을 구성하는 `opencode.json`과는 별개입니다. ### [옵션](https://opencode.ai/docs/ko/tui#%EC%98%B5%EC%85%98) * `theme` - UI 테마를 설정합니다. [더 알아보기](https://opencode.ai/docs/themes) . * `keybinds` - 키보드 단축키를 사용자 정의합니다. [더 알아보기](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - 부드럽고 자연스러운 스크롤을 위해 macOS 스타일의 스크롤 가속을 활성화합니다. 활성화하면 빠른 스크롤 제스처로 스크롤 속도가 증가하고 느린 움직임에서는 정밀하게 유지됩니다. **이 설정은 `scroll_speed`보다 우선하며 활성화 시 이를 덮어씁니다.** * `scroll_speed` - 스크롤 명령을 사용할 때 TUI 스크롤 속도를 제어합니다 (최소: `0.001`, 소수점 값 지원). 기본값은 `3`입니다. **참고: `scroll_acceleration.enabled`가 `true`로 설정되면 무시됩니다.** * `diff_style` - diff 렌더링 방식을 제어합니다. `"auto"`는 터미널 너비에 적응하고, `"stacked"`는 항상 단일 열 레이아웃을 표시합니다. `OPENCODE_TUI_CONFIG`를 사용하여 사용자 정의 TUI 설정 경로를 로드할 수 있습니다. * * * [사용자 정의](https://opencode.ai/docs/ko/tui#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98) ----------------------------------------------------------------------------------------- 명령 팔레트(`ctrl+x h` 또는 `/help`)를 사용하여 TUI 보기의 다양한 측면을 사용자 정의할 수 있습니다. 설정은 다시 시작해도 유지됩니다. * * * #### [사용자 이름 표시](https://opencode.ai/docs/ko/tui#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%9D%B4%EB%A6%84-%ED%91%9C%EC%8B%9C) 채팅 메시지에 사용자 이름이 표시되는지 여부를 토글합니다. 다음을 통해 액세스: * 명령 팔레트: “username” 또는 “hide username” 검색 * 설정은 자동으로 유지되며 TUI 세션 간에 기억됩니다. --- # TUI | OpenCode [Gå til indhold](https://opencode.ai/docs/da/tui#_top) TUI === Brug af OpenCode-terminalbrugergrænsefladen. OpenCode giver en interaktiv terminalgrænseflade eller TUI til at arbejde med dine projekter med en LLM. At køre OpenCode starter TUI for den nuværende mappe. opencode Eller du kan starte den for en bestemt arbejdsmappe. opencode /path/to/project Når du er i TUI, kan du spørge den med en besked. Give me a quick summary of the codebase. * * * [Filreferencer](https://opencode.ai/docs/da/tui#filreferencer) --------------------------------------------------------------- Du kan referere til filer i dine beskeder med `@`. Det laver en fuzzy filsøgning i den nuværende arbejdsmappe. How is auth handled in @packages/functions/src/api/index.ts? Indholdet i filen tilføjes automatisk til samtalen. * * * [Bash-kommandoer](https://opencode.ai/docs/da/tui#bash-kommandoer) ------------------------------------------------------------------- Start en besked med `!` for at køre en shell-kommando. !ls -la Outputtet fra kommandoen tilføjes til samtalen som et værktøjsresultat. * * * [Kommandoer](https://opencode.ai/docs/da/tui#kommandoer) --------------------------------------------------------- Når du bruger OpenCode TUI, kan du skrive `/` efterfulgt af et kommandonavn for hurtigt at udføre handlinger. For eksempel: /help De fleste kommandoer har også genvejstaster som bruger `ctrl+x` som Leader-tast, hvor `ctrl+x` er standard Leader-tast. [Læs mere](https://opencode.ai/docs/keybinds) . Her er alle tilgængelige skråstregskommandoer: * * * ### [connect](https://opencode.ai/docs/da/tui#connect) Tilføj en udbyder til OpenCode. Lader dig vælge fra tilgængelige udbydere og tilføje deres API-nøgler. /connect * * * ### [compact](https://opencode.ai/docs/da/tui#compact) Komprimer nuværende session. _Alias_: `/summarize` /compact **Genvejstast:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/da/tui#details) Skift visning af værktøjsudførelsesdetaljer. /details **Genvejstast:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/da/tui#editor) Åbn eksternt redigeringsprogram for at skrive beskeder. Bruger redigeringsprogrammet i miljøvariablen `EDITOR`. [Læs mere](https://opencode.ai/docs/da/tui#editor-setup) . /editor **Genvejstast:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/da/tui#exit) Afslut OpenCode. _Aliaser_: `/quit`, `/q` /exit **Genvejstast:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/da/tui#export) Eksporter nuværende samtale til Markdown og åbn i standardredigeringsprogrammet. Bruger redigeringsprogrammet i miljøvariablen `EDITOR`. [Læs mere](https://opencode.ai/docs/da/tui#editor-setup) . /export **Genvejstast:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/da/tui#help) Vis hjælpedialogen. /help **Genvejstast:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/da/tui#init) Opret eller opdater `AGENTS.md`\-fil. [Læs mere](https://opencode.ai/docs/rules) . /init **Genvejstast:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/da/tui#models) Liste over tilgængelige modeller. /models **Genvejstast:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/da/tui#new) Start en ny session. _Alias_: `/clear` /new **Genvejstast:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/da/tui#redo) Gentag en tidligere fortrudt besked. Kun tilgængelig efter brug af `/undo`. Internt bruger dette Git til at administrere filændringerne. Så dit projekt **skal være et Git-depot**. /redo **Genvejstast:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/da/tui#sessions) List og skift mellem sessioner. _Aliaser_: `/resume`, `/continue` /sessions **Genvejstast:** `ctrl+x l` * * * Del nuværende session. [Læs mere](https://opencode.ai/docs/share) . /share **Genvejstast:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/da/tui#themes) Liste over tilgængelige temaer. /theme **Genvejstast:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/da/tui#thinking) Skift synligheden af tænke-/ræsonneringsblokke i samtalen. Når den er aktiveret, kan du se modellens ræsonneringsproces for modeller, som understøtter udvidet tænkning. /thinking * * * ### [undo](https://opencode.ai/docs/da/tui#undo) Fortryd sidste besked i samtalen. Fjerner den sidste brugerbesked, alle efterfølgende svar og eventuelle filændringer. Internt bruger dette Git til at administrere filændringerne. Så dit projekt **skal være et Git-depot**. /undo **Genvejstast:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/da/tui#unshare) Ophæv deling af nuværende session. [Læs mere](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Opsætning af editor](https://opencode.ai/docs/da/tui#ops%C3%A6tning-af-editor) -------------------------------------------------------------------------------- Både kommandoerne `/editor` og `/export` bruger editoren som er specificeret i miljøvariablen `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/da/tui#tab-panel-25) * [Windows (CMD)](https://opencode.ai/docs/da/tui#tab-panel-26) * [Windows (PowerShell)](https://opencode.ai/docs/da/tui#tab-panel-27) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" For at gøre det permanent, tilføj dette til din shellprofil; `~/.bashrc`, `~/.zshrc` osv. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait For at gøre det permanent, brug **Systemegenskaber** > **Miljøvariabler**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" For at gøre det permanent, tilføj dette til din PowerShell-profil. Populære redigeringsalternativer inkluderer: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim-editor * `vim` - Vim editor * `nano` - Nano-editor * `notepad` - Windows Notesblok * `subl` - Sublime Text Nogle editorer kræver kommandolinjeargumenter for at køre i blokeringstilstand. `--wait`\-flaget gør at redigeringsprocessen blokeres indtil den lukkes. * * * [Konfigurer](https://opencode.ai/docs/da/tui#konfigurer) --------------------------------------------------------- Du kan tilpasse TUI-adfærd gennem `tui.json` (eller `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Dette er adskilt fra `opencode.json`, som konfigurerer server-/kørselstidsadfærd. ### [Indstillinger](https://opencode.ai/docs/da/tui#indstillinger) * `theme` - Indstiller dit brugergrænsefladetema. [Læs mere](https://opencode.ai/docs/themes) . * `keybinds` - Tilpasser tastaturgenveje. [Læs mere](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Aktiver rulleacceleration i macOS-stil for jævn, naturlig rulning. Når aktiveret, øger rullehastigheden med hurtige rullebevægelser og forbliver præcis for langsommere bevægelser. **Denne indstilling har forrang over `scroll_speed` og tilsidesætter den, når den er aktiveret.** * `scroll_speed` - Styrer hvor hurtigt TUI ruller, når du bruger rullekommandoer (minimum: `0.001`, understøtter decimalværdier). Standard er `3`. **Bemærk: Dette ignoreres hvis `scroll_acceleration.enabled` er sat til `true`.** * `diff_style` - Styrer diff-gengivelse. `"auto"` tilpasser sig terminalbredde, `"stacked"` viser altid et enkeltkolonne-layout. Brug `OPENCODE_TUI_CONFIG` til at indlæse en brugerdefineret TUI-konfigurationssti. * * * [Tilpasning](https://opencode.ai/docs/da/tui#tilpasning) --------------------------------------------------------- Du kan tilpasse forskellige aspekter af TUI-visningen ved at bruge kommandopaletten (`ctrl+x h` eller `/help`). Disse indstillinger gemmes ved genstart. * * * #### [Visning af brugernavn](https://opencode.ai/docs/da/tui#visning-af-brugernavn) Skift om dit brugernavn vises i chat-beskeder. Få adgang til dette gennem: * Kommandopalet: Søg efter “brugernavn” eller “skjul brugernavn” * Indstillingen gemmes automatisk og vil blive husket over TUI-sessioner --- # TUI | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/tui#_top) TUI === Utilisation de l’interface utilisateur du terminal OpenCode. OpenCode fournit une interface de terminal interactif ou TUI pour travailler sur vos projets avec un LLM. L’exécution de OpenCode démarre le TUI pour le répertoire actuel. opencode Ou vous pouvez le démarrer pour un répertoire de travail spécifique. opencode /path/to/project Une fois que vous êtes dans le TUI, vous pouvez lui envoyer un message. Give me a quick summary of the codebase. * * * [Références de fichiers](https://opencode.ai/docs/fr/tui#r%C3%A9f%C3%A9rences-de-fichiers) ------------------------------------------------------------------------------------------- Vous pouvez référencer des fichiers dans vos messages en utilisant `@`. Cela effectue une recherche de fichier floue dans le répertoire de travail actuel. How is auth handled in @packages/functions/src/api/index.ts? Le contenu du fichier est automatiquement ajouté à la conversation. * * * [Commandes Bash](https://opencode.ai/docs/fr/tui#commandes-bash) ----------------------------------------------------------------- Démarrez un message avec `!` pour exécuter une commande shell. !ls -la Le résultat de la commande est ajouté à la conversation en tant que résultat de l’outil. * * * [Commandes](https://opencode.ai/docs/fr/tui#commandes) ------------------------------------------------------- Lorsque vous utilisez le OpenCode TUI, vous pouvez taper `/` suivi d’un nom de commande pour exécuter rapidement des actions. Par exemple: /help La plupart des commandes ont également une liaison clavier utilisant `ctrl+x` comme touche leader, où `ctrl+x` est la touche leader par défaut. [En savoir plus](https://opencode.ai/docs/keybinds) . Voici toutes les commandes slash disponibles : * * * ### [connect](https://opencode.ai/docs/fr/tui#connect) Ajoutez un fournisseur à OpenCode. Vous permet de sélectionner parmi les fournisseurs disponibles et d’ajouter leurs clés API. /connect * * * ### [compact](https://opencode.ai/docs/fr/tui#compact) Compactez la session en cours. _Alias_ : `/summarize` /compact **Reliure de touches :** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/fr/tui#details) Basculer les détails d’exécution de l’outil. /details **Reliure de touches :** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/fr/tui#editor) Ouvrez un éditeur externe pour rédiger des messages. Utilise l’éditeur défini dans votre variable d’environnement `EDITOR`. [En savoir plus](https://opencode.ai/docs/fr/tui#editor-setup) . /editor **Reliure de touches :** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/fr/tui#exit) Quittez OpenCode. _Alias_ : `/quit`, `/q` /exit **Reliure de touches :** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/fr/tui#export) Exportez la conversation en cours vers Markdown et ouvrez-la dans votre éditeur par défaut. Utilise l’éditeur défini dans votre variable d’environnement `EDITOR`. [En savoir plus](https://opencode.ai/docs/fr/tui#editor-setup) . /export **Reliure de touches :** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/fr/tui#help) Afficher la boîte de dialogue d’aide. /help **Reliure de touches :** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/fr/tui#init) Créez ou mettez à jour le fichier `AGENTS.md`. [En savoir plus](https://opencode.ai/docs/rules) . /init **Reliure de touches :** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/fr/tui#models) Liste des modèles disponibles. /models **Reliure de touches :** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/fr/tui#new) Démarrez une nouvelle session. _Alias_ : `/clear` /new **Reliure de touches :** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/fr/tui#redo) Refaire un message précédemment annulé. Disponible uniquement après avoir utilisé `/undo`. En interne, cela utilise Git pour gérer les modifications de fichiers. Votre projet **doit donc être un dépôt Git**. /redo **Reliure de touches :** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/fr/tui#sessions) Répertoriez et basculez entre les sessions. _Alias_ : `/resume`, `/continue` /sessions **Reliure de touches :** `ctrl+x l` * * * Partager la session en cours. [En savoir plus](https://opencode.ai/docs/share) . /share **Reliure de touches :** `ctrl+x s` * * * ### [theme](https://opencode.ai/docs/fr/tui#theme) Répertoriez les thèmes disponibles. /theme **Reliure de touches :** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/fr/tui#thinking) Activez/désactivez la visibilité des blocages de réflexion/raisonnement dans la conversation. Lorsque cette option est activée, vous pouvez voir le processus de raisonnement du modèle pour les modèles prenant en charge la réflexion étendue. /thinking * * * ### [undo](https://opencode.ai/docs/fr/tui#undo) Annuler le dernier message de la conversation. Supprime le message utilisateur le plus récent, toutes les réponses ultérieures et toutes les modifications de fichier. En interne, cela utilise Git pour gérer les modifications de fichiers. Votre projet **doit donc être un dépôt Git**. /undo **Reliure de touches :** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/fr/tui#unshare) Annuler le partage de la session en cours. [En savoir plus](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Configuration de l’éditeur](https://opencode.ai/docs/fr/tui#configuration-de-l%C3%A9diteur) --------------------------------------------------------------------------------------------- Les commandes `/editor` et `/export` utilisent l’éditeur spécifié dans votre variable d’environnement `EDITOR`. * [Linux/macOS](https://opencode.ai/docs/fr/tui#tab-panel-46) * [Windows (CMD)](https://opencode.ai/docs/fr/tui#tab-panel-47) * [Windows (PowerShell)](https://opencode.ai/docs/fr/tui#tab-panel-48) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" Pour le rendre permanent, ajoutez-le à votre profil shell ; `~/.bashrc`, `~/.zshrc`, etc. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait Pour le rendre permanent, utilisez **Propriétés système** > **Environnement Variables**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" Pour le rendre permanent, ajoutez-le à votre profil PowerShell. Les options d’éditeur populaires incluent : * `code`\-Code Visual Studio * `cursor` - Curseur * `windsurf` - Planche à voile * `nvim` - Editeur Neovim * `vim` - Éditeur Vim * `nano` - Éditeur nano * `notepad` - Windows Bloc-notes * `subl` - Texte sublime Certains éditeurs ont besoin d’arguments de ligne de commande pour s’exécuter en mode blocage. L’indicateur `--wait` bloque le processus de l’éditeur jusqu’à sa fermeture. * * * [Configurer](https://opencode.ai/docs/fr/tui#configurer) --------------------------------------------------------- Vous pouvez personnaliser le comportement de TUI via `tui.json` (ou `tui.jsonc`). { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Ceci est séparé de `opencode.json`, qui configure le comportement du serveur/d’exécution. ### [Options](https://opencode.ai/docs/fr/tui#options) * `theme` - Définit votre thème d’interface utilisateur. [En savoir plus](https://opencode.ai/docs/themes) . * `keybinds` - Personnalise les raccourcis clavier. [En savoir plus](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Activez l’accélération de défilement de style macOS pour un défilement fluide et naturel. Lorsqu’elle est activée, la vitesse de défilement augmente avec les gestes de défilement rapides et reste précise pour les mouvements plus lents. **Ce paramètre est prioritaire sur `scroll_speed` et le remplace lorsqu’il est activé.** * `scroll_speed` - Contrôle la vitesse de défilement du TUI lors de l’utilisation des commandes de défilement (minimum : `0.001`, prend en charge les valeurs décimales). La valeur par défaut est `3`. **Remarque : Ceci est ignoré si `scroll_acceleration.enabled` est défini sur `true`.** * `diff_style` - Contrôle le rendu différentiel. `"auto"` s’adapte à la largeur du terminal, `"stacked"` affiche toujours une seule colonne. Utilisez `OPENCODE_TUI_CONFIG` pour charger un chemin de configuration TUI personnalisé. * * * [Personnalisation](https://opencode.ai/docs/fr/tui#personnalisation) --------------------------------------------------------------------- Vous pouvez personnaliser divers aspects de la vue TUI à l’aide de la palette de commandes (`ctrl+x h` ou `/help`). Ces paramètres persistent lors des redémarrages. * * * #### [Affichage du nom d’utilisateur](https://opencode.ai/docs/fr/tui#affichage-du-nom-dutilisateur) Indiquez si votre nom d’utilisateur apparaît dans les messages de discussion. Accédez-y via : * Palette de commandes : recherchez “nom d’utilisateur” ou “masquer le nom d’utilisateur” * Le paramètre persiste automatiquement et sera mémorisé au cours de TUI sessions. --- # TUI | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/tui#_top) TUI === OpenCode terminal kullanıcı arayüzünü kullanma. OpenCode, projelerinizde LLM ile çalışmak için etkileşimli bir terminal arayüzü (TUI) sunar. OpenCode’u çalıştırdığınızda mevcut dizin için TUI başlar. opencode İsterseniz belirli bir çalışma dizini için de başlatabilirsiniz. opencode /path/to/project TUI içine girdiğinizde, bir mesajla istem gönderebilirsiniz. Give me a quick summary of the codebase. * * * [Dosya referansları](https://opencode.ai/docs/tr/tui#dosya-referanslar%C4%B1) ------------------------------------------------------------------------------ Mesajlarınızda `@` kullanarak dosyalara referans verebilirsiniz. Bu, mevcut çalışma dizininde bulanık dosya araması yapar. How is auth handled in @packages/functions/src/api/index.ts? Dosya içeriği otomatik olarak konuşmaya eklenir. * * * [Bash komutları](https://opencode.ai/docs/tr/tui#bash-komutlar%C4%B1) ---------------------------------------------------------------------- Bir mesajı `!` ile başlatarak shell komutu çalıştırın. !ls -la Komut çıktısı bir araç sonucu olarak konuşmaya eklenir. * * * [Komutlar](https://opencode.ai/docs/tr/tui#komutlar) ----------------------------------------------------- OpenCode TUI kullanırken `/` ve ardından komut adını yazarak hızlı eylemler çalıştırabilirsiniz. Örneğin: /help Komutların çoğu, lider tuşu `ctrl+x` olan bir kısayola da sahiptir. [Daha fazla bilgi](https://opencode.ai/docs/keybinds) . İşte mevcut slash komutlarının tümü: * * * ### [connect](https://opencode.ai/docs/tr/tui#connect) OpenCode’a bir sağlayıcı ekler. Mevcut sağlayıcıları seçip API anahtarları eklemenizi sağlar. /connect * * * ### [compact](https://opencode.ai/docs/tr/tui#compact) Mevcut oturumu sıkıştırır. _Takma ad_: `/summarize` /compact **Kısayol:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/tr/tui#details) Araç çalıştırma detaylarını göster/gizle yapar. /details **Kısayol:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/tr/tui#editor) Mesaj yazmak için harici editör açar. `EDITOR` ortam değişkeninde ayarlı editörü kullanır. [Daha fazla bilgi](https://opencode.ai/docs/tr/tui#editor-setup) . /editor **Kısayol:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/tr/tui#exit) OpenCode’dan çıkar. _Takma adlar_: `/quit`, `/q` /exit **Kısayol:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/tr/tui#export) Mevcut konuşmayı Markdown olarak dışa aktarır ve varsayılan editörünüzde açar. `EDITOR` ortam değişkeninde ayarlı editörü kullanır. [Daha fazla bilgi](https://opencode.ai/docs/tr/tui#editor-setup) . /export **Kısayol:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/tr/tui#help) Yardım penceresini gösterir. /help **Kısayol:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/tr/tui#init) `AGENTS.md` dosyasını oluşturur veya günceller. [Daha fazla bilgi](https://opencode.ai/docs/rules) . /init **Kısayol:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/tr/tui#models) Kullanılabilir modelleri listeler. /models **Kısayol:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/tr/tui#new) Yeni bir oturum başlatır. _Takma ad_: `/clear` /new **Kısayol:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/tr/tui#redo) Geri alınan bir mesajı tekrar uygular. Yalnızca `/undo` kullanıldıktan sonra kullanılabilir. Dahili olarak bu işlem dosya değişikliklerini yönetmek için Git kullanır. Bu nedenle projenizin **bir Git deposu olması gerekir**. /redo **Kısayol:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/tr/tui#sessions) Oturumları listeler ve aralarında geçiş yapar. _Takma adlar_: `/resume`, `/continue` /sessions **Kısayol:** `ctrl+x l` * * * Mevcut oturumu paylaşır. [Daha fazla bilgi](https://opencode.ai/docs/share) . /share **Kısayol:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/tr/tui#themes) Kullanılabilir temaları listeler. /themes **Kısayol:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/tr/tui#thinking) Konuşmadaki thinking/reasoning bloklarının görünürlüğünü değiştirir. Etkin olduğunda, genişletilmiş düşünmeyi destekleyen modellerin akıl yürütme sürecini görebilirsiniz. /thinking * * * ### [undo](https://opencode.ai/docs/tr/tui#undo) Konuşmadaki son mesajı geri alır. En son kullanıcı mesajını, sonraki tüm yanıtları ve dosya değişikliklerini kaldırır. Dahili olarak bu işlem dosya değişikliklerini yönetmek için Git kullanır. Bu nedenle projenizin **bir Git deposu olması gerekir**. /undo **Kısayol:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/tr/tui#unshare) Mevcut oturumun paylaşımını kaldırır. [Daha fazla bilgi](https://opencode.ai/docs/share#un-sharing) . /unshare * * * [Editör kurulumu](https://opencode.ai/docs/tr/tui#edit%C3%B6r-kurulumu) ------------------------------------------------------------------------ Hem `/editor` hem de `/export` komutları, `EDITOR` ortam değişkeninde belirtilen editörü kullanır. * [Linux/macOS](https://opencode.ai/docs/tr/tui#tab-panel-109) * [Windows (CMD)](https://opencode.ai/docs/tr/tui#tab-panel-110) * [Windows (PowerShell)](https://opencode.ai/docs/tr/tui#tab-panel-111) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" Kalıcı yapmak için bunu kabuk profilinize ekleyin; `~/.bashrc`, `~/.zshrc` vb. set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait Kalıcı yapmak için **System Properties** > **Environment Variables** yolunu kullanın. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" Kalıcı yapmak için bunu PowerShell profilinize ekleyin. Popüler editör seçenekleri şunları içerir: * `code` - Visual Studio Code * `cursor` - Cursor * `windsurf` - Windsurf * `nvim` - Neovim editörü * `vim` - Vim editörü * `nano` - Nano editörü * `notepad` - Windows Notepad * `subl` - Sublime Text Bazı editörler bloklama modunda çalışmak için komut satırı argümanlarına ihtiyaç duyar. `--wait` bayrağı, editör süreci kapanana kadar işlemin bloklanmasını sağlar. * * * [Yapılandırma](https://opencode.ai/docs/tr/tui#yap%C4%B1land%C4%B1rma) ----------------------------------------------------------------------- TUI davranışını `tui.json` (veya `tui.jsonc`) aracılığıyla özelleştirebilirsiniz. { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} Bu, sunucu/çalışma zamanı davranışını yapılandıran `opencode.json` dosyasından ayrıdır. ### [Seçenekler](https://opencode.ai/docs/tr/tui#se%C3%A7enekler) * `theme` - UI temanızı ayarlar. [Daha fazla bilgi](https://opencode.ai/docs/themes) . * `keybinds` - Klavye kısayollarını özelleştirir. [Daha fazla bilgi](https://opencode.ai/docs/keybinds) . * `scroll_acceleration.enabled` - Pürüzsüz, doğal kaydırma için macOS tarzı kaydırma ivmesini etkinleştirin. Etkinleştirildiğinde, kaydırma hızı hızlı kaydırma hareketleriyle artar ve daha yavaş hareketler için hassas kalır. **Bu ayar `scroll_speed` ayarından önceliklidir ve etkinleştirildiğinde onu geçersiz kılar.** * `scroll_speed` - Kaydırma komutlarını kullanırken TUI’nin ne kadar hızlı kaydırılacağını kontrol eder (minimum: `0.001`, ondalık değerleri destekler). Varsayılan değer `3`’tür. **Not: `scroll_acceleration.enabled` `true` olarak ayarlanmışsa bu yok sayılır.** * `diff_style` - Fark (diff) oluşturmayı kontrol eder. `"auto"` terminal genişliğine uyum sağlar, `"stacked"` her zaman tek sütunlu bir düzen gösterir. Özel bir TUI yapılandırma yolu yüklemek için `OPENCODE_TUI_CONFIG` kullanın. * * * [Özelleştirme](https://opencode.ai/docs/tr/tui#%C3%B6zelle%C5%9Ftirme) ----------------------------------------------------------------------- Komut paletini (`ctrl+x h` veya `/help`) kullanarak TUI görünümünün çeşitli yönlerini özelleştirebilirsiniz. Bu ayarlar yeniden başlatmalar arasında korunur. * * * #### [Kullanıcı adı görünümü](https://opencode.ai/docs/tr/tui#kullan%C4%B1c%C4%B1-ad%C4%B1-g%C3%B6r%C3%BCn%C3%BCm%C3%BC) Sohbet mesajlarında kullanıcı adınızın görünüp görünmeyeceğini değiştirin. Buna şuradan erişin: * Komut paleti: “username” veya “hide username” araması yapın * Ayar otomatik olarak kalıcı hale gelir ve TUI oturumları arasında hatırlanır --- # Web | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/web#_top) Web === En utilisant OpenCode dans votre navigateur. OpenCode peut s’exécuter comme une application Web dans votre navigateur, offrant la même expérience puissante de codage d’IA sans avoir besoin d’un terminal. ![OpenCode Web - Nouvelle session](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Commencer](https://opencode.ai/docs/fr/web#commencer) ------------------------------------------------------- Démarrez l’interface Web en exécutant : opencode web Cela démarre un serveur local sur `127.0.0.1` avec un port disponible aléatoire et ouvre automatiquement OpenCode dans votre navigateur par défaut. * * * [Configuration](https://opencode.ai/docs/fr/web#configuration) --------------------------------------------------------------- Vous pouvez configurer le serveur Web à l’aide d’indicateurs de ligne de commande ou dans votre [fichier de configuration](https://opencode.ai/docs/config) . ### [Port](https://opencode.ai/docs/fr/web#port) Par défaut, OpenCode sélectionne un port disponible. Vous pouvez spécifier un port : opencode web --port 4096 ### [Nom d’hôte](https://opencode.ai/docs/fr/web#nom-dh%C3%B4te) Par défaut, le serveur se lie à `127.0.0.1` (localhost uniquement). Pour rendre OpenCode accessible sur votre réseau : opencode web --hostname 0.0.0.0 Lorsque vous utilisez `0.0.0.0`, OpenCode affichera les adresses locales et réseau : Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [Découverte mDNS](https://opencode.ai/docs/fr/web#d%C3%A9couverte-mdns) Activez mDNS pour rendre votre serveur visible sur le réseau local : opencode web --mdns Cela définit automatiquement le nom d’hôte sur `0.0.0.0` et annonce le serveur comme `opencode.local`. Vous pouvez personnaliser le nom de domaine mDNS pour exécuter plusieurs instances sur le même réseau : opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/fr/web#cors) Pour autoriser des domaines supplémentaires pour CORS (utile pour les frontends personnalisés) : opencode web --cors https://example.com ### [Authentification](https://opencode.ai/docs/fr/web#authentification) Pour protéger l’accès, définissez un mot de passe à l’aide de la variable d’environnement `OPENCODE_SERVER_PASSWORD` : OPENCODE_SERVER_PASSWORD=secret opencode web Le nom d’utilisateur par défaut est `opencode` mais peut être modifié avec `OPENCODE_SERVER_USERNAME`. * * * [Utilisation de l’interface Web](https://opencode.ai/docs/fr/web#utilisation-de-linterface-web) ------------------------------------------------------------------------------------------------ Une fois démarrée, l’interface web permet d’accéder à vos sessions OpenCode. ### [Sessions](https://opencode.ai/docs/fr/web#sessions) Consultez et gérez vos sessions depuis la page d’accueil. Vous pouvez voir les sessions actives et en démarrer de nouvelles. ![OpenCode Web - Session active](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Statut du serveur](https://opencode.ai/docs/fr/web#statut-du-serveur) Cliquez sur “Voir les serveurs” pour afficher les serveurs connectés et leur état. ![OpenCode Web - Voir Serveurs](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Attacher un terminal](https://opencode.ai/docs/fr/web#attacher-un-terminal) ----------------------------------------------------------------------------- Vous pouvez connecter un terminal TUI à un serveur Web en cours d’exécution : # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Cela vous permet d’utiliser simultanément l’interface Web et le terminal, en partageant les mêmes sessions et le même état. * * * [Fichier de configuration](https://opencode.ai/docs/fr/web#fichier-de-configuration) ------------------------------------------------------------------------------------- Vous pouvez également configurer les paramètres du serveur dans votre fichier de configuration `opencode.json` : { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Les indicateurs de ligne de commande ont priorité sur les paramètres du fichier de configuration. --- # Plugins | OpenCode [Gå til indhold](https://opencode.ai/docs/da/plugins#_top) Plugins ======= Skriv dine egne plugins for at udvide OpenCode. Plugins giver dig mulighed for at udvide OpenCode ved at tilslutte sig forskellige begivenheder og tilpasse adfærd. Du kan oprette plugins for at tilføje nye funktioner, integrere med eksterne tjenester eller ændre OpenCodes standardadfærd. For eksempler, tjek [plugins](https://opencode.ai/docs/ecosystem#plugins) oprettet af fællesskabet. * * * [Brug af plugin](https://opencode.ai/docs/da/plugins#brug-af-plugin) --------------------------------------------------------------------- Der er to måder at indlæse plugins på. * * * ### [Fra lokale filer](https://opencode.ai/docs/da/plugins#fra-lokale-filer) Placer JavaScript- eller TypeScript-filer i plugin-mappen. * `.opencode/plugins/` - Plugins på projektniveau * `~/.config/opencode/plugins/` - Globale plugins Filer i disse mapper indlæses automatisk ved opstart. * * * ### [Fra npm](https://opencode.ai/docs/da/plugins#fra-npm) Angiv npm-pakker i din konfigurationsfil. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Både almindelige og omfangsrige npm-pakker understøttes. Gennemse tilgængelige plugins i [ecosystem](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Installation af plugins](https://opencode.ai/docs/da/plugins#installation-af-plugins) **npm plugins** installeres automatisk ved hjælp af Bun ved opstart. Pakker og deres afhængigheder cachelagres i `~/.cache/opencode/node_modules/`. **Lokale plugins** indlæses direkte fra plugin-biblioteket. For at bruge eksterne pakker skal du oprette en `package.json` i din konfigurationsmappe (se [Dependencies](https://opencode.ai/docs/da/plugins#dependencies) ), eller udgive pluginnet til npm og [add it to your config](https://opencode.ai/docs/config#plugins) . * * * ### [Indlæsningsrækkefølge](https://opencode.ai/docs/da/plugins#indl%C3%A6sningsr%C3%A6kkef%C3%B8lge) Plugins indlæses fra alle kilder, og alle hooks kører i rækkefølge. Indlæsningsrækkefølgen er: 1. Global konfiguration (`~/.config/opencode/opencode.json`) 2. Projektkonfiguration (`opencode.json`) 3. Global plugin-mappe (`~/.config/opencode/plugins/`) 4. Projekt plugin bibliotek (`.opencode/plugins/`) Dublerede npm-pakker med samme navn og version indlæses én gang. Et lokalt plugin og et npm plugin med lignende navne indlæses dog hver for sig. * * * [Oprettelse af plugin](https://opencode.ai/docs/da/plugins#oprettelse-af-plugin) --------------------------------------------------------------------------------- Et plugin er et **JavaScript/TypeScript modul**, der eksporterer et eller flere plugin funktioner. Hver funktion modtager et kontekstobjekt og returnerer et hooks-objekt. * * * ### [Afhængigheder](https://opencode.ai/docs/da/plugins#afh%C3%A6ngigheder) Lokale plugins og brugerdefinerede værktøjer kan bruge eksterne npm-pakker. Tilføj en `package.json` til din konfigurationsmappe med de afhængigheder, du har brug for. { "dependencies": { "shescape": "^2.1.0" }} OpenCode kører `bun install` ved opstart for at installere disse. Dine plugins og værktøjer kan derefter importere dem. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Grundlæggende struktur](https://opencode.ai/docs/da/plugins#grundl%C3%A6ggende-struktur) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} Plugin-funktionen modtager: * `project`: Den aktuelle projektinformation. * `directory`: Den aktuelle arbejdsmappe. * `worktree`: Git worktree-stien. * `client`: En opencode SDK klient til interaktion med AI. * `$`: Buns [shell API](https://bun.com/docs/runtime/shell) til udførelse af kommandoer. * * * ### [TypeScript-understøttelse](https://opencode.ai/docs/da/plugins#typescript-underst%C3%B8ttelse) For TypeScript-plugins kan du importere typer fra plugin-pakken: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Begivenheder](https://opencode.ai/docs/da/plugins#begivenheder) Plugins kan abonnere på begivenheder som vist nedenfor i afsnittet Eksempler. Her er en liste over de forskellige arrangementer. #### [Kommandohændelser](https://opencode.ai/docs/da/plugins#kommandoh%C3%A6ndelser) * `command.executed` #### [Filhændelser](https://opencode.ai/docs/da/plugins#filh%C3%A6ndelser) * `file.edited` * `file.watcher.updated` #### [Installationshændelser](https://opencode.ai/docs/da/plugins#installationsh%C3%A6ndelser) * `installation.updated` #### [LSP-hændelser](https://opencode.ai/docs/da/plugins#lsp-h%C3%A6ndelser) * `lsp.client.diagnostics` * `lsp.updated` #### [Beskedhændelser](https://opencode.ai/docs/da/plugins#beskedh%C3%A6ndelser) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Tilladelseshændelser](https://opencode.ai/docs/da/plugins#tilladelsesh%C3%A6ndelser) * `permission.asked` * `permission.replied` #### [Serverhændelser](https://opencode.ai/docs/da/plugins#serverh%C3%A6ndelser) * `server.connected` #### [Sessionshændelser](https://opencode.ai/docs/da/plugins#sessionsh%C3%A6ndelser) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Todo-hændelser](https://opencode.ai/docs/da/plugins#todo-h%C3%A6ndelser) * `todo.updated` #### [Shell-hændelser](https://opencode.ai/docs/da/plugins#shell-h%C3%A6ndelser) * `shell.env` #### [Værktøjshændelser](https://opencode.ai/docs/da/plugins#v%C3%A6rkt%C3%B8jsh%C3%A6ndelser) * `tool.execute.after` * `tool.execute.before` #### [TUI-hændelser](https://opencode.ai/docs/da/plugins#tui-h%C3%A6ndelser) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Eksempler](https://opencode.ai/docs/da/plugins#eksempler) ----------------------------------------------------------- Her er nogle eksempler på plugins, du kan bruge til at udvide opencode. * * * ### [Send meddelelser](https://opencode.ai/docs/da/plugins#send-meddelelser) Send meddelelser, når visse hændelser indtræffer: 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"'` } }, }} Vi bruger `osascript` til at køre AppleScript på macOS. Her bruger vi det til at sende notifikationer. * * * ### [.env-beskyttelse](https://opencode.ai/docs/da/plugins#env-beskyttelse) Undgå opencode i at læse `.env` filer: 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") } }, }} * * * ### [Injicer miljøvariabler](https://opencode.ai/docs/da/plugins#injicer-milj%C3%B8variabler) Injicer miljøvariabler i al shell-udførelse (AI-værktøjer og brugerterminaler): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Brugerdefinerede værktøjer](https://opencode.ai/docs/da/plugins#brugerdefinerede-v%C3%A6rkt%C3%B8jer) Plugins kan også tilføje brugerdefinerede værktøjer til opencode: 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})` }, }), }, }} `tool`\-hjælperen opretter et brugerdefineret værktøj, som opencode kan kalde. Det tager en Zod-skemafunktion og returnerer en værktøjsdefinition med: * `description`: Hvad værktøjet gør * `args`: Zod-skema for værktøjets argumenter * `execute`: Funktion, der kører, når værktøjet kaldes Dine tilpassede værktøjer vil være tilgængelige for opencode sammen med indbyggede værktøjer. * * * ### [Logning](https://opencode.ai/docs/da/plugins#logning) Brug `client.app.log()` i stedet for `console.log` til struktureret logning: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Niveauer: `debug`, `info`, `warn`, `error`. Se [SDK documentation](https://opencode.ai/docs/sdk) for detaljer. * * * ### [Komprimerings-hooks](https://opencode.ai/docs/da/plugins#komprimerings-hooks) Tilpas konteksten inkluderet, når en session komprimeres: 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`) }, }} `experimental.session.compacting` krogen affyres, før LLM genererer en fortsættelsesoversigt. Brug den til at injicere domænespecifik kontekst, som standardkomprimeringsprompten ville gå glip af. Du kan også erstatte komprimeringsprompten helt ved at indstille `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Når `output.prompt` er indstillet, erstatter den standardkompressionsprompten fuldstændigt. `output.context`\-arrayet ignoreres i dette tilfælde. --- # Programtillegg | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/plugins#_top) Programtillegg ============== Skriv dine egne programtillegg for å utvide OpenCode. Plugins lar deg utvide OpenCode ved å koble til ulike hendelser og tilpasse atferd. Du kan lage plugins for å legge til nye funksjoner, integrere med eksterne tjenester eller endre standardoppførselen til OpenCode. For eksempler, sjekk ut [plugins](https://opencode.ai/docs/ecosystem#plugins) opprettet av fellesskapet. * * * [Bruk av en plugin](https://opencode.ai/docs/nb/plugins#bruk-av-en-plugin) --------------------------------------------------------------------------- Det er to måter å laste inn plugins. * * * ### [Fra lokale filer](https://opencode.ai/docs/nb/plugins#fra-lokale-filer) Plasser JavaScript- eller TypeScript-filer i plugin-katalogen. * `.opencode/plugins/` - Programtillegg på prosjektnivå * `~/.config/opencode/plugins/` - Globale plugins Filer i disse katalogene lastes automatisk ved oppstart. * * * ### [Fra npm](https://opencode.ai/docs/nb/plugins#fra-npm) Spesifiser npm-pakker i konfigurasjonsfilen. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Både vanlige og scoped npm-pakker støttes. Bla gjennom tilgjengelige plugins i [økosystemet](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Hvordan plugins installeres](https://opencode.ai/docs/nb/plugins#hvordan-plugins-installeres) **npm-plugins** installeres automatisk ved hjelp av Bun ved oppstart. Pakker og deres avhengigheter er bufret i `~/.cache/opencode/node_modules/`. **Lokale plugins** lastes direkte fra plugin-katalogen. For å bruke eksterne pakker, må du opprette en `package.json` i konfigurasjonskatalogen din (se [Dependencies](https://opencode.ai/docs/nb/plugins#dependencies) ), eller publisere plugin-en til npm og [legg den til i konfigurasjonen din](https://opencode.ai/docs/config#plugins) . * * * ### [Lasterekkefølge](https://opencode.ai/docs/nb/plugins#lasterekkef%C3%B8lge) Plugins lastes inn fra alle kilder og alle kroker kjøres i rekkefølge. Lastrekkefølgen er: 1. Global konfigurasjon (`~/.config/opencode/opencode.json`) 2. Prosjektkonfigurasjon (`opencode.json`) 3. Global plugin-katalog (`~/.config/opencode/plugins/`) 4. Prosjektpluginkatalog (`.opencode/plugins/`) Dupliserte npm-pakker med samme navn og versjon lastes inn én gang. Imidlertid lastes en lokal plugin og en npm plugin med lignende navn begge separat. * * * [Opprette en plugin](https://opencode.ai/docs/nb/plugins#opprette-en-plugin) ----------------------------------------------------------------------------- En plugin er en **JavaScript/TypeScript-modul** som eksporterer en eller flere plugin-moduler funksjoner. Hver funksjon mottar et kontekstobjekt og returnerer et krokobjekt. * * * ### [Avhengigheter](https://opencode.ai/docs/nb/plugins#avhengigheter) Lokale plugins og tilpassede verktøy kan bruke eksterne npm-pakker. Legg til en `package.json` til konfigurasjonskatalogen med avhengighetene du trenger. { "dependencies": { "shescape": "^2.1.0" }} OpenCode kjører `bun install` ved oppstart for å installere disse. Programtilleggene og verktøyene dine kan deretter importere dem. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Grunnleggende struktur](https://opencode.ai/docs/nb/plugins#grunnleggende-struktur) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} Plugin-funksjonen mottar: * `project`: Gjeldende prosjektinformasjon. * `directory`: Gjeldende arbeidskatalog. * `worktree`: Git-arbeidstrebanen. * `client`: En OpenCode SDK klient for samhandling med AI. * `$`: Buns [shell API](https://bun.com/docs/runtime/shell) for å utføre kommandoer. * * * ### [TypeScript-støtte](https://opencode.ai/docs/nb/plugins#typescript-st%C3%B8tte) For TypeScript-plugins kan du importere typer fra plugin-pakken: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Hendelser](https://opencode.ai/docs/nb/plugins#hendelser) Plugins kan abonnere på hendelser som vist nedenfor i Eksempler-delen. Her er en liste over de forskjellige hendelsene som er tilgjengelige. #### [Kommandohendelser](https://opencode.ai/docs/nb/plugins#kommandohendelser) * `command.executed` #### [Filhendelser](https://opencode.ai/docs/nb/plugins#filhendelser) * `file.edited` * `file.watcher.updated` #### [Installasjonshendelser](https://opencode.ai/docs/nb/plugins#installasjonshendelser) * `installation.updated` #### [LSP Hendelser](https://opencode.ai/docs/nb/plugins#lsp-hendelser) * `lsp.client.diagnostics` * `lsp.updated` #### [Meldingshendelser](https://opencode.ai/docs/nb/plugins#meldingshendelser) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Tillatelseshendelser](https://opencode.ai/docs/nb/plugins#tillatelseshendelser) * `permission.asked` * `permission.replied` #### [Serverhendelser](https://opencode.ai/docs/nb/plugins#serverhendelser) * `server.connected` #### [Sesjonshendelser](https://opencode.ai/docs/nb/plugins#sesjonshendelser) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Todo-hendelser](https://opencode.ai/docs/nb/plugins#todo-hendelser) * `todo.updated` #### [Shell-hendelser](https://opencode.ai/docs/nb/plugins#shell-hendelser) * `shell.env` #### [Verktøyhendelser](https://opencode.ai/docs/nb/plugins#verkt%C3%B8yhendelser) * `tool.execute.after` * `tool.execute.before` #### [TUI Hendelser](https://opencode.ai/docs/nb/plugins#tui-hendelser) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Eksempler](https://opencode.ai/docs/nb/plugins#eksempler) ----------------------------------------------------------- Her er noen eksempler på plugins du kan bruke for å utvide OpenCode. * * * ### [Send varsler](https://opencode.ai/docs/nb/plugins#send-varsler) Send varsler når visse hendelser inntreffer: 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"'` } }, }} Vi bruker `osascript` for å kjøre AppleScript på macOS. Her bruker vi den til å sende varsler. * * * ### [.env-beskyttelse](https://opencode.ai/docs/nb/plugins#env-beskyttelse) Hindre OpenCode fra å lese `.env` filer: 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") } }, }} * * * ### [Injiser miljøvariabler](https://opencode.ai/docs/nb/plugins#injiser-milj%C3%B8variabler) Injiser miljøvariabler i all shell-utførelse (AI-verktøy og brukerterminaler): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Egendefinerte verktøy](https://opencode.ai/docs/nb/plugins#egendefinerte-verkt%C3%B8y) Plugins kan også legge til egendefinerte verktøy til OpenCode: 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})` }, }), }, }} `tool`\-hjelperen lager et tilpasset verktøy som OpenCode kan kalle. Den tar en Zod-skjemafunksjon og returnerer en verktøydefinisjon med: * `description`: Hva verktøyet gjør * `args`: Zod-skjema for verktøyets argumenter * `execute`: Funksjon som kjører når verktøyet kalles Dine egendefinerte verktøy vil være tilgjengelige for OpenCode sammen med innebygde verktøy. * * * ### [Logging](https://opencode.ai/docs/nb/plugins#logging) Bruk `client.app.log()` i stedet for `console.log` for strukturert logging: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Nivåer: `debug`, `info`, `warn`, `error`. Se [SDK dokumentasjon](https://opencode.ai/docs/sdk) for detaljer. * * * ### [Komprimerings-hooks](https://opencode.ai/docs/nb/plugins#komprimerings-hooks) Tilpass konteksten inkludert når en økt komprimeres: 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`) }, }} `experimental.session.compacting`\-kroken trigges før LLM genererer et fortsettelsessammendrag. Bruk den til å injisere domenespesifikk kontekst som standard komprimeringsprompt ville gå glipp av. Du kan også erstatte komprimeringsprompten helt ved å stille inn `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Når `output.prompt` er angitt, erstatter den standard komprimeringsprompt fullstendig. `output.context`\-matrisen ignoreres i dette tilfellet. --- # Plugin | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/plugins#_top) Plugin ====== Scrivi plugin per estendere OpenCode. I plugin ti permettono di estendere OpenCode agganciandoti a vari eventi e personalizzando il comportamento. Puoi creare plugin per aggiungere nuove funzionalità, integrare servizi esterni o modificare il comportamento predefinito di OpenCode. Per esempi, dai un’occhiata ai [plugin](https://opencode.ai/docs/ecosystem#plugins) creati dalla community. * * * [Usare un plugin](https://opencode.ai/docs/it/plugins#usare-un-plugin) ----------------------------------------------------------------------- Ci sono due modi per caricare i plugin. * * * ### [Da file locali](https://opencode.ai/docs/it/plugins#da-file-locali) Metti file JavaScript o TypeScript nella directory dei plugin. * `.opencode/plugins/` - plugin a livello progetto * `~/.config/opencode/plugins/` - plugin globali I file in queste directory vengono caricati automaticamente all’avvio. * * * ### [Da npm](https://opencode.ai/docs/it/plugins#da-npm) Specifica i pacchetti npm nel tuo file di configurazione. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Sono supportati sia pacchetti npm normali sia scoped. Sfoglia i plugin disponibili nell’[ecosistema](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Come vengono installati i plugin](https://opencode.ai/docs/it/plugins#come-vengono-installati-i-plugin) I **plugin npm** vengono installati automaticamente usando Bun all’avvio. I pacchetti e le loro dipendenze vengono cache-ati in `~/.cache/opencode/node_modules/`. I **plugin locali** vengono caricati direttamente dalla directory dei plugin. Per usare pacchetti esterni, devi creare un `package.json` nella directory di configurazione (vedi [Dipendenze](https://opencode.ai/docs/it/plugins#dependencies) ) oppure pubblicare il plugin su npm e [aggiungerlo alla configurazione](https://opencode.ai/docs/config#plugins) . * * * ### [Ordine di caricamento](https://opencode.ai/docs/it/plugins#ordine-di-caricamento) I plugin vengono caricati da tutte le sorgenti e tutti gli hook vengono eseguiti in sequenza. L’ordine di caricamento è: 1. Config globale (`~/.config/opencode/opencode.json`) 2. Config di progetto (`opencode.json`) 3. Directory plugin globale (`~/.config/opencode/plugins/`) 4. Directory plugin di progetto (`.opencode/plugins/`) I pacchetti npm duplicati con lo stesso nome e versione vengono caricati una sola volta. Tuttavia, un plugin locale e un plugin npm con nomi simili vengono entrambi caricati separatamente. * * * [Creare un plugin](https://opencode.ai/docs/it/plugins#creare-un-plugin) ------------------------------------------------------------------------- Un plugin è un **modulo JavaScript/TypeScript** che esporta una o più funzioni di plugin. Ogni funzione riceve un oggetto di contesto e restituisce un oggetto di hook. * * * ### [Dipendenze](https://opencode.ai/docs/it/plugins#dipendenze) I plugin locali e gli strumenti personalizzati possono usare pacchetti npm esterni. Aggiungi un `package.json` alla tua directory di configurazione con le dipendenze di cui hai bisogno. { "dependencies": { "shescape": "^2.1.0" }} OpenCode esegue `bun install` all’avvio per installarle. I tuoi plugin e strumenti potranno poi importarle. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Struttura base](https://opencode.ai/docs/it/plugins#struttura-base) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} La funzione del plugin riceve: * `project`: informazioni sul progetto corrente. * `directory`: la working directory corrente. * `worktree`: il path del worktree git. * `client`: un client SDK di opencode per interagire con l’AI. * `$`: la [shell API](https://bun.com/docs/runtime/shell) di Bun per eseguire comandi. * * * ### [Supporto TypeScript](https://opencode.ai/docs/it/plugins#supporto-typescript) Per i plugin TypeScript, puoi importare i tipi dal pacchetto plugin: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Eventi](https://opencode.ai/docs/it/plugins#eventi) I plugin possono sottoscrivere eventi come mostrato sotto nella sezione Esempi. Ecco l’elenco dei diversi eventi disponibili. #### [Eventi dei comandi](https://opencode.ai/docs/it/plugins#eventi-dei-comandi) * `command.executed` #### [Eventi dei file](https://opencode.ai/docs/it/plugins#eventi-dei-file) * `file.edited` * `file.watcher.updated` #### [Eventi di installazione](https://opencode.ai/docs/it/plugins#eventi-di-installazione) * `installation.updated` #### [Eventi LSP](https://opencode.ai/docs/it/plugins#eventi-lsp) * `lsp.client.diagnostics` * `lsp.updated` #### [Eventi dei messaggi](https://opencode.ai/docs/it/plugins#eventi-dei-messaggi) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Eventi dei permessi](https://opencode.ai/docs/it/plugins#eventi-dei-permessi) * `permission.asked` * `permission.replied` #### [Eventi del server](https://opencode.ai/docs/it/plugins#eventi-del-server) * `server.connected` #### [Eventi delle sessioni](https://opencode.ai/docs/it/plugins#eventi-delle-sessioni) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Eventi della todo](https://opencode.ai/docs/it/plugins#eventi-della-todo) * `todo.updated` #### [Eventi della shell](https://opencode.ai/docs/it/plugins#eventi-della-shell) * `shell.env` #### [Eventi degli strumenti](https://opencode.ai/docs/it/plugins#eventi-degli-strumenti) * `tool.execute.after` * `tool.execute.before` #### [Eventi TUI](https://opencode.ai/docs/it/plugins#eventi-tui) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Esempi](https://opencode.ai/docs/it/plugins#esempi) ----------------------------------------------------- Ecco alcuni esempi di plugin che puoi usare per estendere opencode. * * * ### [Invia notifiche](https://opencode.ai/docs/it/plugins#invia-notifiche) Invia notifiche quando avvengono certi eventi: 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"'` } }, }} Stiamo usando `osascript` per eseguire AppleScript su macOS. Qui lo usiamo per inviare notifiche. * * * ### [Protezione .env](https://opencode.ai/docs/it/plugins#protezione-env) Impedisci a opencode di leggere i file `.env`: 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") } }, }} * * * ### [Inietta variabili d’ambiente](https://opencode.ai/docs/it/plugins#inietta-variabili-dambiente) Inietta variabili d’ambiente in tutte le esecuzioni di shell (strumenti AI e terminale utente): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Strumenti personalizzati](https://opencode.ai/docs/it/plugins#strumenti-personalizzati) I plugin possono anche aggiungere strumenti personalizzati a opencode: 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})` }, }), }, }} L’helper `tool` crea uno strumento personalizzato che opencode può chiamare. Accetta una funzione di schema Zod e restituisce una definizione di tool con: * `description`: cosa fa lo strumento * `args`: schema Zod per gli argomenti dello strumento * `execute`: funzione eseguita quando lo strumento viene chiamato I tuoi strumenti personalizzati saranno disponibili in opencode insieme agli strumenti integrati. * * * ### [Logging](https://opencode.ai/docs/it/plugins#logging) Usa `client.app.log()` invece di `console.log` per logging strutturato: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Livelli: `debug`, `info`, `warn`, `error`. Vedi la [documentazione SDK](https://opencode.ai/docs/sdk) per i dettagli. * * * ### [Hook di compaction](https://opencode.ai/docs/it/plugins#hook-di-compaction) Personalizza il contesto incluso quando una sessione viene compattata: 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`) }, }} L’hook `experimental.session.compacting` scatta prima che l’LLM generi un riassunto di continuazione. Usalo per iniettare contesto specifico di dominio che il prompt di compaction predefinito potrebbe non includere. Puoi anche sostituire completamente il prompt di compaction impostando `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Quando `output.prompt` è impostato, sostituisce completamente il prompt di compaction predefinito. In questo caso l’array `output.context` viene ignorato. --- # Plugins | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/plugins#_top) Plugins ======= Escreva seus próprios plugins para estender o opencode. Plugins permitem que você estenda o opencode conectando-se a vários eventos e personalizando o comportamento. Você pode criar plugins para adicionar novos recursos, integrar-se a serviços externos ou modificar o comportamento padrão do opencode. Para exemplos, confira os [plugins](https://opencode.ai/docs/ecosystem#plugins) criados pela comunidade. * * * [Usando um plugin](https://opencode.ai/docs/pt-br/plugins#usando-um-plugin) ---------------------------------------------------------------------------- Existem duas maneiras de carregar plugins. * * * ### [De arquivos locais](https://opencode.ai/docs/pt-br/plugins#de-arquivos-locais) Coloque arquivos JavaScript ou TypeScript no diretório de plugins. * `.opencode/plugins/` - Plugins em nível de projeto * `~/.config/opencode/plugins/` - Plugins globais Os arquivos nesses diretórios são carregados automaticamente na inicialização. * * * ### [Do npm](https://opencode.ai/docs/pt-br/plugins#do-npm) Especifique pacotes npm no seu arquivo de configuração. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Pacotes npm regulares e escopados são suportados. Navegue pelos plugins disponíveis no [ecossistema](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Como os plugins são instalados](https://opencode.ai/docs/pt-br/plugins#como-os-plugins-s%C3%A3o-instalados) **Plugins npm** são instalados automaticamente usando Bun na inicialização. Pacotes e suas dependências são armazenados em cache em `~/.cache/opencode/node_modules/`. **Plugins locais** são carregados diretamente do diretório de plugins. Para usar pacotes externos, você deve criar um `package.json` dentro do seu diretório de configuração (veja [Dependências](https://opencode.ai/docs/pt-br/plugins#dependencies) ), ou publicar o plugin no npm e [adicioná-lo à sua configuração](https://opencode.ai/docs/config#plugins) . * * * ### [Ordem de carregamento](https://opencode.ai/docs/pt-br/plugins#ordem-de-carregamento) Os plugins são carregados de todas as fontes e todos os hooks são executados em sequência. A ordem de carregamento é: 1. Configuração global (`~/.config/opencode/opencode.json`) 2. Configuração do projeto (`opencode.json`) 3. Diretório de plugins global (`~/.config/opencode/plugins/`) 4. Diretório de plugins do projeto (`.opencode/plugins/`) Pacotes npm duplicados com o mesmo nome e versão são carregados uma vez. No entanto, um plugin local e um plugin npm com nomes semelhantes são carregados separadamente. * * * [Criando um plugin](https://opencode.ai/docs/pt-br/plugins#criando-um-plugin) ------------------------------------------------------------------------------ Um plugin é um **módulo JavaScript/TypeScript** que exporta uma ou mais funções de plugin. Cada função recebe um objeto de contexto e retorna um objeto de hooks. * * * ### [Dependências](https://opencode.ai/docs/pt-br/plugins#depend%C3%AAncias) Plugins locais e ferramentas personalizadas podem usar pacotes npm externos. Adicione um `package.json` ao seu diretório de configuração com as dependências necessárias. { "dependencies": { "shescape": "^2.1.0" }} O opencode executa `bun install` na inicialização para instalar esses pacotes. Seus plugins e ferramentas podem então importá-los. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Estrutura básica](https://opencode.ai/docs/pt-br/plugins#estrutura-b%C3%A1sica) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} A função do plugin recebe: * `project`: As informações do projeto atual. * `directory`: O diretório de trabalho atual. * `worktree`: O caminho do worktree do git. * `client`: Um cliente SDK do opencode para interagir com a AI. * `$`: A [API shell](https://bun.com/docs/runtime/shell) do Bun para executar comandos. * * * ### [Suporte a TypeScript](https://opencode.ai/docs/pt-br/plugins#suporte-a-typescript) Para plugins TypeScript, você pode importar tipos do pacote de plugin: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Eventos](https://opencode.ai/docs/pt-br/plugins#eventos) Plugins podem se inscrever em eventos como visto abaixo na seção Exemplos. Aqui está uma lista dos diferentes eventos disponíveis. #### [Eventos de Comando](https://opencode.ai/docs/pt-br/plugins#eventos-de-comando) * `command.executed` #### [Eventos de Arquivo](https://opencode.ai/docs/pt-br/plugins#eventos-de-arquivo) * `file.edited` * `file.watcher.updated` #### [Eventos de Instalação](https://opencode.ai/docs/pt-br/plugins#eventos-de-instala%C3%A7%C3%A3o) * `installation.updated` #### [Eventos LSP](https://opencode.ai/docs/pt-br/plugins#eventos-lsp) * `lsp.client.diagnostics` * `lsp.updated` #### [Eventos de Mensagem](https://opencode.ai/docs/pt-br/plugins#eventos-de-mensagem) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Eventos de Permissão](https://opencode.ai/docs/pt-br/plugins#eventos-de-permiss%C3%A3o) * `permission.asked` * `permission.replied` #### [Eventos de Servidor](https://opencode.ai/docs/pt-br/plugins#eventos-de-servidor) * `server.connected` #### [Eventos de Sessão](https://opencode.ai/docs/pt-br/plugins#eventos-de-sess%C3%A3o) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Eventos de Todo](https://opencode.ai/docs/pt-br/plugins#eventos-de-todo) * `todo.updated` #### [Eventos de Shell](https://opencode.ai/docs/pt-br/plugins#eventos-de-shell) * `shell.env` #### [Eventos de Ferramenta](https://opencode.ai/docs/pt-br/plugins#eventos-de-ferramenta) * `tool.execute.after` * `tool.execute.before` #### [Eventos TUI](https://opencode.ai/docs/pt-br/plugins#eventos-tui) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Exemplos](https://opencode.ai/docs/pt-br/plugins#exemplos) ------------------------------------------------------------ Aqui estão alguns exemplos de plugins que você pode usar para estender o opencode. * * * ### [Enviando notificações](https://opencode.ai/docs/pt-br/plugins#enviando-notifica%C3%A7%C3%B5es) Envie notificações quando certos eventos ocorrerem: 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"'` } }, }} Estamos usando `osascript` para executar AppleScript no macOS. Aqui estamos usando para enviar notificações. * * * ### [Proteção .env](https://opencode.ai/docs/pt-br/plugins#prote%C3%A7%C3%A3o-env) Impeça o opencode de ler arquivos `.env`: 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") } }, }} * * * ### [Injetando variáveis de ambiente](https://opencode.ai/docs/pt-br/plugins#injetando-vari%C3%A1veis-de-ambiente) Injete variáveis de ambiente em todas as execuções de shell (ferramentas de AI e terminais de usuário): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Ferramentas personalizadas](https://opencode.ai/docs/pt-br/plugins#ferramentas-personalizadas) Plugins também podem adicionar ferramentas personalizadas ao opencode: 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})` }, }), }, }} O helper `tool` cria uma ferramenta personalizada que o opencode pode chamar. Ele aceita uma função de esquema Zod e retorna uma definição de ferramenta com: * `description`: O que a ferramenta faz * `args`: Esquema Zod para os argumentos da ferramenta * `execute`: Função que é executada quando a ferramenta é chamada Suas ferramentas personalizadas estarão disponíveis para o opencode junto com as ferramentas integradas. * * * ### [Registro](https://opencode.ai/docs/pt-br/plugins#registro) Use `client.app.log()` em vez de `console.log` para registro estruturado: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Níveis: `debug`, `info`, `warn`, `error`. Veja a [documentação do SDK](https://opencode.ai/docs/sdk) para detalhes. * * * ### [Hooks de compactação](https://opencode.ai/docs/pt-br/plugins#hooks-de-compacta%C3%A7%C3%A3o) Personalize o contexto incluído quando uma sessão é compactada: 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`) }, }} O hook `experimental.session.compacting` é acionado antes que o LLM gere um resumo de continuação. Use-o para injetar contexto específico de domínio que o prompt de compactação padrão poderia perder. Você também pode substituir o prompt de compactação completamente definindo `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Quando `output.prompt` é definido, ele substitui completamente o prompt de compactação padrão. O array `output.context` é ignorado neste caso. --- # 外掛 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/plugins#_top) 外掛 == 編寫自己的外掛來擴展 OpenCode。 外掛允許您透過掛鉤各種事件和自訂行為來擴展 OpenCode。您可以建立外掛來新增新功能、整合外部服務,或修改 OpenCode 的預設行為。 如需了解範例,請查看社群建立的[外掛](https://opencode.ai/docs/ecosystem#plugins) 。 * * * [使用外掛](https://opencode.ai/docs/zh-tw/plugins#%E4%BD%BF%E7%94%A8%E5%A4%96%E6%8E%9B) ------------------------------------------------------------------------------------ 有兩種方式載入外掛。 * * * ### [從本地檔案載入](https://opencode.ai/docs/zh-tw/plugins#%E5%BE%9E%E6%9C%AC%E5%9C%B0%E6%AA%94%E6%A1%88%E8%BC%89%E5%85%A5) 將 JavaScript 或 TypeScript 檔案放置在外掛目錄中。 * `.opencode/plugins/` - 專案級外掛 * `~/.config/opencode/plugins/` - 全域外掛 這些目錄中的檔案會在啟動時自動載入。 * * * ### [從 npm 載入](https://opencode.ai/docs/zh-tw/plugins#%E5%BE%9E-npm-%E8%BC%89%E5%85%A5) 在設定檔中指定 npm 套件。 { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} 支援常規和帶作用域的 npm 套件。 瀏覽[生態系統](https://opencode.ai/docs/ecosystem#plugins) 中的可用外掛。 * * * ### [外掛的安裝方式](https://opencode.ai/docs/zh-tw/plugins#%E5%A4%96%E6%8E%9B%E7%9A%84%E5%AE%89%E8%A3%9D%E6%96%B9%E5%BC%8F) **npm 外掛**在啟動時使用 Bun 自動安裝。套件及其相依套件會快取在 `~/.cache/opencode/node_modules/` 中。 **本地外掛**直接從外掛目錄載入。如果需要使用外部套件,您必須在設定目錄中建立 `package.json`(參見[相依套件](https://opencode.ai/docs/zh-tw/plugins#dependencies) ),或者將外掛發布到 npm 並[將其新增到設定中](https://opencode.ai/docs/config#plugins) 。 * * * ### [載入順序](https://opencode.ai/docs/zh-tw/plugins#%E8%BC%89%E5%85%A5%E9%A0%86%E5%BA%8F) 外掛從所有來源載入,所有鉤子按順序執行。載入順序為: 1. 全域設定 (`~/.config/opencode/opencode.json`) 2. 專案設定 (`opencode.json`) 3. 全域外掛目錄 (`~/.config/opencode/plugins/`) 4. 專案外掛目錄 (`.opencode/plugins/`) 名稱和版本相同的重複 npm 套件只會載入一次。但本地外掛和名稱相似的 npm 外掛會分別獨立載入。 * * * [建立外掛](https://opencode.ai/docs/zh-tw/plugins#%E5%BB%BA%E7%AB%8B%E5%A4%96%E6%8E%9B) ------------------------------------------------------------------------------------ 外掛是一個 **JavaScript/TypeScript 模組**,它匯出一個或多個外掛函式。每個函式接收一個上下文物件,並回傳一個鉤子物件。 * * * ### [相依套件](https://opencode.ai/docs/zh-tw/plugins#%E7%9B%B8%E4%BE%9D%E5%A5%97%E4%BB%B6) 本地外掛和自訂工具可以使用外部 npm 套件。在設定目錄中新增一個 `package.json`,列出所需的相依套件。 { "dependencies": { "shescape": "^2.1.0" }} OpenCode 會在啟動時執行 `bun install` 來安裝這些相依套件。之後您的外掛和工具就可以匯入它們了。 import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [基本結構](https://opencode.ai/docs/zh-tw/plugins#%E5%9F%BA%E6%9C%AC%E7%B5%90%E6%A7%8B) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} 外掛函式接收以下參數: * `project`:當前專案資訊。 * `directory`:當前工作目錄。 * `worktree`:git 工作樹路徑。 * `client`:用於與 AI 互動的 OpenCode SDK 用戶端。 * `$`:Bun 的 [Shell API](https://bun.com/docs/runtime/shell) ,用於執行指令。 * * * ### [TypeScript 支援](https://opencode.ai/docs/zh-tw/plugins#typescript-%E6%94%AF%E6%8F%B4) 對於 TypeScript 外掛,您可以從外掛套件中匯入類型: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [事件](https://opencode.ai/docs/zh-tw/plugins#%E4%BA%8B%E4%BB%B6) 外掛可以訂閱事件,如下方範例部分所示。以下是所有可用事件的列表。 #### [指令事件](https://opencode.ai/docs/zh-tw/plugins#%E6%8C%87%E4%BB%A4%E4%BA%8B%E4%BB%B6) * `command.executed` #### [檔案事件](https://opencode.ai/docs/zh-tw/plugins#%E6%AA%94%E6%A1%88%E4%BA%8B%E4%BB%B6) * `file.edited` * `file.watcher.updated` #### [安裝事件](https://opencode.ai/docs/zh-tw/plugins#%E5%AE%89%E8%A3%9D%E4%BA%8B%E4%BB%B6) * `installation.updated` #### [LSP 事件](https://opencode.ai/docs/zh-tw/plugins#lsp-%E4%BA%8B%E4%BB%B6) * `lsp.client.diagnostics` * `lsp.updated` #### [訊息事件](https://opencode.ai/docs/zh-tw/plugins#%E8%A8%8A%E6%81%AF%E4%BA%8B%E4%BB%B6) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [權限事件](https://opencode.ai/docs/zh-tw/plugins#%E6%AC%8A%E9%99%90%E4%BA%8B%E4%BB%B6) * `permission.asked` * `permission.replied` #### [伺服器事件](https://opencode.ai/docs/zh-tw/plugins#%E4%BC%BA%E6%9C%8D%E5%99%A8%E4%BA%8B%E4%BB%B6) * `server.connected` #### [工作階段事件](https://opencode.ai/docs/zh-tw/plugins#%E5%B7%A5%E4%BD%9C%E9%9A%8E%E6%AE%B5%E4%BA%8B%E4%BB%B6) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [待辦事項事件](https://opencode.ai/docs/zh-tw/plugins#%E5%BE%85%E8%BE%A6%E4%BA%8B%E9%A0%85%E4%BA%8B%E4%BB%B6) * `todo.updated` #### [Shell 事件](https://opencode.ai/docs/zh-tw/plugins#shell-%E4%BA%8B%E4%BB%B6) * `shell.env` #### [工具事件](https://opencode.ai/docs/zh-tw/plugins#%E5%B7%A5%E5%85%B7%E4%BA%8B%E4%BB%B6) * `tool.execute.after` * `tool.execute.before` #### [TUI 事件](https://opencode.ai/docs/zh-tw/plugins#tui-%E4%BA%8B%E4%BB%B6) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [範例](https://opencode.ai/docs/zh-tw/plugins#%E7%AF%84%E4%BE%8B) ---------------------------------------------------------------- 以下是一些可用於擴展 OpenCode 的外掛範例。 * * * ### [傳送通知](https://opencode.ai/docs/zh-tw/plugins#%E5%82%B3%E9%80%81%E9%80%9A%E7%9F%A5) 在特定事件發生時傳送通知: 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"'` } }, }} 這裡使用 `osascript` 在 macOS 上執行 AppleScript 來傳送通知。 * * * ### [.env 保護](https://opencode.ai/docs/zh-tw/plugins#env-%E4%BF%9D%E8%AD%B7) 阻止 OpenCode 讀取 `.env` 檔案: 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") } }, }} * * * ### [注入環境變數](https://opencode.ai/docs/zh-tw/plugins#%E6%B3%A8%E5%85%A5%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8) 將環境變數注入所有 Shell 執行(AI 工具和使用者終端機): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [自訂工具](https://opencode.ai/docs/zh-tw/plugins#%E8%87%AA%E8%A8%82%E5%B7%A5%E5%85%B7) 外掛還可以為 OpenCode 新增自訂工具: 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})` }, }), }, }} `tool` 輔助函式用於建立 OpenCode 可呼叫的自訂工具。它接受一個 Zod schema 函式,並回傳一個工具定義,包含: * `description`:工具的功能描述 * `args`:工具參數的 Zod schema * `execute`:工具被呼叫時執行的函式 您的自訂工具將與內建工具一起在 OpenCode 中可用。 * * * ### [日誌記錄](https://opencode.ai/docs/zh-tw/plugins#%E6%97%A5%E8%AA%8C%E8%A8%98%E9%8C%84) 使用 `client.app.log()` 代替 `console.log` 進行結構化日誌記錄: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} 日誌層級:`debug`、`info`、`warn`、`error`。詳情請參閱 [SDK 文件](https://opencode.ai/docs/sdk) 。 * * * ### [壓縮鉤子](https://opencode.ai/docs/zh-tw/plugins#%E5%A3%93%E7%B8%AE%E9%89%A4%E5%AD%90) 自訂工作階段壓縮時包含的上下文: 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`) }, }} `experimental.session.compacting` 鉤子在 LLM 生成續接摘要之前觸發。使用它來注入預設壓縮提示詞可能遺漏的領域特定上下文。 您還可以透過設定 `output.prompt` 來完全替換壓縮提示詞: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} 當設定了 `output.prompt` 時,它會完全替換預設的壓縮提示詞。在這種情況下,`output.context` 陣列將被忽略。 --- # 플러그인 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/plugins#_top) 플러그인 ==== OpenCode를 확장하기 위해 자신만의 플러그인을 작성하세요. 플러그인은 다양한 이벤트와 사용자 정의 행동으로 후킹하여 opencode를 확장 할 수 있습니다. 플러그인을 사용하여 새로운 기능을 추가하거나, 외부 서비스와 통합하거나, opencode의 기본 동작을 수정할 수 있습니다. 예를 들어, 커뮤니티에 의해 생성 된 [plugins](https://opencode.ai/docs/ecosystem#plugins) 를 확인하십시오. * * * [플러그인 사용](https://opencode.ai/docs/ko/plugins#%ED%94%8C%EB%9F%AC%EA%B7%B8%EC%9D%B8-%EC%82%AC%EC%9A%A9) ------------------------------------------------------------------------------------------------------- 플러그인을 로드하는 두 가지 방법이 있습니다. * * * ### [로컬 파일에서](https://opencode.ai/docs/ko/plugins#%EB%A1%9C%EC%BB%AC-%ED%8C%8C%EC%9D%BC%EC%97%90%EC%84%9C) 플러그인 디렉토리에 JavaScript 또는 TypeScript 파일을 배치합니다. * `.opencode/plugins/` - 프로젝트 레벨 플러그인 * `~/.config/opencode/plugins/` - 글로벌 플러그인 이 디렉토리의 파일은 시작 시 자동으로 로드됩니다. * * * ### [npm에서](https://opencode.ai/docs/ko/plugins#npm%EC%97%90%EC%84%9C) config 파일에 npm 패키지를 지정합니다. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} 일반 패키지 및 스코프 npm 패키지 모두 지원됩니다. [ecosystem](https://opencode.ai/docs/ecosystem#plugins) 에서 사용할 수 있는 플러그인을 찾아보세요. * * * ### [플러그인이 설치되는 방법](https://opencode.ai/docs/ko/plugins#%ED%94%8C%EB%9F%AC%EA%B7%B8%EC%9D%B8%EC%9D%B4-%EC%84%A4%EC%B9%98%EB%90%98%EB%8A%94-%EB%B0%A9%EB%B2%95) **npm 플러그인**은 시작시 Bun을 사용하여 자동으로 설치됩니다. 패키지와 그 의존성은 `~/.cache/opencode/node_modules/`에 캐시됩니다. **로컬 플러그인**은 플러그인 디렉토리에서 직접 로드됩니다. 외부 패키지를 사용하려면 구성 디렉토리 내에 `package.json`을 작성해야 하거나([의존성](https://opencode.ai/docs/ko/plugins#%EC%9D%98%EC%A1%B4%EC%84%B1) 참조), 플러그인을 npm에 게시하고 [config에 추가](https://opencode.ai/docs/config#plugins) 해야 합니다. * * * ### [로드 순서](https://opencode.ai/docs/ko/plugins#%EB%A1%9C%EB%93%9C-%EC%88%9C%EC%84%9C) 플러그인은 모든 소스에서 로드되며 모든 후크는 순서대로 실행됩니다. 로드 순서는 다음과 같습니다: 1. 글로벌 구성 (`~/.config/opencode/opencode.json`) 2. 프로젝트 구성 (`opencode.json`) 3. 글로벌 플러그인 디렉토리 (`~/.config/opencode/plugins/`) 4. 프로젝트 플러그인 디렉토리 (`.opencode/plugins/`) 중복된 이름과 버전의 npm 패키지는 한 번만 로드됩니다. 하지만 로컬 플러그인과 npm 플러그인의 이름이 비슷하더라도 둘 다 별도로 로드됩니다. * * * [플러그인 만들기](https://opencode.ai/docs/ko/plugins#%ED%94%8C%EB%9F%AC%EA%B7%B8%EC%9D%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0) ----------------------------------------------------------------------------------------------------------------- 플러그인은 하나 이상의 플러그인 함수를 내보내는 **JavaScript/TypeScript 모듈**입니다. 각 함수는 context 객체를 수신하고 hooks 객체를 반환합니다. * * * ### [의존성](https://opencode.ai/docs/ko/plugins#%EC%9D%98%EC%A1%B4%EC%84%B1) 로컬 플러그인 및 사용자 정의 도구는 외부 npm 패키지를 사용할 수 있습니다. config 디렉토리에 `package.json`을 추가하고 필요한 의존성을 명시하십시오. { "dependencies": { "shescape": "^2.1.0" }} opencode는 시작 시 `bun install`을 실행하여 이를 설치합니다. 이후 플러그인 및 도구에서 가져올 수 있습니다. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [기본 구조](https://opencode.ai/docs/ko/plugins#%EA%B8%B0%EB%B3%B8-%EA%B5%AC%EC%A1%B0) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} 플러그인 함수가 받는 인자: * `project`: 현재 프로젝트 정보. * `directory`: 현재 작업 디렉토리. * `worktree`: git worktree 경로. * `client`: AI와 상호 작용을 위한 opencode SDK 클라이언트. * `$`: 명령어를 실행하기 위한 Bun의 [shell API](https://bun.com/docs/runtime/shell) . * * * ### [TypeScript 지원](https://opencode.ai/docs/ko/plugins#typescript-%EC%A7%80%EC%9B%90) TypeScript 플러그인의 경우 플러그인 패키지에서 타입을 가져올 수 있습니다. import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [이벤트](https://opencode.ai/docs/ko/plugins#%EC%9D%B4%EB%B2%A4%ED%8A%B8) 플러그인은 아래 예제 섹션에서 볼 수 있듯이 이벤트를 구독할 수 있습니다. 사용 가능한 이벤트 목록은 다음과 같습니다. #### [명령어 이벤트](https://opencode.ai/docs/ko/plugins#%EB%AA%85%EB%A0%B9%EC%96%B4-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `command.executed` #### [파일 이벤트](https://opencode.ai/docs/ko/plugins#%ED%8C%8C%EC%9D%BC-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `file.edited` * `file.watcher.updated` #### [설치 이벤트](https://opencode.ai/docs/ko/plugins#%EC%84%A4%EC%B9%98-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `installation.updated` #### [LSP 이벤트](https://opencode.ai/docs/ko/plugins#lsp-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `lsp.client.diagnostics` * `lsp.updated` #### [메시지 이벤트](https://opencode.ai/docs/ko/plugins#%EB%A9%94%EC%8B%9C%EC%A7%80-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [권한 이벤트](https://opencode.ai/docs/ko/plugins#%EA%B6%8C%ED%95%9C-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `permission.asked` * `permission.replied` #### [서버 이벤트](https://opencode.ai/docs/ko/plugins#%EC%84%9C%EB%B2%84-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `server.connected` #### [세션 이벤트](https://opencode.ai/docs/ko/plugins#%EC%84%B8%EC%85%98-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Todo 이벤트](https://opencode.ai/docs/ko/plugins#todo-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `todo.updated` #### [셸 이벤트](https://opencode.ai/docs/ko/plugins#%EC%85%B8-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `shell.env` #### [도구 이벤트](https://opencode.ai/docs/ko/plugins#%EB%8F%84%EA%B5%AC-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `tool.execute.after` * `tool.execute.before` #### [TUI 이벤트](https://opencode.ai/docs/ko/plugins#tui-%EC%9D%B4%EB%B2%A4%ED%8A%B8) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [예제](https://opencode.ai/docs/ko/plugins#%EC%98%88%EC%A0%9C) ------------------------------------------------------------- opencode를 확장하기 위해 사용할 수 있는 플러그인 예제입니다. * * * ### [알림 보내기](https://opencode.ai/docs/ko/plugins#%EC%95%8C%EB%A6%BC-%EB%B3%B4%EB%82%B4%EA%B8%B0) 특정 이벤트가 발생할 때 알림을 전송: 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"'` } }, }} macOS에서 AppleScript를 실행하기 위해 `osascript`를 사용하고 있습니다. 여기서는 알림을 보내는 데 사용합니다. * * * ### [.env 보호](https://opencode.ai/docs/ko/plugins#env-%EB%B3%B4%ED%98%B8) opencode가 `.env` 파일을 읽지 못하도록 방지: 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 환경 변수](https://opencode.ai/docs/ko/plugins#inject-%ED%99%98%EA%B2%BD-%EB%B3%80%EC%88%98) 모든 shell 실행(AI 도구 및 사용자 terminal)에 환경 변수 주입: export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [사용자 정의 도구](https://opencode.ai/docs/ko/plugins#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98-%EB%8F%84%EA%B5%AC) 플러그인은 opencode에 사용자 정의 도구를 추가할 수 있습니다: 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})` }, }), }, }} `tool` helper는 opencode가 호출할 수 있는 사용자 정의 도구를 만듭니다. Zod 스키마 함수를 받고 다음을 포함하는 도구 정의를 반환합니다: * `description`: 도구가 하는 일 * `args`: 도구의 인수에 대한 Zod 스키마 * `execute`: 도구가 호출될 때 실행되는 함수 사용자 정의 도구는 내장 도구와 함께 opencode에서 사용할 수 있습니다. * * * ### [로깅](https://opencode.ai/docs/ko/plugins#%EB%A1%9C%EA%B9%85) 구조화된 로깅을 위해 `console.log` 대신 `client.app.log()`를 사용하십시오: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} 레벨: `debug`, `info`, `warn`, `error`. [SDK 문서](https://opencode.ai/docs/sdk) 를 참고하세요. * * * ### [Compaction 훅](https://opencode.ai/docs/ko/plugins#compaction-%ED%9B%85) 세션이 압축될 때 포함되는 컨텍스트를 사용자 지정할 수 있습니다: 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`) }, }} `experimental.session.compacting` 훅은 LLM이 연속 요약을 생성하기 전에 실행됩니다. 기본 압축 프롬프트가 놓칠 수 있는 도메인별 컨텍스트를 주입하는 데 사용하세요. 또한 `output.prompt`를 설정하여 압축 프롬프트를 완전히 대체할 수도 있습니다: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} `output.prompt`가 설정되면 기본 압축 프롬프트를 완전히 대체합니다. 이 경우 `output.context` 배열은 무시됩니다. --- # Plugins | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/plugins#_top) Plugins ======= Schreiben Sie Ihre eigenen Plugins, um OpenCode zu erweitern. Mit Plugins können Sie OpenCode erweitern, indem Sie verschiedene Ereignisse einbinden und das Verhalten anpassen. Sie können Plugins erstellen, um neue Funktionen hinzuzufügen, externe Dienste zu integrieren oder das Standardverhalten von OpenCode zu ändern. Beispiele finden Sie im von der Community erstellten [plugins](https://opencode.ai/docs/ecosystem#plugins) . * * * [Plugins verwenden](https://opencode.ai/docs/de/plugins#plugins-verwenden) --------------------------------------------------------------------------- Es gibt zwei Möglichkeiten, Plugins zu laden. * * * ### [Aus lokalen Dateien](https://opencode.ai/docs/de/plugins#aus-lokalen-dateien) Platzieren Sie JavaScript- oder TypeScript-Dateien im Plugin-Verzeichnis. * `.opencode/plugins/` – Plugins auf Projektebene * `~/.config/opencode/plugins/` – Globale Plugins Dateien in diesen Verzeichnissen werden beim Start automatisch geladen. * * * ### [Von npm](https://opencode.ai/docs/de/plugins#von-npm) Geben Sie npm-Pakete in Ihrer Konfigurationsdatei an. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Es werden sowohl reguläre als auch bereichsbezogene NPM-Pakete unterstützt. Durchsuchen Sie die verfügbaren Plugins im [ecosystem](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Plugin-Installation](https://opencode.ai/docs/de/plugins#plugin-installation) **NPM-Plugins** werden beim Start automatisch mit Bun installiert. Pakete und ihre Abhängigkeiten werden in `~/.cache/opencode/node_modules/` zwischengespeichert. **Lokale Plugins** werden direkt aus dem Plugin-Verzeichnis geladen. Um externe Pakete zu verwenden, müssen Sie ein `package.json` in Ihrem Konfigurationsverzeichnis erstellen (siehe [Dependencies](https://opencode.ai/docs/de/plugins#dependencies) ) oder das Plugin auf npm und [add it to your config](https://opencode.ai/docs/config#plugins) veröffentlichen. * * * ### [Ladereihenfolge](https://opencode.ai/docs/de/plugins#ladereihenfolge) Plugins werden aus allen Quellen geladen und alle Hooks werden nacheinander ausgeführt. Die Ladereihenfolge lautet: 1. Globale Konfiguration (`~/.config/opencode/opencode.json`) 2. Projektkonfiguration (`opencode.json`) 3. Globales Plugin-Verzeichnis (`~/.config/opencode/plugins/`) 4. Projekt-Plugin-Verzeichnis (`.opencode/plugins/`) Doppelte npm-Pakete mit demselben Namen und derselben Version werden einmal geladen. Allerdings werden ein lokales Plugin und ein NPM-Plugin mit ähnlichen Namen beide separat geladen. * * * [Plugins erstellen](https://opencode.ai/docs/de/plugins#plugins-erstellen) --------------------------------------------------------------------------- Ein Plugin ist ein **JavaScript/TypeScript-Modul**, das eine oder mehrere Plugin-Funktionen exportiert. Jede Funktion empfängt ein Kontextobjekt und gibt ein Hooks-Objekt zurück. * * * ### [Abhängigkeiten](https://opencode.ai/docs/de/plugins#abh%C3%A4ngigkeiten) Lokale Plugins und benutzerdefinierte Tools können externe npm-Pakete verwenden. Fügen Sie Ihrem Konfigurationsverzeichnis ein `package.json` mit den benötigten Abhängigkeiten hinzu. { "dependencies": { "shescape": "^2.1.0" }} OpenCode führt beim Start `bun install` aus, um diese zu installieren. Ihre Plugins und Tools können sie dann importieren. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Grundstruktur](https://opencode.ai/docs/de/plugins#grundstruktur) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} Die Plugin-Funktion erhält: * `project`: Die aktuellen Projektinformationen. * `directory`: Das aktuelle Arbeitsverzeichnis. * `worktree`: Der Git-Worktree-Pfad. * `client`: Ein OpenCode-SDK-Client für die Interaktion mit AI. * `$`: Buns [shell API](https://bun.com/docs/runtime/shell) zum Ausführen von Befehlen. * * * ### [TypeScript-Unterstützung](https://opencode.ai/docs/de/plugins#typescript-unterst%C3%BCtzung) Für TypeScript-Plugins können Sie Typen aus dem Plugin-Paket importieren: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Ereignisse](https://opencode.ai/docs/de/plugins#ereignisse) Plugins können Ereignisse abonnieren, wie unten im Abschnitt „Beispiele“ gezeigt. Hier finden Sie eine Liste der verschiedenen verfügbaren Veranstaltungen. #### [Befehlsereignisse](https://opencode.ai/docs/de/plugins#befehlsereignisse) * `command.executed` #### [Dateiereignisse](https://opencode.ai/docs/de/plugins#dateiereignisse) * `file.edited` * `file.watcher.updated` #### [Installationsereignisse](https://opencode.ai/docs/de/plugins#installationsereignisse) * `installation.updated` #### [LSP-Ereignisse](https://opencode.ai/docs/de/plugins#lsp-ereignisse) * `lsp.client.diagnostics` * `lsp.updated` #### [Nachrichtenereignisse](https://opencode.ai/docs/de/plugins#nachrichtenereignisse) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Berechtigungsereignisse](https://opencode.ai/docs/de/plugins#berechtigungsereignisse) * `permission.asked` * `permission.replied` #### [Serverereignisse](https://opencode.ai/docs/de/plugins#serverereignisse) * `server.connected` #### [Sitzungsereignisse](https://opencode.ai/docs/de/plugins#sitzungsereignisse) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Todo-Ereignisse](https://opencode.ai/docs/de/plugins#todo-ereignisse) * `todo.updated` #### [Shell-Ereignisse](https://opencode.ai/docs/de/plugins#shell-ereignisse) * `shell.env` #### [Tool-Ereignisse](https://opencode.ai/docs/de/plugins#tool-ereignisse) * `tool.execute.after` * `tool.execute.before` #### [TUI-Ereignisse](https://opencode.ai/docs/de/plugins#tui-ereignisse) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Beispiele](https://opencode.ai/docs/de/plugins#beispiele) ----------------------------------------------------------- Hier sind einige Beispiele für Plugins, mit denen Sie OpenCode erweitern können. * * * ### [Benachrichtigungen senden](https://opencode.ai/docs/de/plugins#benachrichtigungen-senden) Senden Sie Benachrichtigungen, wenn bestimmte Ereignisse eintreten: 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"'` } }, }} Wir verwenden `osascript`, um AppleScript unter macOS auszuführen. Hier verwenden wir es zum Versenden von Benachrichtigungen. * * * ### [.env-Schutz](https://opencode.ai/docs/de/plugins#env-schutz) Verhindern Sie, dass OpenCode `.env`\-Dateien liest: 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") } }, }} * * * ### [Umgebungsvariablen einfügen](https://opencode.ai/docs/de/plugins#umgebungsvariablen-einf%C3%BCgen) Fügen Sie Umgebungsvariablen in alle Shell-Ausführungen ein (AI-Tools und Benutzerterminals): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Benutzerdefinierte Tools](https://opencode.ai/docs/de/plugins#benutzerdefinierte-tools) Plugins können OpenCode auch benutzerdefinierte Tools hinzufügen: 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})` }, }), }, }} Der `tool`\-Helfer erstellt ein benutzerdefiniertes Tool, das OpenCode aufrufen kann. Es verwendet eine Zod-Schemafunktion und gibt eine Tooldefinition zurück mit: * `description`: Was das Tool macht * `args`: Zod-Schema für die Argumente des Tools * `execute`: Funktion, die ausgeführt wird, wenn das Tool aufgerufen wird Ihre benutzerdefinierten Tools stehen neben den integrierten Tools für OpenCode zur Verfügung. * * * ### [Protokollierung](https://opencode.ai/docs/de/plugins#protokollierung) Verwenden Sie `client.app.log()` anstelle von `console.log` für die strukturierte Protokollierung: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Ebenen: `debug`, `info`, `warn`, `error`. Weitere Informationen finden Sie unter [SDK documentation](https://opencode.ai/docs/sdk) . * * * ### [Compaction-Hooks](https://opencode.ai/docs/de/plugins#compaction-hooks) Passen Sie den Kontext an, der beim Komprimieren einer Sitzung einbezogen wird: 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`) }, }} Der Hook `experimental.session.compacting` wird ausgelöst, bevor der Hook LLM eine Fortsetzungszusammenfassung generiert. Verwenden Sie es, um domänenspezifischen Kontext einzufügen, der der standardmäßigen Komprimierungsaufforderung entgehen würde. Sie können die Komprimierungsaufforderung auch vollständig ersetzen, indem Sie `output.prompt` festlegen: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Wenn `output.prompt` festgelegt ist, ersetzt es die standardmäßige Komprimierungsaufforderung vollständig. Das Array `output.context` wird in diesem Fall ignoriert. --- # Rozwiązywanie problemów | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/troubleshooting#_top) Rozwiązywanie problemów ======================= Typowe problemy i sposoby ich rozwiązywania. Aby debugować problemy z opencode, zacznij od sprawdzenia dzienników i danych lokalnych przechowywanych na dysku. * * * [Dzienniki](https://opencode.ai/docs/pl/troubleshooting#dzienniki) ------------------------------------------------------------------- Pliki logów są zapisywane w: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.local\share\opencode\log` Nazwy plików dziennika zawierają znaczniki czasu (np. `2025-01-09T123456.log`) i przechowywanych jest 10 ostatnich plików dziennika. Możesz ustawić poziom dziennika za pomocą opcji wiersza poleceń `--log-level`, aby uzyskać bardziej szczegółowe informacje debugowania. Na przykład `opencode --log-level DEBUG`. * * * [Przechowywanie danych](https://opencode.ai/docs/pl/troubleshooting#przechowywanie-danych) ------------------------------------------------------------------------------------------- opencode przechowuje dane sesji i inne dane aplikacji na dysku pod adresem: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.local\share\opencode` Ten katalog zawiera: * `auth.json` - Authentication data like API keys, OAuth tokens * `log/` - Application logs * `project/` — Dane specyficzne dla projektu, takie jak dane sesji i komunikatów * Jeśli projekt znajduje się w repozytorium Git, jest on przechowywany w `.//storage/` * If it is not a Git repo, it is stored in `./global/storage/` * * * [Aplikacja desktopowa](https://opencode.ai/docs/pl/troubleshooting#aplikacja-desktopowa) ----------------------------------------------------------------------------------------- opencode Desktop uruchamia w tle lokalny serwer opencode (sidecar `opencode-cli`). Większość problemów jest spowodowana nieprawidłowo działającą wtyczką, uszkodzoną pamięcią podręczną lub złymi ustawieniami serwera. ### [Szybkie sprawdzenie](https://opencode.ai/docs/pl/troubleshooting#szybkie-sprawdzenie) * Całkowicie zakończ i uruchom ponownie aplikację. * Jeśli aplikacja wyświetli ekran błędu, kliknij **Uruchom ponownie** i skopiuj szczegóły błędu. * Tylko macOS: menu `OpenCode` -> **Załaduj ponownie przeglądarkę internetową** (pomaga, jeśli interfejs użytkownika jest pusty/zawieszony). * * * ### [Wyłączanie wtyczek](https://opencode.ai/docs/pl/troubleshooting#wy%C5%82%C4%85czanie-wtyczek) Jeśli aplikacja komputerowa ulega awarii podczas uruchamiania, zawiesza się lub zachowuje się dziwnie, zacznij od wyłączenia wtyczek. #### [Sprawdź konfigurację globalną](https://opencode.ai/docs/pl/troubleshooting#sprawd%C5%BA-konfiguracj%C4%99-globaln%C4%85) Otwórz globalny plik konfiguracyjny i poszukaj klucza `plugin`. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (lub `~/.config/opencode/opencode.json`) * **macOS/Linux** (starsze instalacje): `~/.local/share/opencode/opencode.jsonc` * **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.config\opencode\opencode.jsonc` Jeśli masz skonfigurowane wtyczki, tymczasowo je wyłącz, usuwając klucz lub ustawiając go na pustą tablicę: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Sprawdź katalogi wtyczek](https://opencode.ai/docs/pl/troubleshooting#sprawd%C5%BA-katalogi-wtyczek) opencode może także ładować lokalne wtyczki z dysku. Tymczasowo usuń je (lub zmień nazwę folderu) i uruchom ponownie aplikację komputerową: * **Wtyczki globalne** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.config\opencode\plugins` * **Wtyczki projektowe** (tylko jeśli używasz konfiguracji dla poszczególnych projektów) * `/.opencode/plugins/` Jeśli aplikacja ponownie zacznie działać, włączaj ponownie wtyczki pojedynczo, aby dowiedzieć się, która powoduje problem. * * * ### [Wyczyść pamięć podręczną](https://opencode.ai/docs/pl/troubleshooting#wyczy%C5%9B%C4%87-pami%C4%99%C4%87-podr%C4%99czn%C4%85) Jeśli wyłączenie wtyczek nie pomoże (lub instalacja wtyczki utknęła), wyczyść pamięć podręczną, aby opencode mógł ją odbudować. 1. Całkowicie zamknij opencode Desktop. 2. Usuń katalog pamięci podręcznej: * **macOS**: Finder -> `Cmd+Shift+G` -> paste `~/.cache/opencode` * **Linux**: usuń `~/.cache/opencode` (lub uruchom `rm -rf ~/.cache/opencode`) * **Windows**: Naciśnij `WIN+R` i wklej `%USERPROFILE%\.cache\opencode` 3. Uruchom ponownie opencode Desktop. * * * ### [Napraw problemy z połączeniem z serwerem](https://opencode.ai/docs/pl/troubleshooting#napraw-problemy-z-po%C5%82%C4%85czeniem-z-serwerem) opencode Desktop może uruchomić własny serwer lokalny (domyślnie) lub połączyć się ze skonfigurowanym adresem URL serwera. Jeśli zobaczysz okno dialogowe **„Połączenie nie powiodło się”** (lub aplikacja nigdy nie wychodzi poza ekran powitalny), sprawdź, czy jest niestandardowy adres URL serwera. #### [Wyczyść domyślny adres URL serwera na komputerze](https://opencode.ai/docs/pl/troubleshooting#wyczy%C5%9B%C4%87-domy%C5%9Blny-adres-url-serwera-na-komputerze) Na ekranie głównym kliknij nazwę serwera (z kropką stanu), aby otworzyć selektor serwerów. W sekcji **Serwer domyślny** kliknij **Wyczyść**. #### [Usuń `server.port` / `server.hostname` ze swojej konfiguracji](https://opencode.ai/docs/pl/troubleshooting#usu%C5%84-serverport--serverhostname-ze-swojej-konfiguracji) Jeśli Twój `opencode.json(c)` zawiera sekcję `server`, tymczasowo usuń ją i uruchom ponownie aplikację komputerową. #### [Sprawdź zmienne środowiskowe](https://opencode.ai/docs/pl/troubleshooting#sprawd%C5%BA-zmienne-%C5%9Brodowiskowe) Jeśli w swoim środowisku masz ustawiony `OPENCODE_PORT`, aplikacja komputerowa spróbuje użyć tego portu dla serwera lokalnego. * usuń `OPENCODE_PORT` (lub wybierz wolny port) i uruchom ponownie. * * * ### [Linux: Problemy z Wayland / X11](https://opencode.ai/docs/pl/troubleshooting#linux-problemy-z-wayland--x11) W systemie Linux, niektóre konfiguracje Wayland mogą powodować puste okna lub błędy kompozytora. * Jeśli korzystasz z Wayland, a aplikacja jest pusta/ ulega awarii, spróbuj uruchomić ją za pomocą `OC_ALLOW_WAYLAND=1`. * Jeśli to pogorszy sprawę, usuń go i zamiast tego spróbuj uruchomić w sesji X11. * * * ### [Windows: Środowisko uruchomieniowe WebView2](https://opencode.ai/docs/pl/troubleshooting#windows-%C5%9Brodowisko-uruchomieniowe-webview2) W systemie Windows opencode Desktop wymaga Microsoft Edge **WebView2 Runtime**. Jeśli aplikacja otwiera się w pustym oknie lub nie uruchamia się, zainstaluj/zaktualizuj WebView2 i spróbuj ponownie. * * * ### [Windows: Ogólne problemy z wydajnością](https://opencode.ai/docs/pl/troubleshooting#windows-og%C3%B3lne-problemy-z-wydajno%C5%9Bci%C4%85) Jeśli doświadczasz niskiej wydajności, problemów z dostępem do plików lub problemów z terminalem w systemie Windows, spróbuj użyć \[WSL (podsystem Windows dla systemu Linux) (./windows-wsl). WSL zapewnia środowisko Linux, które płynniej współpracuje z funkcjami opencode.\ \ * * *\ \ ### [Brak powiadomień](https://opencode.ai/docs/pl/troubleshooting#brak-powiadomie%C5%84)\ \ opencode Desktop pokazuje powiadomienia systemowe tylko wtedy, gdy:\ \ * powiadomienia są włączone dla opencode w ustawieniach systemu operacyjnego, oraz\ * okno aplikacji nie jest aktywne.\ \ * * *\ \ ### [Resetowanie pamięci aplikacji](https://opencode.ai/docs/pl/troubleshooting#resetowanie-pami%C4%99ci-aplikacji)\ \ Jeśli aplikacja nie uruchamia się i nie możesz wyczyścić ustawień w interfejsie użytkownika, zresetuj zapisany stan aplikacji komputerowej.\ \ 1. Zamknij całkowicie opencode Desktop.\ 2. Znajdź i usuń te pliki (znajdują się w katalogu danych aplikacji opencode Desktop):\ \ * `opencode.settings.dat` (domyślny adres URL serwera na komputerze stacjonarnym)\ * `opencode.global.dat` i `opencode.workspace.*.dat` (stan interfejsu użytkownika, taki jak najnowsze serwery/projekty)\ \ Aby szybko znaleźć katalog:\ \ * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (następnie wyszukaj nazwy plików powyżej)\ * **Linux**: wyszukaj powyższe nazwy plików pod `~/.local/share`\ * **Windows**: Naciśnij `WIN+R` -> `%APPDATA%` (następnie wyszukaj nazwy plików powyżej)\ \ * * *\ \ [Uzyskiwanie pomocy](https://opencode.ai/docs/pl/troubleshooting#uzyskiwanie-pomocy)\ \ -------------------------------------------------------------------------------------\ \ Jeśli masz problemy z opencode:\ \ 1. **Zgłoś problem na GitHub**\ \ Najlepszym sposobem zgłaszania błędów lub zgłaszania żądań funkcji jest skorzystanie z naszego repozytorium GitHub:\ \ [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues)\ \ Przed utworzeniem nowego problemu przeszukaj istniejące i sprawdź, czy Twój problem nie został już zgłoszony.\ \ 2. **Dołącz do naszego Discorda**\ \ Aby uzyskać pomoc w czasie rzeczywistym i dyskusję społeczności, dołącz do naszego serwera Discord:\ \ [**opencode.ai/discord**](https://opencode.ai/discord)\ \ \ * * *\ \ [Typowe problemy](https://opencode.ai/docs/pl/troubleshooting#typowe-problemy)\ \ -------------------------------------------------------------------------------\ \ Oto kilka typowych problemów i sposobów ich rozwiązania.\ \ * * *\ \ ### [opencode nie uruchamia się](https://opencode.ai/docs/pl/troubleshooting#opencode-nie-uruchamia-si%C4%99)\ \ 1. Sprawdź dzienniki pod kątem komunikatów o błędach\ 2. Spróbuj uruchomić z `--print-logs`, aby zobaczyć dane wyjściowe w terminalu\ 3. Upewnij się, że masz najnowszą wersję z `opencode upgrade`\ \ * * *\ \ ### [Problemy z uwierzytelnianiem](https://opencode.ai/docs/pl/troubleshooting#problemy-z-uwierzytelnianiem)\ \ 1. Spróbuj ponownie uwierzytelnić się za pomocą polecenia `/connect` w TUI\ 2. Sprawdź, czy klucze API są ważne\ 3. Upewnij się, że Twoja sieć umożliwia połączenia z interfejsem API dostawcy\ \ * * *\ \ ### [Model niedostępny](https://opencode.ai/docs/pl/troubleshooting#model-niedost%C4%99pny)\ \ 1. Sprawdź, czy dokonałeś uwierzytelnienia u dostawcy\ 2. Sprawdź, czy nazwa modelu w konfiguracji jest poprawna\ 3. Niektóre modele mogą wymagać określonego dostępu lub subskrypcji\ \ Jeśli napotkasz `ProviderModelNotFoundError`, najprawdopodobniej błędnie odwołujesz się gdzieś do modelu. Modele powinny być wskazywane w ten sposób: `/`\ \ Przykłady:\ \ * `openai/gpt-4.1`\ * `openrouter/google/gemini-2.5-flash`\ * `opencode/kimi-k2`\ \ Aby dowiedzieć się, do jakich modeli masz dostęp, uruchom `opencode models`\ \ * * *\ \ ### [ProviderInitError](https://opencode.ai/docs/pl/troubleshooting#provideriniterror)\ \ Jeśli napotkasz błąd ProviderInitError, prawdopodobnie masz nieprawidłową lub uszkodzoną konfigurację.\ \ Aby rozwiązać ten problem:\ \ 1. Najpierw sprawdź, czy Twój dostawca jest prawidłowo skonfigurowany, postępując zgodnie z [przewodnikiem dostawców](https://opencode.ai/docs/providers)\ \ 2. Jeśli problem będzie się powtarzał, spróbuj wyczyścić zapisaną konfigurację:\ \ rm -rf ~/.local/share/opencode\ \ W systemie Windows naciśnij `WIN+R` i usuń: `%USERPROFILE%\.local\share\opencode`\ \ 3. Ponownie uwierzytelnij się u swojego dostawcy za pomocą polecenia `/connect` w TUI.\ \ \ * * *\ \ ### [Błędy AI\_APICallError i problemy z pakietami dostawców](https://opencode.ai/docs/pl/troubleshooting#b%C5%82%C4%99dy-ai_apicallerror-i-problemy-z-pakietami-dostawc%C3%B3w)\ \ Jeśli napotkasz błędy wywołań API, może to wynikać z nieaktualnych pakietów dostawców. opencode dynamicznie instaluje pakiety dostawców (OpenAI, Anthropic, Google itp.) w razie potrzeby i przechowuje je lokalnie w pamięci podręcznej.\ \ Aby rozwiązać problemy z pakietem dostawcy:\ \ 1. Wyczyść pamięć podręczną pakietu dostawcy:\ \ rm -rf ~/.cache/opencode\ \ W systemie Windows naciśnij `WIN+R` i usuń: `%USERPROFILE%\.cache\opencode`\ \ 2. Uruchom ponownie kod opencode, aby ponownie zainstalować najnowsze pakiety dostawców\ \ \ Zmusi to opencode do pobrania najnowszych wersji pakietów dostawców, co często rozwiązuje problemy ze zgodnością z parametrami modelu i zmianami API.\ \ * * *\ \ ### [Kopiowanie/wklejanie nie działa na Linuxie](https://opencode.ai/docs/pl/troubleshooting#kopiowaniewklejanie-nie-dzia%C5%82a-na-linuxie)\ \ Aby funkcja kopiowania/wklejania działała, użytkownicy systemu Linux muszą mieć zainstalowane jedno z następujących narzędzi schowka:\ \ **Dla systemów X11:**\ \ apt install -y xclip# orapt install -y xsel\ \ **Dla systemów Wayland:**\ \ apt install -y wl-clipboard\ \ **Dla środowisk headless:**\ \ apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0\ \ opencode wykryje, czy używasz Waylanda i wolisz `wl-clipboard`, w przeciwnym razie spróbuje znaleźć narzędzia schowka w kolejności: `xclip` i `xsel`. --- # Tastenkombinationen | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/keybinds#_top) Tastenkombinationen =================== Passen Sie Ihre Tastenkombinationen an. OpenCode verfügt über eine Liste von Tastenkombinationen, die Sie über die OpenCode-Konfiguration anpassen können. { "$schema": "https://opencode.ai/config.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Leader Key](https://opencode.ai/docs/de/keybinds#leader-key) -------------------------------------------------------------- OpenCode verwendet für die meisten Keybinds einen `leader`\-Schlüssel. Dies vermeidet Konflikte in Ihrem Terminal. Standardmäßig ist `ctrl+x` der Leader Key und bei den meisten Aktionen müssen Sie zuerst den Leader Key und dann die Tastenkombination drücken. Um beispielsweise eine neue Sitzung zu starten, drücken Sie zuerst `ctrl+x` und dann `n`. Sie müssen für Ihre Keybinds keinen Leader Key verwenden, wir empfehlen jedoch, dies zu tun. * * * [Keybind deaktivieren](https://opencode.ai/docs/de/keybinds#keybind-deaktivieren) ---------------------------------------------------------------------------------- Sie können eine Keybind deaktivieren, indem Sie den Schlüssel mit dem Wert „none“ zu Ihrer Konfiguration hinzufügen. { "$schema": "https://opencode.ai/config.json", "keybinds": { "session_compact": "none" }} * * * [Desktop-Prompt-Shortcuts](https://opencode.ai/docs/de/keybinds#desktop-prompt-shortcuts) ------------------------------------------------------------------------------------------ Die Eingabeaufforderungseingabe der OpenCode-Desktop-App unterstützt gängige Readline/Emacs-style-Verknüpfungen zum Bearbeiten von Text. Diese sind integriert und derzeit nicht über `opencode.json` konfigurierbar. | Keybind | Aktion | | --- | --- | | `ctrl+a` | Zum Anfang der aktuellen Zeile gehen | | `ctrl+e` | Zum Ende der aktuellen Zeile gehen | | `ctrl+b` | Cursor um ein Zeichen zurückbewegen | | `ctrl+f` | Cursor um ein Zeichen vorwärts bewegen | | `alt+b` | Cursor um ein Wort zurückbewegen | | `alt+f` | Bewegen Sie den Cursor ein Wort vorwärts | | `ctrl+d` | Zeichen unter dem Cursor löschen | | `ctrl+k` | Bis zum Zeilenende löschen (Kill) | | `ctrl+u` | Bis zum Zeilenanfang löschen (Kill) | | `ctrl+w` | Vorheriges Wort löschen (Kill) | | `alt+d` | Nächstes Wort löschen (Kill) | | `ctrl+t` | Zeichen transponieren | | `ctrl+g` | Popovers abbrechen / Ausführung der Antwort abbrechen | * * * [Shift+Enter](https://opencode.ai/docs/de/keybinds#shiftenter) --------------------------------------------------------------- Einige Terminals senden standardmäßig keine Zusatztasten mit der Eingabetaste. Möglicherweise müssen Sie Ihr Terminal so konfigurieren, dass es `Shift+Enter` als Escape-Sequenz sendet. ### [Windows Terminal](https://opencode.ai/docs/de/keybinds#windows-terminal) Öffnen Sie Ihr `settings.json` unter: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Fügen Sie dies dem `actions`\-Array auf Stammebene hinzu: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Fügen Sie dies dem `keybindings`\-Array auf Stammebene hinzu:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Speichern Sie die Datei und starten Sie das Windows-Terminal neu oder öffnen Sie einen neuen Tab. --- # Skróty klawiszowe | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/keybinds#_top) Skróty klawiszowe ================= Dostosuj swoje skróty klawiszowe. OpenCode zawiera listę skrótów klawiszowych, które można dostosować za pomocą `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Klucz lidera](https://opencode.ai/docs/pl/keybinds#klucz-lidera) ------------------------------------------------------------------ opencode używa klucza `leader` dla głównych skrótów klawiszowych. Rozwiązanie problemu konfliktów w terminalu. Domyślnie `ctrl+x` jest klawiszem głównym i główną akcją wymaga najpierw naciśnięcia klawisza lidera, a następnie skrótu. Na przykład, aby ponownie zastosować, następnie następuje `ctrl+x`, a następnie następuje `n`. Nie musisz mieć klawisza wiodącego do skrótów klawiszowych, ale zalecamy to Reg. * * * [Wyłącz powiązanie klawiszy](https://opencode.ai/docs/pl/keybinds#wy%C5%82%C4%85cz-powi%C4%85zanie-klawiszy) ------------------------------------------------------------------------------------------------------------- Możesz wyłączyć skrót klawiszowy, dodając klucz do `tui.json` z wartością “none”. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Skróty monitów na pulpicie](https://opencode.ai/docs/pl/keybinds#skr%C3%B3ty-monit%C3%B3w-na-pulpicie) -------------------------------------------------------------------------------------------------------- Pole sprawdzania aplikacji komputerowej opencode obsługuje popularne skróty w stylu Readline/Emacs do edycji tekstu. Są one dostępne i obecnie nie można ich skonfigurować za pomocą `opencode.json`. | Skrót | Akcja | | --- | --- | | `ctrl+a` | Przejdź do źródła regularnej linii | | `ctrl+e` | Przejdź na koniec bieżącej linii | | `ctrl+b` | Przesuń kursor do tyłu o jeden znak | | `ctrl+f` | Przesuń kursor o jeden znak do przodu | | `alt+b` | Przesuń kursor o jedno słowo wstecz | | `alt+f` | Przesuń kursor do przodu o jedno słowo | | `ctrl+d` | Usuń znak pod kursorem | | `ctrl+k` | Zabij do końca linii | | `ctrl+u` | Zabij na początek linii | | `ctrl+w` | Zabij poprzednie słowo | | `alt+d` | Zabij następne słowo | | `ctrl+t` | Transponuj znaki | | `ctrl+g` | Anuluj wyskakujące okienka / przerwij uruchamianie odpowiedzi | * * * [Shift+Enter](https://opencode.ai/docs/pl/keybinds#shiftenter) --------------------------------------------------------------- Istnieją terminale, które nie wysyłają klawiszy modyfikujących z Enterem. Może być konieczne skonfigurowanie terminala tak, aby wysłać `Shift+Enter` jako przerwanie zakończenia. ### [Terminal Windowsowy](https://opencode.ai/docs/pl/keybinds#terminal-windowsowy) Otwórz swój `settings.json` pod adresem: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Dodaj do tablicy `actions` na poziomie wyższym: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Dodaj do tablicy `keybindings` na poziomie wyższym:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Zapisz plik i uruchom ponownie terminal Windows lub otwórz nową kartę. --- # Tastebindinger | OpenCode [Gå til indhold](https://opencode.ai/docs/da/keybinds#_top) Tastebindinger ============== Tilpas dine nøglebindinger. OpenCode har en liste over nøglebindinger, som du kan tilpasse gennem `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Ledertast](https://opencode.ai/docs/da/keybinds#ledertast) ------------------------------------------------------------ OpenCode bruger en `leader` nøgle til de fleste smagsbindinger. Dette undgår konflikter i din terminal. Som standard er `ctrl+x` ledertasten, og de fleste handlinger kræver, at du først trykker på ledertasten og derefter genvejen. For eksempel, for at starte en ny session, skal du først trykke på `ctrl+x` og derefter trykke på `n`. Du behøver ikke bruge en ledernøgle til dine nøglebindinger, men vi anbefaler at du gør det. * * * [Deaktiver tastebinding](https://opencode.ai/docs/da/keybinds#deaktiver-tastebinding) -------------------------------------------------------------------------------------- Du kan deaktivere en nøglebinding ved at tilføje nøglen til `tui.json` med værdien “none”. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Genveje til skrivebordsprompt](https://opencode.ai/docs/da/keybinds#genveje-til-skrivebordsprompt) ---------------------------------------------------------------------------------------------------- OpenCode desktop app prompt input understøtter almindelige Readline/Emacs-style genveje til redigering af tekst. Disse er indbyggede og i øjeblikket ikke konfigurerede via `opencode.json`. | Genvej | Håndtering | | --- | --- | | `ctrl+a` | Flyt til starten af ​​den aktuelle linje | | `ctrl+e` | Flyt til slutningen af ​​den aktuelle linje | | `ctrl+b` | Flyt markøren et tegn tilbage | | `ctrl+f` | Flyt markøren et tegn frem | | `alt+b` | Flyt markøren et ord tilbage | | `alt+f` | Flyt markøren et ord frem | | `ctrl+d` | Slet tegn under markøren | | `ctrl+k` | Dræb til slutningen af ​​linjen | | `ctrl+u` | Dræb til starten af ​​linjen | | `ctrl+w` | Dræb forrige ord | | `alt+d` | Dræb næste ord | | `ctrl+t` | Transponer tegn | | `ctrl+g` | Annuller popovers / afbryd kørsel af svar | * * * [Shift+Enter](https://opencode.ai/docs/da/keybinds#shiftenter) --------------------------------------------------------------- Nogle terminaler sender ikke modifikationsnøgler med Enter som standard. Du skal muligvis konfigurere din terminal til at sende `Shift+Enter` som en escape-sekvens. ### [Windows Terminal](https://opencode.ai/docs/da/keybinds#windows-terminal) Åbn din `settings.json` på: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Føj dette til `actions`\-arrayet på rodniveau: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Føj dette til `keybindings`\-arrayet på rodniveau:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Gem fil og genstart Windows Terminal eller åbn en ny fane. --- # LSP 伺服器 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/lsp#_top) LSP 伺服器 ======= OpenCode 與您的 LSP 伺服器整合。 OpenCode 與您的語言伺服器協定(LSP)整合,協助 LLM 與您的程式碼庫進行互動。它利用診斷資訊向 LLM 提供回饋。 * * * [內建支援](https://opencode.ai/docs/zh-tw/lsp#%E5%85%A7%E5%BB%BA%E6%94%AF%E6%8F%B4) -------------------------------------------------------------------------------- OpenCode 內建了多種適用於主流語言的 LSP 伺服器: | LSP 伺服器 | 副檔名 | 要求 | | --- | --- | --- | | astro | .astro | 為 Astro 專案自動安裝 | | bash | .sh, .bash, .zsh, .ksh | 自動安裝 bash-language-server | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | 為 C/C++ 專案自動安裝 | | csharp | .cs | 需要已安裝 `.NET SDK` | | clojure-lsp | .clj, .cljs, .cljc, .edn | 需要 `clojure-lsp` 指令可用 | | dart | .dart | 需要 `dart` 指令可用 | | deno | .ts, .tsx, .js, .jsx, .mjs | 需要 `deno` 指令可用(自動偵測 deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | 需要 `elixir` 指令可用 | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | 專案中需要 `eslint` 相依套件 | | fsharp | .fs, .fsi, .fsx, .fsscript | 需要已安裝 `.NET SDK` | | gleam | .gleam | 需要 `gleam` 指令可用 | | gopls | .go | 需要 `go` 指令可用 | | hls | .hs, .lhs | 需要 `haskell-language-server-wrapper` 指令可用 | | jdtls | .java | 需要已安裝 `Java SDK (version 21+)` | | julials | .jl | 需要已安裝 `julia` 和 `LanguageServer.jl` | | kotlin-ls | .kt, .kts | 為 Kotlin 專案自動安裝 | | lua-ls | .lua | 為 Lua 專案自動安裝 | | nixd | .nix | 需要 `nixd` 指令可用 | | ocaml-lsp | .ml, .mli | 需要 `ocamllsp` 指令可用 | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | 專案中需要 `oxlint` 相依套件 | | php intelephense | .php | 為 PHP 專案自動安裝 | | prisma | .prisma | 需要 `prisma` 指令可用 | | pyright | .py, .pyi | 需要已安裝 `pyright` 相依套件 | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | 需要 `ruby` 和 `gem` 指令可用 | | rust | .rs | 需要 `rust-analyzer` 指令可用 | | sourcekit-lsp | .swift, .objc, .objcpp | 需要已安裝 `swift`(macOS 上為 `xcode`) | | svelte | .svelte | 為 Svelte 專案自動安裝 | | terraform | .tf, .tfvars | 從 GitHub releases 自動安裝 | | tinymist | .typ, .typc | 從 GitHub releases 自動安裝 | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | 專案中需要 `typescript` 相依套件 | | vue | .vue | 為 Vue 專案自動安裝 | | yaml-ls | .yaml, .yml | 自動安裝 Red Hat yaml-language-server | | zls | .zig, .zon | 需要 `zig` 指令可用 | 當偵測到上述檔案副檔名且滿足相應要求時,LSP 伺服器會自動啟用。 * * * [工作原理](https://opencode.ai/docs/zh-tw/lsp#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) -------------------------------------------------------------------------------- 當 OpenCode 開啟一個檔案時,它會: 1. 將檔案副檔名與所有已啟用的 LSP 伺服器進行比對。 2. 如果對應的 LSP 伺服器尚未執行,則自動啟動它。 * * * [設定](https://opencode.ai/docs/zh-tw/lsp#%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------ 您可以透過 OpenCode 設定檔中的 `lsp` 部分來自訂 LSP 伺服器。 { "$schema": "https://opencode.ai/config.json", "lsp": {}} 每個 LSP 伺服器支援以下設定項: | 屬性 | 類型 | 描述 | | --- | --- | --- | | `disabled` | boolean | 設定為 `true` 可停用該 LSP 伺服器 | | `command` | string\[\] | 啟動 LSP 伺服器的指令 | | `extensions` | string\[\] | 該 LSP 伺服器需要處理的檔案副檔名 | | `env` | object | 啟動伺服器時設定的環境變數 | | `initialization` | object | 傳送給 LSP 伺服器的初始化選項 | 下面來看一些範例。 * * * ### [環境變數](https://opencode.ai/docs/zh-tw/lsp#%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8) 使用 `env` 屬性在啟動 LSP 伺服器時設定環境變數: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [初始化選項](https://opencode.ai/docs/zh-tw/lsp#%E5%88%9D%E5%A7%8B%E5%8C%96%E9%81%B8%E9%A0%85) 使用 `initialization` 屬性向 LSP 伺服器傳遞初始化選項。這些是在 LSP `initialize` 請求期間傳送的伺服器特定設定: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [停用 LSP 伺服器](https://opencode.ai/docs/zh-tw/lsp#%E5%81%9C%E7%94%A8-lsp-%E4%BC%BA%E6%9C%8D%E5%99%A8) 要全域停用**所有** LSP 伺服器,將 `lsp` 設定為 `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} 要停用**特定的** LSP 伺服器,將 `disabled` 設定為 `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [自訂 LSP 伺服器](https://opencode.ai/docs/zh-tw/lsp#%E8%87%AA%E8%A8%82-lsp-%E4%BC%BA%E6%9C%8D%E5%99%A8) 您可以透過指定指令和檔案副檔名來新增自訂 LSP 伺服器: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [補充資訊](https://opencode.ai/docs/zh-tw/lsp#%E8%A3%9C%E5%85%85%E8%B3%87%E8%A8%8A) -------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/zh-tw/lsp#php-intelephense) PHP Intelephense 透過授權金鑰提供進階功能。您可以將授權金鑰單獨放在以下路徑的文字檔案中: * macOS/Linux:`$HOME/intelephense/license.txt` * Windows:`%USERPROFILE%/intelephense/license.txt` 該檔案應僅包含授權金鑰,不要新增其他任何內容。 --- # LSP 서버 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/lsp#_top) LSP 서버 ====== OpenCode는 LSP 서버와 통합됩니다. OpenCode는 Language Server Protocol(LSP)과 통합되어 LLM이 코드베이스와 상호작용하도록 돕습니다. 진단 정보를 활용해 LLM에 피드백을 제공합니다. * * * [기본 제공 (Built-in)](https://opencode.ai/docs/ko/lsp#%EA%B8%B0%EB%B3%B8-%EC%A0%9C%EA%B3%B5-built-in) --------------------------------------------------------------------------------------------------- OpenCode는 널리 사용되는 언어를 위해 여러 built-in LSP 서버를 제공합니다. | LSP 서버 | 확장자 | 요구 사항 | | --- | --- | --- | | astro | .astro | Astro 프로젝트에서 자동 설치 | | bash | .sh, .bash, .zsh, .ksh | `bash-language-server` 자동 설치 | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | C/C++ 프로젝트에서 자동 설치 | | csharp | .cs | `.NET SDK` 설치됨 | | clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` 명령 사용 가능 | | dart | .dart | `dart` 명령 사용 가능 | | deno | .ts, .tsx, .js, .jsx, .mjs | `deno` 명령 사용 가능 (`deno.json`/`deno.jsonc` 자동 감지) | | elixir-ls | .ex, .exs | `elixir` 명령 사용 가능 | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | 프로젝트에 `eslint` dependency 존재 | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` 설치됨 | | gleam | .gleam | `gleam` 명령 사용 가능 | | gopls | .go | `go` 명령 사용 가능 | | hls | .hs, .lhs | `haskell-language-server-wrapper` 명령 사용 가능 | | jdtls | .java | `Java SDK (version 21+)` 설치됨 | | julials | .jl | `julia` 및 `LanguageServer.jl` 설치됨 | | kotlin-ls | .kt, .kts | Kotlin 프로젝트에서 자동 설치 | | lua-ls | .lua | Lua 프로젝트에서 자동 설치 | | nixd | .nix | `nixd` 명령 사용 가능 | | ocaml-lsp | .ml, .mli | `ocamllsp` 명령 사용 가능 | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | 프로젝트에 `oxlint` dependency 존재 | | php intelephense | .php | PHP 프로젝트에서 자동 설치 | | prisma | .prisma | `prisma` 명령 사용 가능 | | pyright | .py, .pyi | `pyright` dependency 설치됨 | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | `ruby` 및 `gem` 명령 사용 가능 | | rust | .rs | `rust-analyzer` 명령 사용 가능 | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` 설치됨 (macOS에서는 `xcode`) | | svelte | .svelte | Svelte 프로젝트에서 자동 설치 | | terraform | .tf, .tfvars | GitHub releases에서 자동 설치 | | tinymist | .typ, .typc | GitHub releases에서 자동 설치 | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | 프로젝트에 `typescript` dependency 존재 | | vue | .vue | Vue 프로젝트에서 자동 설치 | | yaml-ls | .yaml, .yml | Red Hat `yaml-language-server` 자동 설치 | | zls | .zig, .zon | `zig` 명령 사용 가능 | 위 확장자 중 하나가 감지되고 요구 사항이 충족되면 LSP 서버가 자동으로 활성화됩니다. * * * [작동 방식](https://opencode.ai/docs/ko/lsp#%EC%9E%91%EB%8F%99-%EB%B0%A9%EC%8B%9D) ------------------------------------------------------------------------------- OpenCode가 파일을 열면 다음과 같이 동작합니다. 1. 활성화된 모든 LSP 서버에 대해 파일 확장자를 확인합니다. 2. 적절한 LSP 서버가 아직 실행 중이지 않다면 시작합니다. * * * [구성](https://opencode.ai/docs/ko/lsp#%EA%B5%AC%EC%84%B1) --------------------------------------------------------- OpenCode config의 `lsp` 섹션에서 LSP 서버를 사용자 정의할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "lsp": {}} 각 LSP 서버는 다음 속성을 지원합니다. | 속성 | 타입 | 설명 | | --- | --- | --- | | `disabled` | boolean | LSP 서버를 비활성화하려면 `true`로 설정하세요 | | `command` | string\[\] | LSP 서버를 시작하는 명령입니다 | | `extensions` | string\[\] | 이 LSP 서버가 처리할 파일 확장자입니다 | | `env` | object | 서버 시작 시 설정할 환경 변수입니다 | | `initialization` | object | LSP 서버로 전송할 초기화 옵션입니다 | 예시를 살펴보겠습니다. * * * ### [환경 변수](https://opencode.ai/docs/ko/lsp#%ED%99%98%EA%B2%BD-%EB%B3%80%EC%88%98) `env` 속성을 사용하면 LSP 서버 시작 시 환경 변수를 설정할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [초기화 옵션](https://opencode.ai/docs/ko/lsp#%EC%B4%88%EA%B8%B0%ED%99%94-%EC%98%B5%EC%85%98) `initialization` 속성을 사용해 LSP 서버에 초기화 옵션을 전달하세요. 이 값은 LSP `initialize` 요청 중에 전송되는 서버별 설정입니다. { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [LSP 서버 비활성화](https://opencode.ai/docs/ko/lsp#lsp-%EC%84%9C%EB%B2%84-%EB%B9%84%ED%99%9C%EC%84%B1%ED%99%94) 전역에서 **모든** LSP 서버를 비활성화하려면 `lsp`를 `false`로 설정하세요. { "$schema": "https://opencode.ai/config.json", "lsp": false} **특정** LSP 서버를 비활성화하려면 `disabled`를 `true`로 설정하세요. { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * [사용자 정의 LSP 서버](https://opencode.ai/docs/ko/lsp#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98-lsp-%EC%84%9C%EB%B2%84) ----------------------------------------------------------------------------------------------------------------------- 명령과 파일 확장자를 지정해 사용자 정의 LSP 서버를 추가할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [추가 정보](https://opencode.ai/docs/ko/lsp#%EC%B6%94%EA%B0%80-%EC%A0%95%EB%B3%B4) ------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/ko/lsp#php-intelephense) PHP Intelephense는 라이선스 키를 통해 프리미엄 기능을 제공합니다. 텍스트 파일에 키만 저장해 라이선스 키를 제공할 수 있습니다. * macOS/Linux: `$HOME/intelephense/license.txt` * Windows: `%USERPROFILE%/intelephense/license.txt` 파일에는 추가 내용 없이 라이선스 키만 포함하는 것이 좋습니다. --- # LSP 服务器 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/lsp#_top) LSP 服务器 ======= OpenCode 与你的 LSP 服务器集成。 OpenCode 与你的语言服务器协议(LSP)集成,帮助 LLM 与你的代码库进行交互。它利用诊断信息向 LLM 提供反馈。 * * * [内置支持](https://opencode.ai/docs/zh-cn/lsp#%E5%86%85%E7%BD%AE%E6%94%AF%E6%8C%81) -------------------------------------------------------------------------------- OpenCode 内置了多种适用于主流语言的 LSP 服务器: | LSP 服务器 | 扩展名 | 要求 | | --- | --- | --- | | astro | .astro | 为 Astro 项目自动安装 | | bash | .sh, .bash, .zsh, .ksh | 自动安装 bash-language-server | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | 为 C/C++ 项目自动安装 | | csharp | .cs | 需要已安装 `.NET SDK` | | clojure-lsp | .clj, .cljs, .cljc, .edn | 需要 `clojure-lsp` 命令可用 | | dart | .dart | 需要 `dart` 命令可用 | | deno | .ts, .tsx, .js, .jsx, .mjs | 需要 `deno` 命令可用(自动检测 deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | 需要 `elixir` 命令可用 | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | 项目中需要 `eslint` 依赖 | | fsharp | .fs, .fsi, .fsx, .fsscript | 需要已安装 `.NET SDK` | | gleam | .gleam | 需要 `gleam` 命令可用 | | gopls | .go | 需要 `go` 命令可用 | | hls | .hs, .lhs | 需要 `haskell-language-server-wrapper` 命令可用 | | jdtls | .java | 需要已安装 `Java SDK (version 21+)` | | julials | .jl | 需要安装 `julia` and `LanguageServer.jl` | | kotlin-ls | .kt, .kts | 为 Kotlin 项目自动安装 | | lua-ls | .lua | 为 Lua 项目自动安装 | | nixd | .nix | 需要 `nixd` 命令可用 | | ocaml-lsp | .ml, .mli | 需要 `ocamllsp` 命令可用 | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | 项目中需要 `oxlint` 依赖 | | php intelephense | .php | 为 PHP 项目自动安装 | | prisma | .prisma | 需要 `prisma` 命令可用 | | pyright | .py, .pyi | 需要已安装 `pyright` 依赖 | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | 需要 `ruby` 和 `gem` 命令可用 | | rust | .rs | 需要 `rust-analyzer` 命令可用 | | sourcekit-lsp | .swift, .objc, .objcpp | 需要已安装 `swift`(macOS 上为 `xcode`) | | svelte | .svelte | 为 Svelte 项目自动安装 | | terraform | .tf, .tfvars | 从 GitHub releases 自动安装 | | tinymist | .typ, .typc | 从 GitHub releases 自动安装 | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | 项目中需要 `typescript` 依赖 | | vue | .vue | 为 Vue 项目自动安装 | | yaml-ls | .yaml, .yml | 自动安装 Red Hat yaml-language-server | | zls | .zig, .zon | 需要 `zig` 命令可用 | 当检测到上述文件扩展名且满足相应要求时,LSP 服务器会自动启用。 * * * [工作原理](https://opencode.ai/docs/zh-cn/lsp#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86) -------------------------------------------------------------------------------- 当 opencode 打开一个文件时,它会: 1. 将文件扩展名与所有已启用的 LSP 服务器进行匹配。 2. 如果对应的 LSP 服务器尚未运行,则自动启动它。 * * * [配置](https://opencode.ai/docs/zh-cn/lsp#%E9%85%8D%E7%BD%AE) ------------------------------------------------------------ 你可以通过 opencode 配置文件中的 `lsp` 部分来自定义 LSP 服务器。 { "$schema": "https://opencode.ai/config.json", "lsp": {}} 每个 LSP 服务器支持以下配置项: | 属性 | 类型 | 描述 | | --- | --- | --- | | `disabled` | boolean | 设置为 `true` 可禁用该 LSP 服务器 | | `command` | string\[\] | 启动 LSP 服务器的命令 | | `extensions` | string\[\] | 该 LSP 服务器需要处理的文件扩展名 | | `env` | object | 启动服务器时设置的环境变量 | | `initialization` | object | 发送给 LSP 服务器的初始化选项 | 下面来看一些示例。 * * * ### [环境变量](https://opencode.ai/docs/zh-cn/lsp#%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F) 使用 `env` 属性在启动 LSP 服务器时设置环境变量: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [初始化选项](https://opencode.ai/docs/zh-cn/lsp#%E5%88%9D%E5%A7%8B%E5%8C%96%E9%80%89%E9%A1%B9) 使用 `initialization` 属性向 LSP 服务器传递初始化选项。这些是在 LSP `initialize` 请求期间发送的服务器特定设置: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [禁用 LSP 服务器](https://opencode.ai/docs/zh-cn/lsp#%E7%A6%81%E7%94%A8-lsp-%E6%9C%8D%E5%8A%A1%E5%99%A8) 要全局禁用**所有** LSP 服务器,将 `lsp` 设置为 `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} 要禁用**特定的** LSP 服务器,将 `disabled` 设置为 `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [自定义 LSP 服务器](https://opencode.ai/docs/zh-cn/lsp#%E8%87%AA%E5%AE%9A%E4%B9%89-lsp-%E6%9C%8D%E5%8A%A1%E5%99%A8) 你可以通过指定命令和文件扩展名来添加自定义 LSP 服务器: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [补充信息](https://opencode.ai/docs/zh-cn/lsp#%E8%A1%A5%E5%85%85%E4%BF%A1%E6%81%AF) -------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/zh-cn/lsp#php-intelephense) PHP Intelephense 通过许可证密钥提供高级功能。你可以将许可证密钥单独放在以下路径的文本文件中: * macOS/Linux:`$HOME/intelephense/license.txt` * Windows:`%USERPROFILE%/intelephense/license.txt` 该文件应仅包含许可证密钥,不要添加其他任何内容。 --- # Server LSP | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/lsp#_top) Server LSP ========== OpenCode si integra con i tuoi server LSP. OpenCode si integra con il tuo Language Server Protocol (LSP) per aiutare l’LLM a interagire con la tua codebase. Usa le diagnostiche per fornire feedback all’LLM. * * * [Integrati](https://opencode.ai/docs/it/lsp#integrati) ------------------------------------------------------- OpenCode include diversi server LSP integrati per linguaggi popolari: | Server LSP | Estensioni | Requisiti | | --- | --- | --- | | astro | .astro | Installazione automatica per progetti Astro | | bash | .sh, .bash, .zsh, .ksh | Installazione automatica di bash-language-server | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Installazione automatica per progetti C/C++ | | csharp | .cs | `.NET SDK` installato | | clojure-lsp | .clj, .cljs, .cljc, .edn | comando `clojure-lsp` disponibile | | dart | .dart | comando `dart` disponibile | | deno | .ts, .tsx, .js, .jsx, .mjs | comando `deno` disponibile (rileva automaticamente deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | comando `elixir` disponibile | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | dipendenza `eslint` nel progetto | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installato | | gleam | .gleam | comando `gleam` disponibile | | gopls | .go | comando `go` disponibile | | hls | .hs, .lhs | comando `haskell-language-server-wrapper` disponibile | | jdtls | .java | `Java SDK (version 21+)` installato | | julials | .jl | `julia` e `LanguageServer.jl` installati | | kotlin-ls | .kt, .kts | Installazione automatica per progetti Kotlin | | lua-ls | .lua | Installazione automatica per progetti Lua | | nixd | .nix | comando `nixd` disponibile | | ocaml-lsp | .ml, .mli | comando `ocamllsp` disponibile | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | dipendenza `oxlint` nel progetto | | php intelephense | .php | Installazione automatica per progetti PHP | | prisma | .prisma | comando `prisma` disponibile | | pyright | .py, .pyi | dipendenza `pyright` installata | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | comandi `ruby` e `gem` disponibili | | rust | .rs | comando `rust-analyzer` disponibile | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` installato (`xcode` su macOS) | | svelte | .svelte | Installazione automatica per progetti Svelte | | terraform | .tf, .tfvars | Installazione automatica dalle release GitHub | | tinymist | .typ, .typc | Installazione automatica dalle release GitHub | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | dipendenza `typescript` nel progetto | | vue | .vue | Installazione automatica per progetti Vue | | yaml-ls | .yaml, .yml | Installazione automatica di Red Hat yaml-language-server | | zls | .zig, .zon | comando `zig` disponibile | I server LSP vengono abilitati automaticamente quando viene rilevata una delle estensioni qui sopra e i requisiti sono soddisfatti. * * * [Come funziona](https://opencode.ai/docs/it/lsp#come-funziona) --------------------------------------------------------------- Quando opencode apre un file: 1. Controlla l’estensione del file rispetto a tutti i server LSP abilitati. 2. Avvia il server LSP appropriato se non e gia in esecuzione. * * * [Configura](https://opencode.ai/docs/it/lsp#configura) ------------------------------------------------------- Puoi personalizzare i server LSP tramite la sezione `lsp` nella configurazione di opencode. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Ogni server LSP supporta i seguenti campi: | Proprieta | Tipo | Descrizione | | --- | --- | --- | | `disabled` | boolean | Imposta a `true` per disabilitare il server LSP | | `command` | string\[\] | Il comando per avviare il server LSP | | `extensions` | string\[\] | Estensioni file gestite da questo server LSP | | `env` | object | Variabili d’ambiente da impostare all’avvio | | `initialization` | object | Opzioni di inizializzazione da inviare al server | Vediamo alcuni esempi. * * * ### [Variabili d’ambiente](https://opencode.ai/docs/it/lsp#variabili-dambiente) Usa la proprieta `env` per impostare variabili d’ambiente quando avvii il server LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Opzioni di inizializzazione](https://opencode.ai/docs/it/lsp#opzioni-di-inizializzazione) Usa la proprieta `initialization` per passare opzioni di inizializzazione al server LSP. Sono impostazioni specifiche del server inviate durante la richiesta LSP `initialize`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Disabilitare i server LSP](https://opencode.ai/docs/it/lsp#disabilitare-i-server-lsp) Per disabilitare **tutti** i server LSP globalmente, imposta `lsp` a `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} Per disabilitare un server LSP **specifico**, imposta `disabled` a `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Server LSP personalizzati](https://opencode.ai/docs/it/lsp#server-lsp-personalizzati) Puoi aggiungere server LSP personalizzati specificando il comando e le estensioni file: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Informazioni aggiuntive](https://opencode.ai/docs/it/lsp#informazioni-aggiuntive) ----------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/it/lsp#php-intelephense) PHP Intelephense offre funzionalita premium tramite una chiave di licenza. Puoi fornire la chiave inserendo (solo) la chiave in un file di testo in: * Su macOS/Linux: `$HOME/intelephense/license.txt` * Su Windows: `%USERPROFILE%/intelephense/license.txt` Il file deve contenere solo la chiave di licenza, senza contenuti aggiuntivi. --- # TUI | OpenCode [Skip to content](https://opencode.ai/docs/th/tui#_top) TUI === การใช้อินเทอร์เฟซผู้ใช้ terminal OpenCode OpenCode มีอินเทอร์เฟซ terminal แบบโต้ตอบหรือ TUI สำหรับการทำงานในโครงการของคุณด้วย LLM การรัน OpenCode จะเริ่มต้น TUI สำหรับไดเร็กทอรีปัจจุบัน opencode หรือคุณสามารถเริ่มต้นสำหรับไดเร็กทอรีการทำงานเฉพาะได้ opencode /path/to/project เมื่อคุณอยู่ใน TUI แล้ว คุณสามารถแจ้งด้วยข้อความได้ Give me a quick summary of the codebase. * * * [การอ้างอิงไฟล์](https://opencode.ai/docs/th/tui#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AD%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B8%AD%E0%B8%B4%E0%B8%87%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- คุณสามารถอ้างอิงไฟล์ในข้อความของคุณโดยใช้ `@` นี่เป็นการค้นหาไฟล์ที่ไม่ชัดเจนในไดเร็กทอรีการทำงานปัจจุบัน How is auth handled in @packages/functions/src/api/index.ts? เนื้อหาของไฟล์จะถูกเพิ่มในการสนทนาโดยอัตโนมัติ * * * [คำสั่ง Bash](https://opencode.ai/docs/th/tui#%E0%B8%84%E0%B8%B3%E0%B8%AA%E0%B8%B1%E0%B9%88%E0%B8%87-bash) ----------------------------------------------------------------------------------------------------------- เริ่มข้อความด้วย `!` เพื่อรันคำสั่ง shell !ls -la ผลลัพธ์ของคำสั่งจะถูกเพิ่มเข้าไปในการสนทนาซึ่งเป็นผลลัพธ์ของเครื่องมือ * * * [คำสั่ง](https://opencode.ai/docs/th/tui#%E0%B8%84%E0%B8%B3%E0%B8%AA%E0%B8%B1%E0%B9%88%E0%B8%87) ------------------------------------------------------------------------------------------------- เมื่อใช้ OpenCode TUI คุณสามารถพิมพ์ `/` ตามด้วยชื่อคำสั่งเพื่อดำเนินการอย่างรวดเร็ว ตัวอย่างเช่น: /help คำสั่งส่วนใหญ่ยังมีการผูกคีย์โดยใช้ `ctrl+x` เป็นคีย์ผู้นำ โดยที่ `ctrl+x` เป็นคีย์ผู้นำเริ่มต้น [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/keybinds) นี่คือคำสั่งสแลชที่ใช้ได้ทั้งหมด: * * * ### [connect](https://opencode.ai/docs/th/tui#connect) เพิ่มผู้ให้บริการให้กับ OpenCode ให้คุณเลือกจากผู้ให้บริการที่มีอยู่และเพิ่มคีย์ API /connect * * * ### [compact](https://opencode.ai/docs/th/tui#compact) กระชับเซสชันปัจจุบัน _นามแฝง_: `/summarize` /compact **ผูกปุ่ม:** `ctrl+x c` * * * ### [details](https://opencode.ai/docs/th/tui#details) สลับรายละเอียดการดำเนินการของเครื่องมือ /details **ผูกปุ่ม:** `ctrl+x d` * * * ### [editor](https://opencode.ai/docs/th/tui#editor) เปิดตัวแก้ไขภายนอกเพื่อเขียนข้อความ ใช้ตัวแก้ไขที่ตั้งค่าไว้ในตัวแปรสภาพแวดล้อม `EDITOR` ของคุณ [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/th/tui#editor-setup) /editor **ผูกปุ่ม:** `ctrl+x e` * * * ### [exit](https://opencode.ai/docs/th/tui#exit) ออกจาก OpenCode _นามแฝง_: `/quit`, `/q` /exit **ผูกปุ่ม:** `ctrl+x q` * * * ### [export](https://opencode.ai/docs/th/tui#export) ส่งออกการสนทนาปัจจุบันไปยัง Markdown และเปิดในตัวแก้ไขเริ่มต้นของคุณ ใช้ตัวแก้ไขที่ตั้งค่าไว้ในตัวแปรสภาพแวดล้อม `EDITOR` ของคุณ [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/th/tui#editor-setup) /export **ผูกปุ่ม:** `ctrl+x x` * * * ### [help](https://opencode.ai/docs/th/tui#help) แสดงกล่องโต้ตอบความช่วยเหลือ /help **ผูกปุ่ม:** `ctrl+x h` * * * ### [init](https://opencode.ai/docs/th/tui#init) สร้างหรืออัปเดตไฟล์ `AGENTS.md` [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/rules) /init **ผูกปุ่ม:** `ctrl+x i` * * * ### [models](https://opencode.ai/docs/th/tui#models) รายการรุ่นที่มีจำหน่าย /models **ผูกปุ่ม:** `ctrl+x m` * * * ### [new](https://opencode.ai/docs/th/tui#new) เริ่มเซสชันใหม่ _นามแฝง_: `/clear` /new **ผูกปุ่ม:** `ctrl+x n` * * * ### [redo](https://opencode.ai/docs/th/tui#redo) ทำซ้ำข้อความที่เลิกทำก่อนหน้านี้ ใช้ได้หลังจากใช้ `/undo` เท่านั้น ภายในจะใช้ Git เพื่อจัดการการเปลี่ยนแปลงไฟล์ ดังนั้นโครงการของคุณ **จำเป็นต้อง เป็นที่เก็บ Git** /redo **ผูกปุ่ม:** `ctrl+x r` * * * ### [sessions](https://opencode.ai/docs/th/tui#sessions) รายการและสลับระหว่างเซสชัน _นามแฝง_: `/resume`, `/continue` /sessions **ผูกปุ่ม:** `ctrl+x l` * * * แบ่งปันเซสชั่นปัจจุบัน [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/share) /share **ผูกปุ่ม:** `ctrl+x s` * * * ### [themes](https://opencode.ai/docs/th/tui#themes) แสดงรายการธีมที่มีอยู่ /themes **ผูกปุ่ม:** `ctrl+x t` * * * ### [thinking](https://opencode.ai/docs/th/tui#thinking) สลับการเปิดเผยการบล็อก thinking/reasoning ในการสนทนา เมื่อเปิดใช้งาน คุณสามารถดูกระบวนการให้เหตุผลของแบบจำลองสำหรับแบบจำลองที่รองรับการคิดแบบขยาย /thinking * * * ### [undo](https://opencode.ai/docs/th/tui#undo) เลิกทำข้อความสุดท้ายในการสนทนา ลบข้อความผู้ใช้ล่าสุด การตอบกลับที่ตามมาทั้งหมด และการเปลี่ยนแปลงไฟล์ใดๆ ภายในจะใช้ Git เพื่อจัดการการเปลี่ยนแปลงไฟล์ ดังนั้นโครงการของคุณ **จำเป็นต้อง เป็นที่เก็บ Git** /undo **ผูกปุ่ม:** `ctrl+x u` * * * ### [unshare](https://opencode.ai/docs/th/tui#unshare) ยกเลิกการแชร์เซสชันปัจจุบัน [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/share#un-sharing) /unshare * * * [การตั้งค่าตัวแก้ไข](https://opencode.ai/docs/th/tui#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87%E0%B8%84%E0%B9%88%E0%B8%B2%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%81%E0%B9%89%E0%B9%84%E0%B8%82) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ทั้งคำสั่ง `/editor` และ `/export` ใช้ตัวแก้ไขที่ระบุในตัวแปรสภาพแวดล้อม `EDITOR` ของคุณ * [Linux/macOS](https://opencode.ai/docs/th/tui#tab-panel-102) * [Windows (CMD)](https://opencode.ai/docs/th/tui#tab-panel-103) * [Windows (PowerShell)](https://opencode.ai/docs/th/tui#tab-panel-104) # Example for nano or vimexport EDITOR=nanoexport EDITOR=vim # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitexport EDITOR="code --wait" หากต้องการทำให้เป็นแบบถาวร ให้เพิ่มสิ่งนี้ลงในโปรไฟล์ shell ของคุณ `~/.bashrc`, `~/.zshrc` ฯลฯ set EDITOR=notepad # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --waitset EDITOR=code --wait หากต้องการทำให้เป็นแบบถาวร ให้ใช้ **คุณสมบัติของระบบ** > **สภาพแวดล้อม ตัวแปร**. $env:EDITOR = "notepad" # For GUI editors, VS Code, Cursor, VSCodium, Windsurf, Zed, etc.# include --wait$env:EDITOR = "code --wait" หากต้องการทำให้เป็นแบบถาวร ให้เพิ่มสิ่งนี้ลงในโปรไฟล์ PowerShell ของคุณ ตัวเลือกตัวแก้ไขยอดนิยม ได้แก่ : * `code` - ​​รหัส Visual Studio * `cursor` - ​​เคอร์เซอร์ * `windsurf` - ​​วินด์เซิร์ฟ * `nvim` - ​​บรรณาธิการ Neovim * `vim` - ​​โปรแกรมแก้ไขเป็นกลุ่ม * `nano` - ​​โปรแกรมแก้ไขนาโน * `notepad` - ​​สมุดบันทึกของ Windows * `subl` - ​​ข้อความประเสริฐ ผู้แก้ไขบางรายจำเป็นต้องมีอาร์กิวเมนต์บรรทัดคำสั่งเพื่อทำงานในโหมดการบล็อก แฟล็ก `--wait` ทำให้กระบวนการแก้ไขบล็อกจนกว่าจะปิด * * * [กำหนดค่า](https://opencode.ai/docs/th/tui#%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2) --------------------------------------------------------------------------------------------------------------------- คุณสามารถปรับแต่งพฤติกรรม TUI ได้ผ่าน `tui.json` (หรือ `tui.jsonc`) { "$schema": "https://opencode.ai/tui.json", "theme": "opencode", "keybinds": { "leader": "ctrl+x" }, "scroll_speed": 3, "scroll_acceleration": { "enabled": true }, "diff_style": "auto"} สิ่งนี้แยกจาก `opencode.json` ซึ่งกำหนดค่าพฤติกรรมเซิร์ฟเวอร์/รันไทม์ ### [ตัวเลือก](https://opencode.ai/docs/th/tui#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81) * `theme` - ตั้งค่าธีม UI ของคุณ [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/themes) * `keybinds` - ปรับแต่งแป้นพิมพ์ลัด [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/keybinds) * `scroll_acceleration.enabled` - ​​เปิดใช้งานการเร่งความเร็วการเลื่อนแบบ macOS เพื่อการเลื่อนที่ราบรื่นและเป็นธรรมชาติ เมื่อเปิดใช้งาน ความเร็วในการเลื่อนจะเพิ่มขึ้นตามท่าทางการเลื่อนอย่างรวดเร็ว และคงความแม่นยำไว้สำหรับการเคลื่อนไหวที่ช้าลง **การตั้งค่านี้มีความสำคัญมากกว่า `scroll_speed` และแทนที่เมื่อเปิดใช้งาน** * `scroll_speed` - ​​ควบคุมความเร็วของการเลื่อน TUI เมื่อใช้คำสั่งการเลื่อน (ขั้นต่ำ: `0.001` รองรับค่าทศนิยม) ค่าเริ่มต้นเป็น `3` **หมายเหตุ: สิ่งนี้จะถูกละเว้นหากตั้งค่า `scroll_acceleration.enabled` เป็น `true`.** * `diff_style` - ควบคุมการเรนเดอร์ diff `"auto"` ปรับให้เข้ากับความกว้างของ terminal `"stacked"` จะแสดงคอลัมน์เดียวเสมอ ใช้ `OPENCODE_TUI_CONFIG` เพื่อโหลดเส้นทางการกำหนดค่า TUI แบบกำหนดเอง * * * [การปรับแต่ง](https://opencode.ai/docs/th/tui#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9B%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B9%81%E0%B8%95%E0%B9%88%E0%B8%87) --------------------------------------------------------------------------------------------------------------------------------------------------- คุณสามารถปรับแต่งแง่มุมต่างๆ ของมุมมอง TUI ได้โดยใช้ชุดคำสั่ง (`ctrl+x h` หรือ `/help`) การตั้งค่าเหล่านี้ยังคงมีอยู่ตลอดการรีสตาร์ท * * * #### [การแสดงชื่อผู้ใช้](https://opencode.ai/docs/th/tui#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%81%E0%B8%AA%E0%B8%94%E0%B8%87%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%9C%E0%B8%B9%E0%B9%89%E0%B9%83%E0%B8%8A%E0%B9%89) สลับว่าจะให้ชื่อผู้ใช้ของคุณปรากฏในข้อความแชทหรือไม่ เข้าถึงสิ่งนี้ผ่าน: * Command Palette: ค้นหา “ชื่อผู้ใช้” หรือ “ซ่อนชื่อผู้ใช้” * การตั้งค่าจะคงอยู่โดยอัตโนมัติและจะถูกจดจำตลอดเซสชัน TUI --- # 疑難排解 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/troubleshooting#_top) 疑難排解 ==== 常見問題及其解決方法。 要偵錯 OpenCode 的問題,請先檢查其儲存在磁碟上的日誌和本地資料。 * * * [日誌](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%97%A5%E8%AA%8C) ------------------------------------------------------------------------ 日誌檔案寫入位置: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: 按 `WIN+R` 並貼上 `%USERPROFILE%\.local\share\opencode\log` 日誌檔案以時間戳記命名(例如 `2025-01-09T123456.log`),並保留最近的 10 個日誌檔案。 你可以透過 `--log-level` 命令列選項設定日誌等級以取得更詳細的偵錯資訊。例如:`opencode --log-level DEBUG`。 * * * [儲存](https://opencode.ai/docs/zh-tw/troubleshooting#%E5%84%B2%E5%AD%98) ------------------------------------------------------------------------ OpenCode 將工作階段資料和其他應用程式資料儲存在磁碟上: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: 按 `WIN+R` 並貼上 `%USERPROFILE%\.local\share\opencode` 該目錄包含: * `auth.json` - 身分驗證資料,如 API 金鑰、OAuth Token * `log/` - 應用程式日誌 * `project/` - 專案特定資料,如工作階段和訊息資料 * 如果專案位於 Git 儲存庫中,則儲存在 `.//storage/` * 如果不是 Git 儲存庫,則儲存在 `./global/storage/` * * * [桌面應用程式](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%A1%8C%E9%9D%A2%E6%87%89%E7%94%A8%E7%A8%8B%E5%BC%8F) ---------------------------------------------------------------------------------------------------------------- OpenCode Desktop 會在背景執行一個本地 OpenCode 伺服器(即 `opencode-cli` 附屬程序)。大多數問題是由外掛異常、快取損壞或錯誤的伺服器設定引起的。 ### [快速檢查](https://opencode.ai/docs/zh-tw/troubleshooting#%E5%BF%AB%E9%80%9F%E6%AA%A2%E6%9F%A5) * 完全退出並重新啟動應用程式。 * 如果應用程式顯示錯誤頁面,請點擊**重新啟動**並複製錯誤詳情。 * 僅限 macOS:`OpenCode` 選單 -> **Reload Webview**(當 UI 空白或凍結時有效)。 * * * ### [停用外掛](https://opencode.ai/docs/zh-tw/troubleshooting#%E5%81%9C%E7%94%A8%E5%A4%96%E6%8E%9B) 如果桌面應用程式在啟動時當機、卡住或行為異常,請先停用外掛。 #### [檢查全域設定](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%AA%A2%E6%9F%A5%E5%85%A8%E5%9F%9F%E8%A8%AD%E5%AE%9A) 開啟你的全域設定檔,查找 `plugin` 鍵。 * **macOS/Linux**: `~/.config/opencode/opencode.jsonc`(或 `~/.config/opencode/opencode.json`) * **macOS/Linux**(舊版安裝): `~/.local/share/opencode/opencode.jsonc` * **Windows**: 按 `WIN+R` 並貼上 `%USERPROFILE%\.config\opencode\opencode.jsonc` 如果你設定了外掛,請透過移除該鍵或將其設定為空陣列來暫時停用它們: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [檢查外掛目錄](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%AA%A2%E6%9F%A5%E5%A4%96%E6%8E%9B%E7%9B%AE%E9%8C%84) OpenCode 還可以從磁碟載入本地外掛。暫時將這些外掛移走(或重新命名資料夾),然後重新啟動桌面應用程式: * **全域外掛** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: 按 `WIN+R` 並貼上 `%USERPROFILE%\.config\opencode\plugins` * **專案外掛**(僅當你使用了專案級設定時) * `/.opencode/plugins/` 如果應用程式恢復正常,請逐個重新啟用外掛,找出導致問題的那個。 * * * ### [清除快取](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%B8%85%E9%99%A4%E5%BF%AB%E5%8F%96) 如果停用外掛沒有幫助(或外掛安裝卡住了),請清除快取以便 OpenCode 重新建置。 1. 完全退出 OpenCode Desktop。 2. 刪除快取目錄: * **macOS**: Finder -> `Cmd+Shift+G` -> 貼上 `~/.cache/opencode` * **Linux**: 刪除 `~/.cache/opencode`(或執行 `rm -rf ~/.cache/opencode`) * **Windows**: 按 `WIN+R` 並貼上 `%USERPROFILE%\.cache\opencode` 3. 重新啟動 OpenCode Desktop。 * * * ### [修復伺服器連線問題](https://opencode.ai/docs/zh-tw/troubleshooting#%E4%BF%AE%E5%BE%A9%E4%BC%BA%E6%9C%8D%E5%99%A8%E9%80%A3%E7%B7%9A%E5%95%8F%E9%A1%8C) OpenCode Desktop 可以啟動自己的本地伺服器(預設行為),也可以連線到你設定的伺服器 URL。 如果你看到\*\*「Connection Failed」\*\*對話框(或應用程式始終停留在啟動畫面),請檢查自訂伺服器 URL。 #### [清除桌面預設伺服器 URL](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%B8%85%E9%99%A4%E6%A1%8C%E9%9D%A2%E9%A0%90%E8%A8%AD%E4%BC%BA%E6%9C%8D%E5%99%A8-url) 在主頁面上,點擊伺服器名稱(帶有狀態指示點)以開啟伺服器選擇器。在**預設伺服器**部分,點擊**清除**。 #### [從設定中移除 `server.port` / `server.hostname`](https://opencode.ai/docs/zh-tw/troubleshooting#%E5%BE%9E%E8%A8%AD%E5%AE%9A%E4%B8%AD%E7%A7%BB%E9%99%A4-serverport--serverhostname) 如果你的 `opencode.json(c)` 包含 `server` 部分,請暫時移除該部分並重新啟動桌面應用程式。 #### [檢查環境變數](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%AA%A2%E6%9F%A5%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8) 如果你在環境中設定了 `OPENCODE_PORT`,桌面應用程式將嘗試使用該連接埠作為本地伺服器連接埠。 * 取消設定 `OPENCODE_PORT`(或選擇一個空閒連接埠)並重新啟動。 * * * ### [Linux: Wayland / X11 問題](https://opencode.ai/docs/zh-tw/troubleshooting#linux-wayland--x11-%E5%95%8F%E9%A1%8C) 在 Linux 上,某些 Wayland 設定可能會導致視窗空白或合成器錯誤。 * 如果你使用 Wayland 且應用程式出現空白或當機,請嘗試使用 `OC_ALLOW_WAYLAND=1` 啟動。 * 如果情況變得更糟,請移除該設定並嘗試在 X11 工作階段下啟動。 * * * ### [Windows: WebView2 執行階段](https://opencode.ai/docs/zh-tw/troubleshooting#windows-webview2-%E5%9F%B7%E8%A1%8C%E9%9A%8E%E6%AE%B5) 在 Windows 上,OpenCode Desktop 需要 Microsoft Edge **WebView2 Runtime**。如果應用程式開啟後是空白視窗或無法啟動,請安裝或更新 WebView2 後重試。 * * * ### [Windows: 常見效能問題](https://opencode.ai/docs/zh-tw/troubleshooting#windows-%E5%B8%B8%E8%A6%8B%E6%95%88%E8%83%BD%E5%95%8F%E9%A1%8C) 如果你在 Windows 上遇到效能緩慢、檔案存取問題或終端機問題,請嘗試使用 [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) 。WSL 提供了一個 Linux 環境,能更好地與 OpenCode 的功能相容。 * * * ### [通知不顯示](https://opencode.ai/docs/zh-tw/troubleshooting#%E9%80%9A%E7%9F%A5%E4%B8%8D%E9%A1%AF%E7%A4%BA) OpenCode Desktop 僅在以下情況下顯示系統通知: * 在作業系統設定中已為 OpenCode 啟用通知,且 * 應用程式視窗未處於焦點狀態。 * * * ### [重設桌面應用程式儲存(最後手段)](https://opencode.ai/docs/zh-tw/troubleshooting#%E9%87%8D%E8%A8%AD%E6%A1%8C%E9%9D%A2%E6%87%89%E7%94%A8%E7%A8%8B%E5%BC%8F%E5%84%B2%E5%AD%98%E6%9C%80%E5%BE%8C%E6%89%8B%E6%AE%B5) 如果應用程式無法啟動且你無法從 UI 內部清除設定,請重設桌面應用程式的儲存狀態。 1. 退出 OpenCode Desktop。 2. 找到並刪除以下檔案(它們位於 OpenCode Desktop 應用程式資料目錄中): * `opencode.settings.dat`(桌面預設伺服器 URL) * `opencode.global.dat` 和 `opencode.workspace.*.dat`(UI 狀態,如最近的伺服器/專案) 快速找到該目錄: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support`(然後搜尋上述檔案名稱) * **Linux**: 在 `~/.local/share` 下搜尋上述檔案名稱 * **Windows**: 按 `WIN+R` -> `%APPDATA%`(然後搜尋上述檔案名稱) * * * [取得幫助](https://opencode.ai/docs/zh-tw/troubleshooting#%E5%8F%96%E5%BE%97%E5%B9%AB%E5%8A%A9) -------------------------------------------------------------------------------------------- 如果你遇到 OpenCode 的問題: 1. **在 GitHub 上回報問題** 回報 Bug 或請求功能的最佳方式是透過我們的 GitHub 儲存庫: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) 在建立新 Issue 之前,請先搜尋已有的 Issue,看看你的問題是否已被回報。 2. **加入我們的 Discord** 如需即時幫助和社群討論,請加入我們的 Discord 伺服器: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [常見問題](https://opencode.ai/docs/zh-tw/troubleshooting#%E5%B8%B8%E8%A6%8B%E5%95%8F%E9%A1%8C) -------------------------------------------------------------------------------------------- 以下是一些常見問題及其解決方法。 * * * ### [OpenCode 無法啟動](https://opencode.ai/docs/zh-tw/troubleshooting#opencode-%E7%84%A1%E6%B3%95%E5%95%9F%E5%8B%95) 1. 檢查日誌中的錯誤訊息 2. 嘗試使用 `--print-logs` 執行以在終端機中查看輸出 3. 使用 `opencode upgrade` 確保你使用的是最新版本 * * * ### [身分驗證問題](https://opencode.ai/docs/zh-tw/troubleshooting#%E8%BA%AB%E5%88%86%E9%A9%97%E8%AD%89%E5%95%8F%E9%A1%8C) 1. 嘗試在 TUI 中使用 `/connect` 指令重新進行身分驗證 2. 檢查你的 API 金鑰是否有效 3. 確保你的網路允許連線到供應商的 API * * * ### [模型不可用](https://opencode.ai/docs/zh-tw/troubleshooting#%E6%A8%A1%E5%9E%8B%E4%B8%8D%E5%8F%AF%E7%94%A8) 1. 檢查你是否已通過供應商的身分驗證 2. 驗證設定中的模型名稱是否正確 3. 某些模型可能需要特定的存取權限或訂閱 如果你遇到 `ProviderModelNotFoundError`,很可能是在某處錯誤地參考了模型。 模型應按如下方式參考:`/` 範例: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` 要查看你有權存取哪些模型,請執行 `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/zh-tw/troubleshooting#provideriniterror) 如果你遇到 ProviderInitError,很可能是設定無效或已損壞。 要解決此問題: 1. 首先,按照[供應商指南](https://opencode.ai/docs/providers) 驗證你的供應商是否已正確設定 2. 如果問題仍然存在,請嘗試清除已儲存的設定: rm -rf ~/.local/share/opencode 在 Windows 上,按 `WIN+R` 並刪除:`%USERPROFILE%\.local\share\opencode` 3. 在 TUI 中使用 `/connect` 指令重新與供應商進行身分驗證。 * * * ### [AI\_APICallError 和供應商套件問題](https://opencode.ai/docs/zh-tw/troubleshooting#ai_apicallerror-%E5%92%8C%E4%BE%9B%E6%87%89%E5%95%86%E5%A5%97%E4%BB%B6%E5%95%8F%E9%A1%8C) 如果你遇到 API 呼叫錯誤,可能是由於供應商套件過期導致的。OpenCode 會根據需要動態安裝供應商套件(OpenAI、Anthropic、Google 等)並將它們快取到本地。 要解決供應商套件問題: 1. 清除供應商套件快取: rm -rf ~/.cache/opencode 在 Windows 上,按 `WIN+R` 並刪除:`%USERPROFILE%\.cache\opencode` 2. 重新啟動 OpenCode 以重新安裝最新的供應商套件 這將強制 OpenCode 下載最新版本的供應商套件,通常可以解決模型參數和 API 變更帶來的相容性問題。 * * * ### [在 Linux 上複製/貼上不可用](https://opencode.ai/docs/zh-tw/troubleshooting#%E5%9C%A8-linux-%E4%B8%8A%E8%A4%87%E8%A3%BD%E8%B2%BC%E4%B8%8A%E4%B8%8D%E5%8F%AF%E7%94%A8) Linux 使用者需要安裝以下剪貼簿工具之一,複製/貼上功能才能正常運作: **對於 X11 系統:** apt install -y xclip# orapt install -y xsel **對於 Wayland 系統:** apt install -y wl-clipboard **對於無頭環境:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 OpenCode 會偵測你是否正在使用 Wayland 並優先使用 `wl-clipboard`,否則將按以下順序嘗試查找剪貼簿工具:`xclip` 和 `xsel`。 --- # การแก้ไขปัญหา | OpenCode [Skip to content](https://opencode.ai/docs/th/troubleshooting#_top) การแก้ไขปัญหา ============= ปัญหาทั่วไปและวิธีแก้ปัญหา หากต้องการแก้ไขข้อบกพร่องเกี่ยวกับ OpenCode ให้เริ่มต้นด้วยการตรวจสอบบันทึกและข้อมูลในเครื่องที่จัดเก็บไว้ในดิสก์ * * * [บันทึก](https://opencode.ai/docs/th/troubleshooting#%E0%B8%9A%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B6%E0%B8%81) ------------------------------------------------------------------------------------------------------------- ไฟล์บันทึกถูกเขียนไปที่: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.local\share\opencode\log` ไฟล์บันทึกจะถูกตั้งชื่อด้วยการประทับเวลา (เช่น `2025-01-09T123456.log`) และไฟล์บันทึกล่าสุด 10 ไฟล์จะถูกเก็บไว้ คุณสามารถตั้งค่าระดับการบันทึกด้วยตัวเลือกบรรทัดคำสั่ง `--log-level` เพื่อรับข้อมูลการแก้ไขข้อบกพร่องโดยละเอียดเพิ่มเติม ตัวอย่างเช่น `opencode --log-level DEBUG` * * * [พื้นที่จัดเก็บ](https://opencode.ai/docs/th/troubleshooting#%E0%B8%9E%E0%B8%B7%E0%B9%89%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%88%E0%B8%B1%E0%B8%94%E0%B9%80%E0%B8%81%E0%B9%87%E0%B8%9A) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- opencode เก็บข้อมูลเซสชันและข้อมูลแอปพลิเคชันอื่น ๆ ไว้บนดิสก์ที่: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.local\share\opencode` ไดเรกทอรีนี้ประกอบด้วย: * `auth.json` - ​​ข้อมูลการตรวจสอบสิทธิ์ เช่น คีย์ API, OAuth Token * `log/` - ​​บันทึกแอปพลิเคชัน * `project/` - ​​ข้อมูลเฉพาะโครงการ เช่น ข้อมูลเซสชันและข้อความ * หากโปรเจ็กต์อยู่ภายใน repo Git มันจะถูกจัดเก็บไว้ใน `.//storage/` * หากไม่ใช่ repo Git มันจะถูกเก็บไว้ใน `./global/storage/` * * * [แอปเดสก์ท็อป](https://opencode.ai/docs/th/troubleshooting#%E0%B9%81%E0%B8%AD%E0%B8%9B%E0%B9%80%E0%B8%94%E0%B8%AA%E0%B8%81%E0%B9%8C%E0%B8%97%E0%B9%87%E0%B8%AD%E0%B8%9B) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode Desktop รันเซิร์ฟเวอร์ OpenCode ในเครื่อง (ไฟล์ `opencode-cli` sidecar) ในเบื้องหลัง ปัญหาส่วนใหญ่มีสาเหตุมาจากปลั๊กอินที่ทำงานผิดปกติ แคชเสียหาย หรือการตั้งค่าเซิร์ฟเวอร์ไม่ถูกต้อง ### [การตรวจสอบอย่างรวดเร็ว](https://opencode.ai/docs/th/troubleshooting#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%95%E0%B8%A3%E0%B8%A7%E0%B8%88%E0%B8%AA%E0%B8%AD%E0%B8%9A%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B8%A3%E0%B8%A7%E0%B8%94%E0%B9%80%E0%B8%A3%E0%B9%87%E0%B8%A7) * ออกจากระบบโดยสมบูรณ์แล้วเปิดแอปใหม่อีกครั้ง * หากแอปแสดงหน้าจอข้อผิดพลาด ให้คลิก **รีสตาร์ท** และคัดลอกรายละเอียดข้อผิดพลาด * macOS เท่านั้น: เมนู `OpenCode` -> **โหลด Webview ใหม่** (ช่วยได้หาก UI ว่างเปล่า/frozen) * * * ### [ปิดการใช้งานปลั๊กอิน](https://opencode.ai/docs/th/troubleshooting#%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%9B%E0%B8%A5%E0%B8%B1%E0%B9%8A%E0%B8%81%E0%B8%AD%E0%B8%B4%E0%B8%99) หากแอปเดสก์ท็อปขัดข้องเมื่อเปิดใช้งาน หยุดทำงาน หรือทำงานผิดปกติ ให้เริ่มต้นด้วยการปิดใช้งานปลั๊กอิน #### [ตรวจสอบการกำหนดค่าส่วนกลาง](https://opencode.ai/docs/th/troubleshooting#%E0%B8%95%E0%B8%A3%E0%B8%A7%E0%B8%88%E0%B8%AA%E0%B8%AD%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2%E0%B8%AA%E0%B9%88%E0%B8%A7%E0%B8%99%E0%B8%81%E0%B8%A5%E0%B8%B2%E0%B8%87) เปิดไฟล์กำหนดค่าส่วนกลางของคุณแล้วมองหาคีย์ `plugin` * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (หรือ `~/.config/opencode/opencode.json`) * **macOS/Linux** (การติดตั้งเก่ากว่า): `~/.local/share/opencode/opencode.jsonc` * **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.config\opencode\opencode.jsonc` หากคุณได้กำหนดค่าปลั๊กอินไว้ ให้ปิดการใช้งานชั่วคราวโดยลบคีย์ออกหรือตั้งค่าเป็นอาร์เรย์ว่าง: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [ตรวจสอบไดเร็กทอรีปลั๊กอิน](https://opencode.ai/docs/th/troubleshooting#%E0%B8%95%E0%B8%A3%E0%B8%A7%E0%B8%88%E0%B8%AA%E0%B8%AD%E0%B8%9A%E0%B9%84%E0%B8%94%E0%B9%80%E0%B8%A3%E0%B9%87%E0%B8%81%E0%B8%97%E0%B8%AD%E0%B8%A3%E0%B8%B5%E0%B8%9B%E0%B8%A5%E0%B8%B1%E0%B9%8A%E0%B8%81%E0%B8%AD%E0%B8%B4%E0%B8%99) OpenCode ยังสามารถโหลดปลั๊กอินในเครื่องจากดิสก์ได้ ย้ายสิ่งเหล่านี้ออกไปชั่วคราว (หรือเปลี่ยนชื่อโฟลเดอร์) และรีสตาร์ทแอปเดสก์ท็อป: * **ปลั๊กอินสากล** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.config\opencode\plugins` * **ปลั๊กอินโครงการ** (เฉพาะในกรณีที่คุณใช้การกำหนดค่าต่อโครงการ) * `/.opencode/plugins/` หากแอปเริ่มทำงานอีกครั้ง ให้เปิดใช้งานปลั๊กอินอีกครั้งทีละรายการเพื่อดูว่าปลั๊กอินใดเป็นสาเหตุของปัญหา * * * ### [ล้างแคช](https://opencode.ai/docs/th/troubleshooting#%E0%B8%A5%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B9%81%E0%B8%84%E0%B8%8A) หากการปิดใช้งานปลั๊กอินไม่ได้ผล (หรือการติดตั้งปลั๊กอินค้าง) ให้ล้างแคชเพื่อให้ OpenCode สามารถสร้างใหม่ได้ 1. ออกจาก OpenCode Desktop โดยสมบูรณ์ 2. ลบไดเรกทอรีแคช: * **macOS**: ตัวค้นหา -> `Cmd+Shift+G` -> วาง `~/.cache/opencode` * **Linux**: ลบ `~/.cache/opencode` (หรือรัน `rm -rf ~/.cache/opencode`) * **Windows**: กด `WIN+R` แล้ววาง `%USERPROFILE%\.cache\opencode` 3. รีสตาร์ทเดสก์ท็อป OpenCode * * * ### [แก้ไขปัญหาการเชื่อมต่อเซิร์ฟเวอร์](https://opencode.ai/docs/th/troubleshooting#%E0%B9%81%E0%B8%81%E0%B9%89%E0%B9%84%E0%B8%82%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B9%80%E0%B8%8B%E0%B8%B4%E0%B8%A3%E0%B9%8C%E0%B8%9F%E0%B9%80%E0%B8%A7%E0%B8%AD%E0%B8%A3%E0%B9%8C) OpenCode Desktop สามารถเริ่มต้นเซิร์ฟเวอร์ภายในเครื่องของตนเองได้ (ค่าเริ่มต้น) หรือเชื่อมต่อกับเซิร์ฟเวอร์ URL ที่คุณกำหนดค่าไว้ หากคุณเห็นกล่องโต้ตอบ **“การเชื่อมต่อล้มเหลว”** (หรือแอปไม่เคยผ่านหน้าจอเริ่มต้น) ให้ตรวจสอบเซิร์ฟเวอร์ที่กำหนดเอง URL #### [ล้างเซิร์ฟเวอร์เริ่มต้นของเดสก์ท็อป URL](https://opencode.ai/docs/th/troubleshooting#%E0%B8%A5%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B9%80%E0%B8%8B%E0%B8%B4%E0%B8%A3%E0%B9%8C%E0%B8%9F%E0%B9%80%E0%B8%A7%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%95%E0%B9%89%E0%B8%99%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%94%E0%B8%AA%E0%B8%81%E0%B9%8C%E0%B8%97%E0%B9%87%E0%B8%AD%E0%B8%9B-url) จากหน้าจอหลัก คลิกชื่อเซิร์ฟเวอร์ (ที่มีจุดสถานะ) เพื่อเปิดตัวเลือกเซิร์ฟเวอร์ ในส่วน **เซิร์ฟเวอร์เริ่มต้น** คลิก **ล้าง** #### [ลบ `server.port` / `server.hostname` ออกจากการกำหนดค่าของคุณ](https://opencode.ai/docs/th/troubleshooting#%E0%B8%A5%E0%B8%9A-serverport--serverhostname-%E0%B8%AD%E0%B8%AD%E0%B8%81%E0%B8%88%E0%B8%B2%E0%B8%81%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%84%E0%B8%B8%E0%B8%93) หาก `opencode.json(c)` ของคุณมีส่วน `server` ให้ลบออกชั่วคราวแล้วรีสตาร์ทแอปเดสก์ท็อป #### [ตรวจสอบตัวแปรสภาพแวดล้อม](https://opencode.ai/docs/th/troubleshooting#%E0%B8%95%E0%B8%A3%E0%B8%A7%E0%B8%88%E0%B8%AA%E0%B8%AD%E0%B8%9A%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%9B%E0%B8%A3%E0%B8%AA%E0%B8%A0%E0%B8%B2%E0%B8%9E%E0%B9%81%E0%B8%A7%E0%B8%94%E0%B8%A5%E0%B9%89%E0%B8%AD%E0%B8%A1) หากคุณตั้งค่า `OPENCODE_PORT` ในสภาพแวดล้อมของคุณ แอปเดสก์ท็อปจะพยายามใช้พอร์ตนั้นสำหรับเซิร์ฟเวอร์ภายในเครื่อง * ยกเลิกการตั้งค่า `OPENCODE_PORT` (หรือเลือกพอร์ตว่าง) แล้วรีสตาร์ท * * * ### [Linux: ปัญหา Wayland / X11](https://opencode.ai/docs/th/troubleshooting#linux-%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2-wayland--x11) บน Linux การตั้งค่า Wayland บางอย่างอาจทำให้เกิดหน้าต่างว่างหรือข้อผิดพลาดของตัวประกอบ * หากคุณอยู่บน Wayland และแอปว่างเปล่า/crashing ให้ลองเปิดใช้งานด้วย `OC_ALLOW_WAYLAND=1` * หากสิ่งนั้นทำให้สิ่งต่าง ๆ แย่ลง ให้ลบออกแล้วลองเปิดใช้งานภายใต้เซสชัน X11 แทน * * * ### [Windows: รันไทม์ WebView2](https://opencode.ai/docs/th/troubleshooting#windows-%E0%B8%A3%E0%B8%B1%E0%B8%99%E0%B9%84%E0%B8%97%E0%B8%A1%E0%B9%8C-webview2) บน Windows OpenCode Desktop ต้องใช้ Microsoft Edge **WebView2 Runtime** หากแอปเปิดเป็นหน้าต่างว่างหรือไม่เริ่มทำงาน ให้ติดตั้ง/update WebView2 แล้วลองอีกครั้ง * * * ### [Windows: ปัญหาด้านประสิทธิภาพทั่วไป](https://opencode.ai/docs/th/troubleshooting#windows-%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2%E0%B8%94%E0%B9%89%E0%B8%B2%E0%B8%99%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%AA%E0%B8%B4%E0%B8%97%E0%B8%98%E0%B8%B4%E0%B8%A0%E0%B8%B2%E0%B8%9E%E0%B8%97%E0%B8%B1%E0%B9%88%E0%B8%A7%E0%B9%84%E0%B8%9B) หากคุณประสบปัญหาประสิทธิภาพการทำงานช้า ปัญหาการเข้าถึงไฟล์ หรือปัญหา terminal บน Windows ให้ลองใช้ [WSL (ระบบย่อย Windows สำหรับ Linux)](https://opencode.ai/docs/windows-wsl) WSL มอบสภาพแวดล้อม Linux ที่ทำงานร่วมกับคุณสมบัติของ OpenCode ได้อย่างราบรื่นยิ่งขึ้น * * * ### [การแจ้งเตือนไม่แสดง](https://opencode.ai/docs/th/troubleshooting#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%81%E0%B8%88%E0%B9%89%E0%B8%87%E0%B9%80%E0%B8%95%E0%B8%B7%E0%B8%AD%E0%B8%99%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B9%81%E0%B8%AA%E0%B8%94%E0%B8%87) OpenCode Desktop จะแสดงการแจ้งเตือนของระบบเฉพาะเมื่อ: * การแจ้งเตือนเปิดใช้งานสำหรับ OpenCode ในการตั้งค่าระบบปฏิบัติการของคุณและ * หน้าต่างแอพไม่ได้โฟกัส * * * ### [รีเซ็ตที่เก็บข้อมูลแอปเดสก์ท็อป (วิธีสุดท้าย)](https://opencode.ai/docs/th/troubleshooting#%E0%B8%A3%E0%B8%B5%E0%B9%80%E0%B8%8B%E0%B9%87%E0%B8%95%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%80%E0%B8%81%E0%B9%87%E0%B8%9A%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5%E0%B9%81%E0%B8%AD%E0%B8%9B%E0%B9%80%E0%B8%94%E0%B8%AA%E0%B8%81%E0%B9%8C%E0%B8%97%E0%B9%87%E0%B8%AD%E0%B8%9B-%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B8%AA%E0%B8%B8%E0%B8%94%E0%B8%97%E0%B9%89%E0%B8%B2%E0%B8%A2) หากแอปไม่เริ่มทำงานและคุณไม่สามารถล้างการตั้งค่าจากภายใน UI ได้ ให้รีเซ็ตสถานะที่บันทึกไว้ของแอปเดสก์ท็อป 1. ออกจากเดสก์ท็อป OpenCode 2. ค้นหาและลบไฟล์เหล่านี้ (อยู่ในไดเร็กทอรีข้อมูลแอป OpenCode Desktop): * `opencode.settings.dat` (เซิร์ฟเวอร์เริ่มต้นของเดสก์ท็อป URL) * `opencode.global.dat` และ `opencode.workspace.*.dat` (สถานะ UI เช่น เซิร์ฟเวอร์ล่าสุด/projects) หากต้องการค้นหาไดเร็กทอรีอย่างรวดเร็ว: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (จากนั้นค้นหาชื่อไฟล์ด้านบน) * **Linux**: ค้นหาภายใต้ `~/.local/share` สำหรับชื่อไฟล์ด้านบน * **Windows**: กด `WIN+R` -> `%APPDATA%` (จากนั้นค้นหาชื่อไฟล์ด้านบน) * * * [การขอความช่วยเหลือ](https://opencode.ai/docs/th/troubleshooting#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%82%E0%B8%AD%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%8A%E0%B9%88%E0%B8%A7%E0%B8%A2%E0%B9%80%E0%B8%AB%E0%B8%A5%E0%B8%B7%E0%B8%AD) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- หากคุณประสบปัญหากับ OpenCode: 1. **รายงานปัญหาเกี่ยวกับ GitHub** วิธีที่ดีที่สุดในการรายงานจุดบกพร่องหรือขอคุณสมบัติคือผ่านพื้นที่เก็บข้อมูล GitHub ของเรา: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) ก่อนที่จะสร้างปัญหาใหม่ ให้ค้นหาปัญหาที่มีอยู่เพื่อดูว่าปัญหาของคุณได้รับการรายงานแล้วหรือไม่ 2. **เข้าร่วม Discord ของเรา** สำหรับความช่วยเหลือแบบเรียลไทม์และการสนทนาในชุมชน เข้าร่วมเซิร์ฟเวอร์ Discord ของเรา: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [ปัญหาทั่วไป](https://opencode.ai/docs/th/troubleshooting#%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2%E0%B8%97%E0%B8%B1%E0%B9%88%E0%B8%A7%E0%B9%84%E0%B8%9B) --------------------------------------------------------------------------------------------------------------------------------------------------------------- ต่อไปนี้เป็นปัญหาทั่วไปบางประการและวิธีแก้ปัญหา * * * ### [OpenCode จะไม่เริ่มทำงาน](https://opencode.ai/docs/th/troubleshooting#opencode-%E0%B8%88%E0%B8%B0%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99) 1. ตรวจสอบบันทึกเพื่อดูข้อความแสดงข้อผิดพลาด 2. ลองรันด้วย `--print-logs` เพื่อดูเอาต์พุตใน terminal 3. ตรวจสอบให้แน่ใจว่าคุณมีเวอร์ชันล่าสุดด้วย `opencode upgrade` * * * ### [ปัญหาการรับรองความถูกต้อง](https://opencode.ai/docs/th/troubleshooting#%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%96%E0%B8%B9%E0%B8%81%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87) 1. ลองตรวจสอบความถูกต้องอีกครั้งด้วยคำสั่ง `/connect` ใน TUI 2. ตรวจสอบว่าคีย์ API ของคุณถูกต้อง 3. ตรวจสอบให้แน่ใจว่าเครือข่ายของคุณอนุญาตการเชื่อมต่อกับ API ของผู้ให้บริการ * * * ### [ไม่มีรุ่น](https://opencode.ai/docs/th/troubleshooting#%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B8%A1%E0%B8%B5%E0%B8%A3%E0%B8%B8%E0%B9%88%E0%B8%99) 1. ตรวจสอบว่าคุณได้รับการรับรองความถูกต้องกับผู้ให้บริการแล้ว 2. ตรวจสอบชื่อรุ่นในการกำหนดค่าของคุณถูกต้อง 3. บางรุ่นอาจต้องมีการเข้าถึงหรือสมัครสมาชิกโดยเฉพาะ หากคุณพบ `ProviderModelNotFoundError` เป็นไปได้มากว่าคุณจะคิดผิด อ้างอิงแบบจำลองที่ไหนสักแห่ง ควรอ้างอิงโมเดลดังนี้: `/` ตัวอย่าง: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` หากต้องการทราบว่าคุณมีสิทธิ์เข้าถึงรุ่นใด ให้เรียกใช้ `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/th/troubleshooting#provideriniterror) หากคุณพบ ProviderInitError คุณอาจมีการกำหนดค่าที่ไม่ถูกต้องหรือเสียหาย เพื่อแก้ไขปัญหานี้: 1. ขั้นแรก ตรวจสอบให้แน่ใจว่าผู้ให้บริการของคุณตั้งค่าอย่างถูกต้องโดยทำตาม [คู่มือผู้ให้บริการ](https://opencode.ai/docs/providers) 2. หากปัญหายังคงอยู่ ให้ลองล้างการกำหนดค่าที่เก็บไว้: rm -rf ~/.local/share/opencode บน Windows กด `WIN+R` และลบ: `%USERPROFILE%\.local\share\opencode` 3. ตรวจสอบความถูกต้องอีกครั้งกับผู้ให้บริการของคุณโดยใช้คำสั่ง `/connect` ใน TUI * * * ### [AI\_APICallError และปัญหาแพ็คเกจผู้ให้บริการ](https://opencode.ai/docs/th/troubleshooting#ai_apicallerror-%E0%B9%81%E0%B8%A5%E0%B8%B0%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2%E0%B9%81%E0%B8%9E%E0%B9%87%E0%B8%84%E0%B9%80%E0%B8%81%E0%B8%88%E0%B8%9C%E0%B8%B9%E0%B9%89%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3) หากคุณพบข้อผิดพลาดในการโทร API อาจเนื่องมาจากแพ็คเกจผู้ให้บริการที่ล้าสมัย opencode จะติดตั้งแพ็คเกจของผู้ให้บริการแบบไดนามิก (OpenAI, Anthropic, Google ฯลฯ) ตามความจำเป็น และแคชไว้ในเครื่อง ในการแก้ไขปัญหาแพ็คเกจผู้ให้บริการ: 1. ล้างแคชแพ็คเกจผู้ให้บริการ: rm -rf ~/.cache/opencode บน Windows กด `WIN+R` และลบ: `%USERPROFILE%\.cache\opencode` 2. รีสตาร์ท opencode เพื่อติดตั้งแพ็คเกจผู้ให้บริการล่าสุดอีกครั้ง การดำเนินการนี้จะบังคับให้ opencode ดาวน์โหลดแพ็คเกจผู้ให้บริการเวอร์ชันล่าสุด ซึ่งมักจะแก้ไขปัญหาความเข้ากันได้กับพารามิเตอร์โมเดลและการเปลี่ยนแปลง API * * * ### [Copy/paste ไม่ทำงานบน Linux](https://opencode.ai/docs/th/troubleshooting#copypaste-%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%9A%E0%B8%99-linux) ผู้ใช้ Linux จำเป็นต้องติดตั้งยูทิลิตี้คลิปบอร์ดตัวใดตัวหนึ่งต่อไปนี้เพื่อให้ฟังก์ชัน copy/paste ทำงาน: **สำหรับระบบ X11:** apt install -y xclip# orapt install -y xsel **สำหรับระบบ Wayland:** apt install -y wl-clipboard **สำหรับสภาพแวดล้อมที่ไม่มีหัว:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode จะตรวจพบว่าคุณใช้ Wayland และชอบ `wl-clipboard` หรือไม่เช่นนั้นจะพยายามค้นหาเครื่องมือคลิปบอร์ดตามลำดับ: `xclip` และ `xsel` --- # トラブルシューティング | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/troubleshooting#_top) トラブルシューティング =========== よくある問題とその解決方法。 OpenCode の問題をデバッグするには、まず、ディスク上に保存されているログとローカルデータを確認します。 * * * [ログ](https://opencode.ai/docs/ja/troubleshooting#%E3%83%AD%E3%82%B0) --------------------------------------------------------------------- ログファイルは次の場所に書き込まれます。 * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: `WIN+R` を押して `%USERPROFILE%\.local\share\opencode\log` を貼り付けます ログファイルにはタイムスタンプ付きの名前が付けられ (例: `2025-01-09T123456.log`)、最新の 10 個のログファイルが保存されます。 `--log-level` コマンドラインオプションを使用してログレベルを設定すると、より詳細なデバッグ情報を取得できます。たとえば、`opencode --log-level DEBUG`。 * * * [ストレージ](https://opencode.ai/docs/ja/troubleshooting#%E3%82%B9%E3%83%88%E3%83%AC%E3%83%BC%E3%82%B8) --------------------------------------------------------------------------------------------------- OpenCode は、セッションデータとその他のアプリケーションデータをディスク上の次の場所に保存します。 * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: `WIN+R` を押して `%USERPROFILE%\.local\share\opencode` を貼り付けます このディレクトリには次のものが含まれます。 * `auth.json` - API キー、OAuth トークンなどの認証データ * `log/` - アプリケーションログ * `project/` - セッションデータやメッセージデータなどのプロジェクト固有のデータ * プロジェクトが Git リポジトリ内にある場合は、`.//storage/` に保存されます * Git リポジトリではない場合は、`./global/storage/` に保存されます * * * [デスクトップアプリ](https://opencode.ai/docs/ja/troubleshooting#%E3%83%87%E3%82%B9%E3%82%AF%E3%83%88%E3%83%83%E3%83%97%E3%82%A2%E3%83%97%E3%83%AA) ------------------------------------------------------------------------------------------------------------------------------------------- OpenCode Desktop は、ローカル OpenCode サーバー (`opencode-cli` サイドカー) をバックグラウンドで実行します。ほとんどの問題は、誤動作しているプラグイン、破損したキャッシュ、または不正なサーバー設定によって発生します。 ### [クイックチェック](https://opencode.ai/docs/ja/troubleshooting#%E3%82%AF%E3%82%A4%E3%83%83%E3%82%AF%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF) * アプリを完全に終了して再起動します。 * アプリにエラー画面が表示された場合は、**再起動** をクリックしてエラーの詳細をコピーします。 * macOS のみ: `OpenCode` メニュー -> **Webview をリロード** (UI が空白またはフリーズしている場合に役立ちます)。 * * * ### [プラグインを無効にする](https://opencode.ai/docs/ja/troubleshooting#%E3%83%97%E3%83%A9%E3%82%B0%E3%82%A4%E3%83%B3%E3%82%92%E7%84%A1%E5%8A%B9%E3%81%AB%E3%81%99%E3%82%8B) デスクトップアプリが起動時にクラッシュしたり、ハングしたり、異常な動作をしたりする場合は、まずプラグインを無効にしてください。 #### [グローバル設定の確認](https://opencode.ai/docs/ja/troubleshooting#%E3%82%B0%E3%83%AD%E3%83%BC%E3%83%90%E3%83%AB%E8%A8%AD%E5%AE%9A%E3%81%AE%E7%A2%BA%E8%AA%8D) グローバル設定ファイルを開き、`plugin` キーを探します。 * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (または `~/.config/opencode/opencode.json`) * **macOS/Linux** (古いインストール): `~/.local/share/opencode/opencode.jsonc` * **Windows**: `WIN+R` を押して `%USERPROFILE%\.config\opencode\opencode.jsonc` を貼り付けます プラグインを構成している場合は、キーを削除するか空の配列に設定して、プラグインを一時的に無効にします。 { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [プラグインディレクトリの確認](https://opencode.ai/docs/ja/troubleshooting#%E3%83%97%E3%83%A9%E3%82%B0%E3%82%A4%E3%83%B3%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA%E3%81%AE%E7%A2%BA%E8%AA%8D) OpenCode はディスクからローカルプラグインをロードすることもできます。これらを一時的に邪魔にならない場所に移動し (またはフォルダーの名前を変更し)、デスクトップアプリを再起動します。 * **グローバルプラグイン** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: `WIN+R` を押して `%USERPROFILE%\.config\opencode\plugins` を貼り付けます * **プロジェクトプラグイン** (プロジェクトごとの構成を使用する場合のみ) * `/.opencode/plugins/` アプリが再び動作し始めた場合は、プラグインを 1 つずつ再度有効にして、問題の原因となっているプラ​​グインを特定します。 * * * ### [キャッシュをクリアする](https://opencode.ai/docs/ja/troubleshooting#%E3%82%AD%E3%83%A3%E3%83%83%E3%82%B7%E3%83%A5%E3%82%92%E3%82%AF%E3%83%AA%E3%82%A2%E3%81%99%E3%82%8B) プラグインを無効にしても解決しない場合 (またはプラグインのインストールが停止した場合)、OpenCode がキャッシュを再構築できるようにキャッシュをクリアします。 1. OpenCode Desktop を完全に終了します。 2. キャッシュディレクトリを削除します。 * **macOS**: Finder -> `Cmd+Shift+G` -> `~/.cache/opencode` を貼り付け * **Linux**: `~/.cache/opencode` を削除します (または `rm -rf ~/.cache/opencode` を実行します)。 * **Windows**: `WIN+R` を押して `%USERPROFILE%\.cache\opencode` を貼り付けます 3. OpenCode デスクトップを再起動します。 * * * ### [サーバー接続の問題の修正](https://opencode.ai/docs/ja/troubleshooting#%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E6%8E%A5%E7%B6%9A%E3%81%AE%E5%95%8F%E9%A1%8C%E3%81%AE%E4%BF%AE%E6%AD%A3) OpenCode Desktop は、独自のローカルサーバー (デフォルト) を起動することも、構成したサーバー URL に接続することもできます。 **「接続に失敗しました」** ダイアログが表示された場合 (またはアプリがスプラッシュ画面を通過できない場合)、カスタムサーバー URL を確認してください。 #### [デスクトップのデフォルトのサーバー URL をクリアします](https://opencode.ai/docs/ja/troubleshooting#%E3%83%87%E3%82%B9%E3%82%AF%E3%83%88%E3%83%83%E3%83%97%E3%81%AE%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%81%AE%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC-url-%E3%82%92%E3%82%AF%E3%83%AA%E3%82%A2%E3%81%97%E3%81%BE%E3%81%99) ホーム画面でサーバー名 (ステータスドット付き) をクリックしてサーバーピッカーを開きます。 \[**デフォルトサーバー**\] セクションで、\[**クリア**\] をクリックします。 #### [設定から `server.port` / `server.hostname` を削除します](https://opencode.ai/docs/ja/troubleshooting#%E8%A8%AD%E5%AE%9A%E3%81%8B%E3%82%89-serverport--serverhostname-%E3%82%92%E5%89%8A%E9%99%A4%E3%81%97%E3%81%BE%E3%81%99) `opencode.json(c)` に `server` セクションが含まれている場合は、それを一時的に削除し、デスクトップアプリを再起動します。 #### [環境変数を確認する](https://opencode.ai/docs/ja/troubleshooting#%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0%E3%82%92%E7%A2%BA%E8%AA%8D%E3%81%99%E3%82%8B) 環境に `OPENCODE_PORT` が設定されている場合、デスクトップアプリはローカルサーバーにそのポートを使用しようとします。 * `OPENCODE_PORT` の設定を解除して (または空きポートを選択して)、再起動します。 * * * ### [Linux: Wayland / X11 の問題](https://opencode.ai/docs/ja/troubleshooting#linux-wayland--x11-%E3%81%AE%E5%95%8F%E9%A1%8C) Linux では、一部の Wayland セットアップにより、空白のウィンドウやコンポジターエラーが発生する可能性があります。 * Wayland を使用していて、アプリが空白またはクラッシュしている場合は、`OC_ALLOW_WAYLAND=1` で起動してみてください。 * これにより状況が悪化する場合は、それを削除し、代わりに X11 セッションで起動してみてください。 * * * ### [Windows: WebView2 ランタイム](https://opencode.ai/docs/ja/troubleshooting#windows-webview2-%E3%83%A9%E3%83%B3%E3%82%BF%E3%82%A4%E3%83%A0) Windows では、OpenCode Desktop には Microsoft Edge **WebView2 ランタイム**が必要です。アプリが空白のウィンドウで開くか、起動しない場合は、WebView2 をインストールまたは更新して、もう一度試してください。 * * * ### [Windows: 一般的なパフォーマンスの問題](https://opencode.ai/docs/ja/troubleshooting#windows-%E4%B8%80%E8%88%AC%E7%9A%84%E3%81%AA%E3%83%91%E3%83%95%E3%82%A9%E3%83%BC%E3%83%9E%E3%83%B3%E3%82%B9%E3%81%AE%E5%95%8F%E9%A1%8C) Windows でパフォーマンスの低下、ファイルアクセスの問題、またはターミナルの問題が発生している場合は、[WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) を使用してみてください。 WSL は、OpenCode の機能とよりシームレスに連携する Linux 環境を提供します。 * * * ### [通知が表示されない](https://opencode.ai/docs/ja/troubleshooting#%E9%80%9A%E7%9F%A5%E3%81%8C%E8%A1%A8%E7%A4%BA%E3%81%95%E3%82%8C%E3%81%AA%E3%81%84) OpenCode Desktop では、次の場合にのみシステム通知が表示されます。 * OS 設定で OpenCode の通知が有効になっており、 * アプリウィンドウにフォーカスがありません。 * * * ### [デスクトップアプリのストレージのリセット (最後の手段)](https://opencode.ai/docs/ja/troubleshooting#%E3%83%87%E3%82%B9%E3%82%AF%E3%83%88%E3%83%83%E3%83%97%E3%82%A2%E3%83%97%E3%83%AA%E3%81%AE%E3%82%B9%E3%83%88%E3%83%AC%E3%83%BC%E3%82%B8%E3%81%AE%E3%83%AA%E3%82%BB%E3%83%83%E3%83%88-%E6%9C%80%E5%BE%8C%E3%81%AE%E6%89%8B%E6%AE%B5) アプリが起動せず、UI 内から設定をクリアできない場合は、デスクトップアプリの保存された状態をリセットします。 1. OpenCode デスクトップを終了します。 2. これらのファイルを見つけて削除します (これらのファイルは OpenCode デスクトップアプリのデータディレクトリにあります)。 * `opencode.settings.dat` (デスクトップのデフォルトサーバー URL) * `opencode.global.dat` および `opencode.workspace.*.dat` (最近のサーバー/プロジェクトなどの UI 状態) ディレクトリをすばやく見つけるには: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (その後、上記のファイル名を検索します) * **Linux**: 上記のファイル名を `~/.local/share` で検索します。 * **Windows**: `WIN+R` -> `%APPDATA%` を押します (その後、上記のファイル名を検索します)。 * * * [ヘルプを求める](https://opencode.ai/docs/ja/troubleshooting#%E3%83%98%E3%83%AB%E3%83%97%E3%82%92%E6%B1%82%E3%82%81%E3%82%8B) ----------------------------------------------------------------------------------------------------------------------- OpenCode で問題が発生している場合: 1. **GitHub で問題を報告してください** バグを報告したり、機能をリクエストしたりする最良の方法は、GitHub リポジトリを使用することです。 [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) 新しい問題を作成する前に、既存の問題を検索して、問題がすでに報告されているかどうかを確認してください。 2. **Discord への参加** リアルタイムのヘルプやコミュニティのディスカッションについては、Discord サーバーに参加してください。 [**opencode.ai/discord**](https://opencode.ai/discord) * * * [よくある問題](https://opencode.ai/docs/ja/troubleshooting#%E3%82%88%E3%81%8F%E3%81%82%E3%82%8B%E5%95%8F%E9%A1%8C) ------------------------------------------------------------------------------------------------------------- ここでは、いくつかの一般的な問題とその解決方法を示します。 * * * ### [OpenCode が起動しない](https://opencode.ai/docs/ja/troubleshooting#opencode-%E3%81%8C%E8%B5%B7%E5%8B%95%E3%81%97%E3%81%AA%E3%81%84) 1. ログでエラーメッセージを確認する 2. `--print-logs` で実行して、ターミナルに出力を確認してください。 3. `opencode upgrade` を含む最新バージョンを使用していることを確認してください * * * ### [認証の問題](https://opencode.ai/docs/ja/troubleshooting#%E8%AA%8D%E8%A8%BC%E3%81%AE%E5%95%8F%E9%A1%8C) 1. TUI で `/connect` コマンドを使用して再認証を試みます 2. API キーが有効であることを確認してください 3. ネットワークでプロバイダーの API への接続が許可されていることを確認してください * * * ### [モデルが見つからない](https://opencode.ai/docs/ja/troubleshooting#%E3%83%A2%E3%83%87%E3%83%AB%E3%81%8C%E8%A6%8B%E3%81%A4%E3%81%8B%E3%82%89%E3%81%AA%E3%81%84) 1. プロバイダーで認証されていることを確認してください 2. 構成内のモデル名が正しいことを確認してください 3. 一部のモデルでは、特定のアクセスまたはサブスクリプションが必要な場合があります `ProviderModelNotFoundError` が表示された場合は、間違いがある可能性が高くなります。 どこかのモデルを参照しています。 モデルは次のように参照する必要があります: `/` 例: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` どのモデルにアクセスできるかを確認するには、`opencode models` を実行します。 * * * ### [ProviderInitError](https://opencode.ai/docs/ja/troubleshooting#provideriniterror) ProviderInitError が発生した場合は、構成が無効または破損している可能性があります。 これを解決するには: 1. まず、[プロバイダーガイド](https://opencode.ai/docs/providers) に従って、プロバイダーが正しく設定されていることを確認します。 2. 問題が解決しない場合は、保存されている構成をクリアしてみてください。 rm -rf ~/.local/share/opencode Windows では、`WIN+R` を押して、`%USERPROFILE%\.local\share\opencode` を削除します。 3. TUI の `/connect` コマンドを使用して、プロバイダーで再認証します。 * * * ### [AI\_APICallError とプロバイダーパッケージの問題](https://opencode.ai/docs/ja/troubleshooting#ai_apicallerror-%E3%81%A8%E3%83%97%E3%83%AD%E3%83%90%E3%82%A4%E3%83%80%E3%83%BC%E3%83%91%E3%83%83%E3%82%B1%E3%83%BC%E3%82%B8%E3%81%AE%E5%95%8F%E9%A1%8C) API 呼び出しエラーが発生した場合は、プロバイダーパッケージが古いことが原因である可能性があります。 OpenCode は、必要に応じてプロバイダーパッケージ (OpenAI、Anthropic、Google など) を動的にインストールし、ローカルにキャッシュします。 プロバイダーパッケージの問題を解決するには: 1. プロバイダーパッケージのキャッシュをクリアします。 rm -rf ~/.cache/opencode Windows では、`WIN+R` を押して、`%USERPROFILE%\.cache\opencode` を削除します。 2. OpenCode を再起動して最新のプロバイダーパッケージを再インストールします これにより、OpenCode はプロバイダーパッケージの最新バージョンを強制的にダウンロードすることになり、多くの場合、モデルパラメーターや API の変更に関する互換性の問題が解決されます。 * * * ### [Linux ではコピー/ペーストが機能しない](https://opencode.ai/docs/ja/troubleshooting#linux-%E3%81%A7%E3%81%AF%E3%82%B3%E3%83%94%E3%83%BC%E3%83%9A%E3%83%BC%E3%82%B9%E3%83%88%E3%81%8C%E6%A9%9F%E8%83%BD%E3%81%97%E3%81%AA%E3%81%84) Linux ユーザーがコピー/ペースト機能を動作させるには、次のクリップボードユーティリティのいずれかがインストールされている必要があります。 **X11 システムの場合:** apt install -y xclip# orapt install -y xsel **Wayland システムの場合:** apt install -y wl-clipboard **ヘッドレス環境の場合:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 OpenCode は、Wayland を使用していて `wl-clipboard` を優先しているかどうかを検出します。そうでない場合は、`xclip` および `xsel` の順序でクリップボードツールを検索しようとします。 --- # Web | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/web#_top) Web === Verwenden Sie OpenCode in Ihrem Browser. OpenCode kann als Webanwendung in Ihrem Browser ausgeführt werden und bietet das gleiche leistungsstarke KI-Codierungserlebnis, ohne dass ein Terminal erforderlich ist. ![OpenCode Web – Neue Sitzung](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Erste Schritte](https://opencode.ai/docs/de/web#erste-schritte) ----------------------------------------------------------------- Starten Sie die Weboberfläche, indem Sie Folgendes ausführen: opencode web Dadurch wird ein lokaler Server auf `127.0.0.1` mit einem zufällig verfügbaren Port gestartet und OpenCode automatisch in Ihrem Standardbrowser geöffnet. * * * [Konfiguration](https://opencode.ai/docs/de/web#konfiguration) --------------------------------------------------------------- Sie können den Webserver mithilfe von Befehlszeilen-Flags oder in Ihrer [Konfigurationsdatei](https://opencode.ai/docs/config) konfigurieren. ### [Port](https://opencode.ai/docs/de/web#port) Standardmäßig wählt OpenCode einen verfügbaren Port aus. Sie können einen Port angeben: opencode web --port 4096 ### [Hostname](https://opencode.ai/docs/de/web#hostname) Standardmäßig bindet der Server an `127.0.0.1` (nur localhost). So machen Sie OpenCode in Ihrem Netzwerk zugänglich: opencode web --hostname 0.0.0.0 Bei Verwendung von `0.0.0.0` zeigt OpenCode sowohl lokale als auch Netzwerkadressen an: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS-Erkennung](https://opencode.ai/docs/de/web#mdns-erkennung) Aktivieren Sie mDNS, um Ihren Server im lokalen Netzwerk erkennbar zu machen: opencode web --mdns Dadurch wird der Hostname automatisch auf `0.0.0.0` gesetzt und der Server als `opencode.local` angekündigt. Sie können den mDNS-Domänennamen anpassen, um mehrere Instanzen im selben Netzwerk auszuführen: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/de/web#cors) So erlauben Sie zusätzliche Domänen für CORS (nützlich für benutzerdefinierte Frontends): opencode web --cors https://example.com ### [Authentifizierung](https://opencode.ai/docs/de/web#authentifizierung) Um den Zugriff zu schützen, legen Sie mithilfe der Umgebungsvariablen `OPENCODE_SERVER_PASSWORD` ein Passwort fest: OPENCODE_SERVER_PASSWORD=secret opencode web Der Benutzername ist standardmäßig `opencode`, kann aber mit `OPENCODE_SERVER_USERNAME` geändert werden. * * * [Verwenden der Weboberfläche](https://opencode.ai/docs/de/web#verwenden-der-weboberfl%C3%A4che) ------------------------------------------------------------------------------------------------ Nach dem Start bietet die Weboberfläche Zugriff auf Ihre OpenCode-Sitzungen. ### [Sitzungen](https://opencode.ai/docs/de/web#sitzungen) Zeigen Sie Ihre Sitzungen auf der Startseite an und verwalten Sie sie. Sie können aktive Sitzungen sehen und neue starten. ![OpenCode Web – Aktive Sitzung](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Serverstatus](https://opencode.ai/docs/de/web#serverstatus) Klicken Sie auf „Server anzeigen“, um verbundene Server und deren Status anzuzeigen. ![OpenCode Web – Siehe Server](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Anschließen eines Terminals](https://opencode.ai/docs/de/web#anschlie%C3%9Fen-eines-terminals) ------------------------------------------------------------------------------------------------ Sie können eine Terminal-TUI an einen laufenden Webserver anschließen: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Dadurch können Sie sowohl die Weboberfläche als auch das Terminal gleichzeitig verwenden und dieselben Sitzungen und denselben Status teilen. * * * [Konfigurationsdatei](https://opencode.ai/docs/de/web#konfigurationsdatei) --------------------------------------------------------------------------- Sie können Servereinstellungen auch in Ihrer `opencode.json`\-Konfigurationsdatei konfigurieren: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Befehlszeilenflags haben Vorrang vor Konfigurationsdateieinstellungen. --- # Web | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/web#_top) Web === Usando OpenCode en su navegador. OpenCode puede ejecutarse como una aplicación web en su navegador, brindando la misma poderosa experiencia de codificación de IA sin necesidad de una terminal. ![OpenCode Web - Nueva sesión](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Empezar](https://opencode.ai/docs/es/web#empezar) --------------------------------------------------- Inicie la interfaz web ejecutando: opencode web Esto inicia un servidor local en `127.0.0.1` con un puerto disponible aleatorio y abre automáticamente OpenCode en su navegador predeterminado. * * * [Configuración](https://opencode.ai/docs/es/web#configuraci%C3%B3n) -------------------------------------------------------------------- Puede configurar el servidor web usando indicadores de línea de comando o en su [archivo de configuración](https://opencode.ai/docs/config) . ### [Puerto](https://opencode.ai/docs/es/web#puerto) De forma predeterminada, OpenCode elige un puerto disponible. Puede especificar un puerto: opencode web --port 4096 ### [Nombre de host](https://opencode.ai/docs/es/web#nombre-de-host) De forma predeterminada, el servidor se vincula a `127.0.0.1` (solo localhost). Para hacer que OpenCode sea accesible en su red: opencode web --hostname 0.0.0.0 Al usar `0.0.0.0`, OpenCode mostrará direcciones locales y de red: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [Descubrimiento de mDNS](https://opencode.ai/docs/es/web#descubrimiento-de-mdns) Habilite mDNS para que su servidor sea reconocible en la red local: opencode web --mdns Esto establece automáticamente el nombre de host en `0.0.0.0` y anuncia el servidor como `opencode.local`. Puede personalizar el nombre de dominio mDNS para ejecutar varias instancias en la misma red: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/es/web#cors) Para permitir dominios adicionales para CORS (útil para interfaces personalizadas): opencode web --cors https://example.com ### [Autenticación](https://opencode.ai/docs/es/web#autenticaci%C3%B3n) Para proteger el acceso, establezca una contraseña utilizando la variable de entorno `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web El nombre de usuario predeterminado es `opencode` pero se puede cambiar con `OPENCODE_SERVER_USERNAME`. * * * [Usar la interfaz web](https://opencode.ai/docs/es/web#usar-la-interfaz-web) ----------------------------------------------------------------------------- Una vez iniciada, la interfaz web proporciona acceso a sus sesiones OpenCode. ### [Sesiones](https://opencode.ai/docs/es/web#sesiones) Vea y administre sus sesiones desde la página de inicio. Puedes ver sesiones activas e iniciar otras nuevas. ![OpenCode Web - Sesión activa](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Estado del servidor](https://opencode.ai/docs/es/web#estado-del-servidor) Haga clic en “Ver servidores” para ver los servidores conectados y su estado. ![OpenCode Web - Ver Servidores](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Adjuntar una terminal](https://opencode.ai/docs/es/web#adjuntar-una-terminal) ------------------------------------------------------------------------------- Puede conectar un terminal TUI a un servidor web en ejecución: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Esto le permite utilizar la interfaz web y el terminal simultáneamente, compartiendo las mismas sesiones y estados. * * * [Archivo de configuración](https://opencode.ai/docs/es/web#archivo-de-configuraci%C3%B3n) ------------------------------------------------------------------------------------------ También puede configurar los ajustes del servidor en su archivo de configuración `opencode.json`: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Los indicadores de la línea de comando tienen prioridad sobre la configuración del archivo de configuración. --- # Web | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/web#_top) Web === Usando o opencode no seu navegador. O opencode pode ser executado como uma aplicação web no seu navegador, proporcionando a mesma poderosa experiência de codificação com IA sem precisar de um terminal. ![opencode Web - Nova Sessão](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Primeiros passos](https://opencode.ai/docs/pt-br/web#primeiros-passos) ------------------------------------------------------------------------ Inicie a interface web executando: opencode web Isso inicia um servidor local em `127.0.0.1` com uma porta aleatória disponível e abre automaticamente o opencode no seu navegador padrão. * * * [Configuração](https://opencode.ai/docs/pt-br/web#configura%C3%A7%C3%A3o) -------------------------------------------------------------------------- Você pode configurar o servidor web usando flags de linha de comando ou no seu [arquivo de configuração](https://opencode.ai/docs/config) . ### [Porta](https://opencode.ai/docs/pt-br/web#porta) Por padrão, o opencode escolhe uma porta disponível. Você pode especificar uma porta: opencode web --port 4096 ### [Nome do Host](https://opencode.ai/docs/pt-br/web#nome-do-host) Por padrão, o servidor se vincula a `127.0.0.1` (apenas localhost). Para tornar o opencode acessível na sua rede: opencode web --hostname 0.0.0.0 Ao usar `0.0.0.0`, o opencode exibirá endereços locais e de rede: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [Descoberta mDNS](https://opencode.ai/docs/pt-br/web#descoberta-mdns) Ative o mDNS para tornar seu servidor descobrível na rede local: opencode web --mdns Isso define automaticamente o nome do host como `0.0.0.0` e anuncia o servidor como `opencode.local`. Você pode personalizar o nome de domínio mDNS para executar várias instâncias na mesma rede: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/pt-br/web#cors) Para permitir domínios adicionais para CORS (útil para frontends personalizados): opencode web --cors https://example.com ### [Autenticação](https://opencode.ai/docs/pt-br/web#autentica%C3%A7%C3%A3o) Para proteger o acesso, defina uma senha usando a variável de ambiente `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web O nome de usuário padrão é `opencode`, mas pode ser alterado com `OPENCODE_SERVER_USERNAME`. * * * [Usando a Interface Web](https://opencode.ai/docs/pt-br/web#usando-a-interface-web) ------------------------------------------------------------------------------------ Uma vez iniciada, a interface web fornece acesso às suas sessões do opencode. ### [Sessões](https://opencode.ai/docs/pt-br/web#sess%C3%B5es) Visualize e gerencie suas sessões a partir da página inicial. Você pode ver sessões ativas e iniciar novas. ![opencode Web - Sessão Ativa](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Status do Servidor](https://opencode.ai/docs/pt-br/web#status-do-servidor) Clique em “Ver Servidores” para visualizar os servidores conectados e seu status. ![opencode Web - Ver Servidores](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Anexando um Terminal](https://opencode.ai/docs/pt-br/web#anexando-um-terminal) -------------------------------------------------------------------------------- Você pode anexar um terminal TUI a um servidor web em execução: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Isso permite que você use tanto a interface web quanto o terminal simultaneamente, compartilhando as mesmas sessões e estado. * * * [Arquivo de Configuração](https://opencode.ai/docs/pt-br/web#arquivo-de-configura%C3%A7%C3%A3o) ------------------------------------------------------------------------------------------------ Você também pode configurar as configurações do servidor no seu arquivo de configuração `opencode.json`: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} As flags de linha de comando têm precedência sobre as configurações do arquivo de configuração. --- # ปลั๊กอิน | OpenCode [Skip to content](https://opencode.ai/docs/th/plugins#_top) ปลั๊กอิน ======== เขียนปลั๊กอินของคุณเองเพื่อขยาย OpenCode ปลั๊กอินช่วยให้คุณสามารถขยาย OpenCode ได้โดยเชื่อมโยงกับเหตุการณ์ต่างๆ และปรับแต่งลักษณะการทำงาน คุณสามารถสร้างปลั๊กอินเพื่อเพิ่มคุณสมบัติใหม่ บูรณาการกับบริการภายนอก หรือแก้ไขการทำงานเริ่มต้นของ OpenCode ตัวอย่างเช่น ลองดู [ปลั๊กอิน](https://opencode.ai/docs/ecosystem#%E0%B8%9B%E0%B8%A5%E0%B8%B1%E0%B9%8A%E0%B8%81%E0%B8%AD%E0%B8%B4%E0%B8%99) ที่สร้างโดยชุมชน * * * [ใช้ปลั๊กอิน](https://opencode.ai/docs/th/plugins#%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%9B%E0%B8%A5%E0%B8%B1%E0%B9%8A%E0%B8%81%E0%B8%AD%E0%B8%B4%E0%B8%99) ------------------------------------------------------------------------------------------------------------------------------------------------------- มีสองวิธีในการโหลดปลั๊กอิน * * * ### [จากไฟล์ในเครื่อง](https://opencode.ai/docs/th/plugins#%E0%B8%88%E0%B8%B2%E0%B8%81%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C%E0%B9%83%E0%B8%99%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87) วางไฟล์ JavaScript หรือ TypeScript ในไดเร็กทอรีปลั๊กอิน * `.opencode/plugins/` - ​​ปลั๊กอินระดับโครงการ * `~/.config/opencode/plugins/` - ​​ปลั๊กอินทั่วโลก ไฟล์ในไดเร็กทอรีเหล่านี้จะถูกโหลดโดยอัตโนมัติเมื่อเริ่มต้นระบบ * * * ### [จาก npm](https://opencode.ai/docs/th/plugins#%E0%B8%88%E0%B8%B2%E0%B8%81-npm) ระบุแพ็คเกจ npm ในไฟล์ปรับแต่งของคุณ { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} รองรับแพ็คเกจ npm ทั้งแบบปกติและแบบกำหนดขอบเขต เรียกดูปลั๊กอินที่มีอยู่ใน [ระบบนิเวศ](https://opencode.ai/docs/ecosystem#plugins) * * * ### [วิธีการติดตั้งปลั๊กอิน](https://opencode.ai/docs/th/plugins#%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%95%E0%B8%B4%E0%B8%94%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87%E0%B8%9B%E0%B8%A5%E0%B8%B1%E0%B9%8A%E0%B8%81%E0%B8%AD%E0%B8%B4%E0%B8%99) **ปลั๊กอิน npm** ได้รับการติดตั้งโดยอัตโนมัติโดยใช้ Bun เมื่อเริ่มต้น แพ็คเกจและการขึ้นต่อกันถูกแคชไว้ใน `~/.cache/opencode/node_modules/` **ปลั๊กอินท้องถิ่น** โหลดโดยตรงจากไดเร็กทอรีปลั๊กอิน หากต้องการใช้แพ็คเกจภายนอก คุณต้องสร้าง `package.json` ภายในไดเร็กทอรีการกำหนดค่าของคุณ (ดู [การพึ่งพา](https://opencode.ai/docs/th/plugins#dependencies) ) หรือเผยแพร่ปลั๊กอินไปที่ npm และ [เพิ่มลงในการกำหนดค่าของคุณ](https://opencode.ai/docs/config#plugins) * * * ### [โหลดออเดอร์](https://opencode.ai/docs/th/plugins#%E0%B9%82%E0%B8%AB%E0%B8%A5%E0%B8%94%E0%B8%AD%E0%B8%AD%E0%B9%80%E0%B8%94%E0%B8%AD%E0%B8%A3%E0%B9%8C) ปลั๊กอินถูกโหลดจากทุกแหล่งและ hooks ทั้งหมดทำงานตามลำดับ ลำดับการโหลดคือ: 1. การกำหนดค่าส่วนกลาง (`~/.config/opencode/opencode.json`) 2. การกำหนดค่าโครงการ (`opencode.json`) 3. ไดเร็กทอรีปลั๊กอินสากล (`~/.config/opencode/plugins/`) 4. ไดเรกทอรีปลั๊กอินโครงการ (`.opencode/plugins/`) แพ็กเกจ npm ที่ซ้ำกันซึ่งมีชื่อและเวอร์ชันเดียวกันจะถูกโหลดหนึ่งครั้ง อย่างไรก็ตาม ทั้งปลั๊กอินในเครื่องและปลั๊กอิน npm ที่มีชื่อคล้ายกันจะโหลดแยกกัน * * * [สร้างปลั๊กอิน](https://opencode.ai/docs/th/plugins#%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B8%9B%E0%B8%A5%E0%B8%B1%E0%B9%8A%E0%B8%81%E0%B8%AD%E0%B8%B4%E0%B8%99) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ปลั๊กอินคือ **JavaScript/TypeScript module** ที่ส่งออกปลั๊กอินอย่างน้อยหนึ่งรายการ ฟังก์ชั่น แต่ละฟังก์ชันได้รับวัตถุบริบทและส่งกลับวัตถุ hooks * * * ### [การพึ่งพาอาศัยกัน](https://opencode.ai/docs/th/plugins#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9E%E0%B8%B6%E0%B9%88%E0%B8%87%E0%B8%9E%E0%B8%B2%E0%B8%AD%E0%B8%B2%E0%B8%A8%E0%B8%B1%E0%B8%A2%E0%B8%81%E0%B8%B1%E0%B8%99) ปลั๊กอินท้องถิ่นและเครื่องมือแบบกำหนดเองสามารถใช้แพ็คเกจ npm ภายนอกได้ เพิ่ม `package.json` ลงในไดเร็กทอรี config ของคุณด้วยการอ้างอิงที่คุณต้องการ { "dependencies": { "shescape": "^2.1.0" }} OpenCode รัน `bun install` เมื่อเริ่มต้นเพื่อติดตั้งสิ่งเหล่านี้ ปลั๊กอินและเครื่องมือของคุณสามารถนำเข้าได้ import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [โครงสร้างพื้นฐาน](https://opencode.ai/docs/th/plugins#%E0%B9%82%E0%B8%84%E0%B8%A3%E0%B8%87%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B8%9E%E0%B8%B7%E0%B9%89%E0%B8%99%E0%B8%90%E0%B8%B2%E0%B8%99) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} ฟังก์ชั่นปลั๊กอินได้รับ: * `project`: ข้อมูลโครงการปัจจุบัน * `directory`: ไดเร็กทอรีการทำงานปัจจุบัน * `worktree`: เส้นทางเวิร์กทรีคอมไพล์ * `client`: ไคลเอนต์ opencode SDK สำหรับการโต้ตอบกับ AI * `$`: [shell API](https://bun.com/docs/runtime/shell) ของ Bun สำหรับการดำเนินการคำสั่ง * * * ### [รองรับ TypeScript](https://opencode.ai/docs/th/plugins#%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A-typescript) สำหรับปลั๊กอิน TypeScript คุณสามารถนำเข้าประเภทจากแพ็คเกจปลั๊กอินได้: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [กิจกรรม](https://opencode.ai/docs/th/plugins#%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%81%E0%B8%A3%E0%B8%A3%E0%B8%A1) ปลั๊กอินสามารถสมัครรับกิจกรรมได้ดังที่แสดงด้านล่างในส่วนตัวอย่าง นี่คือรายการกิจกรรมต่างๆ ที่มี #### [เหตุการณ์คำสั่ง](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%84%E0%B8%B3%E0%B8%AA%E0%B8%B1%E0%B9%88%E0%B8%87) * `command.executed` #### [ไฟล์เหตุการณ์](https://opencode.ai/docs/th/plugins#%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C) * `file.edited` * `file.watcher.updated` #### [เหตุการณ์การติดตั้ง](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%95%E0%B8%B4%E0%B8%94%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87) * `installation.updated` #### [LSP กิจกรรม](https://opencode.ai/docs/th/plugins#lsp-%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%81%E0%B8%A3%E0%B8%A3%E0%B8%A1) * `lsp.client.diagnostics` * `lsp.updated` #### [เหตุการณ์ข้อความ](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [เหตุการณ์การอนุญาต](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AD%E0%B8%99%E0%B8%B8%E0%B8%8D%E0%B8%B2%E0%B8%95) * `permission.asked` * `permission.replied` #### [เหตุการณ์เซิร์ฟเวอร์](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B9%80%E0%B8%8B%E0%B8%B4%E0%B8%A3%E0%B9%8C%E0%B8%9F%E0%B9%80%E0%B8%A7%E0%B8%AD%E0%B8%A3%E0%B9%8C) * `server.connected` #### [กิจกรรมเซสชั่น](https://opencode.ai/docs/th/plugins#%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%81%E0%B8%A3%E0%B8%A3%E0%B8%A1%E0%B9%80%E0%B8%8B%E0%B8%AA%E0%B8%8A%E0%B8%B1%E0%B9%88%E0%B8%99) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [เหตุการณ์ที่ต้องทำ](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87%E0%B8%97%E0%B8%B3) * `todo.updated` #### [กิจกรรมของ shell](https://opencode.ai/docs/th/plugins#%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%81%E0%B8%A3%E0%B8%A3%E0%B8%A1%E0%B8%82%E0%B8%AD%E0%B8%87-shell) * `shell.env` #### [เหตุการณ์เครื่องมือ](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%AB%E0%B8%95%E0%B8%B8%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD) * `tool.execute.after` * `tool.execute.before` #### [TUI กิจกรรม](https://opencode.ai/docs/th/plugins#tui-%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%81%E0%B8%A3%E0%B8%A3%E0%B8%A1) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [ตัวอย่าง](https://opencode.ai/docs/th/plugins#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87) ------------------------------------------------------------------------------------------------------------------------- นี่คือตัวอย่างบางส่วนของปลั๊กอินที่คุณสามารถใช้เพื่อขยาย opencode * * * ### [ส่งการแจ้งเตือน](https://opencode.ai/docs/th/plugins#%E0%B8%AA%E0%B9%88%E0%B8%87%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%81%E0%B8%88%E0%B9%89%E0%B8%87%E0%B9%80%E0%B8%95%E0%B8%B7%E0%B8%AD%E0%B8%99) ส่งการแจ้งเตือนเมื่อมีเหตุการณ์บางอย่างเกิดขึ้น: 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"'` } }, }} เรากำลังใช้ `osascript` เพื่อเรียกใช้ AppleScript บน macOS ที่นี่เราใช้มันเพื่อส่งการแจ้งเตือน * * * ### [การป้องกัน .env](https://opencode.ai/docs/th/plugins#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9B%E0%B9%89%E0%B8%AD%E0%B8%87%E0%B8%81%E0%B8%B1%E0%B8%99-env) ป้องกันไม่ให้ opencode อ่านไฟล์ `.env`: 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") } }, }} * * * ### [ฉีดตัวแปรสภาพแวดล้อม](https://opencode.ai/docs/th/plugins#%E0%B8%89%E0%B8%B5%E0%B8%94%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%9B%E0%B8%A3%E0%B8%AA%E0%B8%A0%E0%B8%B2%E0%B8%9E%E0%B9%81%E0%B8%A7%E0%B8%94%E0%B8%A5%E0%B9%89%E0%B8%AD%E0%B8%A1) แทรกตัวแปรสภาพแวดล้อมลงในการดำเนินการ shell ทั้งหมด (เครื่องมือ AI และ terminal ผู้ใช้): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [เครื่องมือที่กำหนดเอง](https://opencode.ai/docs/th/plugins#%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) ปลั๊กอินยังสามารถเพิ่มเครื่องมือที่กำหนดเองให้กับ opencode: 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})` }, }), }, }} ตัวช่วย `tool` สร้างเครื่องมือแบบกำหนดเองที่สามารถเรียกใช้ opencode ได้ ใช้ฟังก์ชัน Zod schema และส่งกลับคำจำกัดความของเครื่องมือด้วย: * `description`: เครื่องมือนี้ทำอะไร * `args`: Zod schema สำหรับข้อโต้แย้งของเครื่องมือ * `execute`: ฟังก์ชั่นที่ทำงานเมื่อมีการเรียกใช้เครื่องมือ เครื่องมือที่คุณกำหนดเองจะพร้อมใช้งานสำหรับ opencode ควบคู่ไปกับเครื่องมือในตัว * * * ### [การบันทึก](https://opencode.ai/docs/th/plugins#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9A%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B6%E0%B8%81) ใช้ `client.app.log()` แทน `console.log` สำหรับการบันทึกแบบมีโครงสร้าง: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} ระดับ: `debug`, `info`, `warn`, `error` ดู[SDKเอกสารประกอบ](https://opencode.ai/docs/sdk) สำหรับรายละเอียด * * * ### [Hooks สำหรับการกระชับข้อมูล](https://opencode.ai/docs/th/plugins#hooks-%E0%B8%AA%E0%B8%B3%E0%B8%AB%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%81%E0%B8%A3%E0%B8%B0%E0%B8%8A%E0%B8%B1%E0%B8%9A%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5) ปรับแต่งบริบทที่รวมไว้เมื่อมีการกระชับเซสชัน: 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`) }, }} `experimental.session.compacting` hook เริ่มทำงานก่อนที่ LLM จะสร้างข้อมูลสรุปต่อเนื่อง ใช้เพื่อแทรกบริบทเฉพาะโดเมนที่พรอมต์การบีบอัดข้อมูลเริ่มต้นอาจพลาดไป คุณยังสามารถแทนที่พรอมต์การกระชับข้อมูลทั้งหมดได้โดยตั้งค่า `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} เมื่อตั้งค่า `output.prompt` มันจะแทนที่พร้อมท์การกระชับค่าเริ่มต้นโดยสมบูรณ์ อาร์เรย์ `output.context` จะถูกละเว้นในกรณีนี้ --- # الإضافات | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/plugins#_top) الإضافات ======== اكتب إضافاتك الخاصة لتوسيع OpenCode. تتيح لك الإضافات توسيع OpenCode عبر ربطها بأحداث مختلفة وتخصيص السلوك. يمكنك إنشاء إضافات لإضافة ميزات جديدة، أو التكامل مع خدمات خارجية، أو تعديل السلوك الافتراضي لـ OpenCode. للاطلاع على أمثلة، راجع [الإضافات](https://opencode.ai/docs/ecosystem#plugins) التي أنشأها المجتمع. * * * [استخدام إضافة](https://opencode.ai/docs/ar/plugins#%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85-%D8%A5%D8%B6%D8%A7%D9%81%D8%A9) ------------------------------------------------------------------------------------------------------------------------------- هناك طريقتان لتحميل الإضافات. * * * ### [من ملفات محلية](https://opencode.ai/docs/ar/plugins#%D9%85%D9%86-%D9%85%D9%84%D9%81%D8%A7%D8%AA-%D9%85%D8%AD%D9%84%D9%8A%D8%A9) ضع ملفات JavaScript أو TypeScript في دليل الإضافات. * `.opencode/plugins/` - إضافات على مستوى المشروع * `~/.config/opencode/plugins/` - إضافات عامة تُحمَّل الملفات في هذه الأدلة تلقائيا عند بدء التشغيل. * * * ### [من npm](https://opencode.ai/docs/ar/plugins#%D9%85%D9%86-npm) حدّد حزم npm في ملف الإعدادات. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} يتم دعم حزم npm العادية والحزم ذات النطاق (scoped). تصفّح الإضافات المتاحة في [النظام البيئي](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [كيفية تثبيت الإضافات](https://opencode.ai/docs/ar/plugins#%D9%83%D9%8A%D9%81%D9%8A%D8%A9-%D8%AA%D8%AB%D8%A8%D9%8A%D8%AA-%D8%A7%D9%84%D8%A5%D8%B6%D8%A7%D9%81%D8%A7%D8%AA) **إضافات npm** تُثبَّت تلقائيا باستخدام Bun عند بدء التشغيل. تُخزَّن الحزم واعتمادياتها مؤقتا في `~/.cache/opencode/node_modules/`. **الإضافات المحلية** تُحمَّل مباشرة من دليل الإضافات. لاستخدام حزم خارجية، يجب إنشاء `package.json` داخل دليل الإعدادات لديك (راجع [الاعتماديات](https://opencode.ai/docs/ar/plugins#dependencies) )، أو نشر الإضافة على npm ثم [إضافتها إلى إعداداتك](https://opencode.ai/docs/config#plugins) . * * * ### [ترتيب التحميل](https://opencode.ai/docs/ar/plugins#%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8-%D8%A7%D9%84%D8%AA%D8%AD%D9%85%D9%8A%D9%84) تُحمَّل الإضافات من جميع المصادر وتعمل جميع الخطافات بالتتابع. ترتيب التحميل هو: 1. إعدادات عامة (`~/.config/opencode/opencode.json`) 2. إعدادات المشروع (`opencode.json`) 3. دليل الإضافات العام (`~/.config/opencode/plugins/`) 4. دليل إضافات المشروع (`.opencode/plugins/`) تُحمَّل حزم npm المكررة ذات الاسم والإصدار نفسيهما مرة واحدة. ومع ذلك، تُحمَّل الإضافة المحلية وإضافة npm ذات الاسم المشابه كلتاهما بشكل مستقل. * * * [إنشاء إضافة](https://opencode.ai/docs/ar/plugins#%D8%A5%D9%86%D8%B4%D8%A7%D8%A1-%D8%A5%D8%B6%D8%A7%D9%81%D8%A9) ----------------------------------------------------------------------------------------------------------------- الإضافة هي **وحدة JavaScript/TypeScript** تصدّر دالة إضافة واحدة أو أكثر. تستقبل كل دالة كائنا للسياق وتعيد كائنا للخطافات. * * * ### [الاعتماديات](https://opencode.ai/docs/ar/plugins#%D8%A7%D9%84%D8%A7%D8%B9%D8%AA%D9%85%D8%A7%D8%AF%D9%8A%D8%A7%D8%AA) يمكن للإضافات المحلية والأدوات المخصصة استخدام حزم npm خارجية. أضف `package.json` إلى دليل الإعدادات لديك متضمنا الاعتماديات التي تحتاجها. { "dependencies": { "shescape": "^2.1.0" }} يشغّل OpenCode الأمر `bun install` عند بدء التشغيل لتثبيتها. بعد ذلك يمكن لإضافاتك وأدواتك استيرادها. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [البنية الأساسية](https://opencode.ai/docs/ar/plugins#%D8%A7%D9%84%D8%A8%D9%86%D9%8A%D8%A9-%D8%A7%D9%84%D8%A3%D8%B3%D8%A7%D8%B3%D9%8A%D8%A9) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} تستقبل دالة الإضافة ما يلي: * `project`: معلومات المشروع الحالي. * `directory`: دليل العمل الحالي. * `worktree`: مسار git worktree. * `client`: عميل SDK لـ opencode للتفاعل مع الذكاء الاصطناعي. * `$`: واجهة [shell API](https://bun.com/docs/runtime/shell) الخاصة بـ Bun لتنفيذ الأوامر. * * * ### [دعم TypeScript](https://opencode.ai/docs/ar/plugins#%D8%AF%D8%B9%D9%85-typescript) بالنسبة لإضافات TypeScript، يمكنك استيراد الأنواع من حزمة الإضافة: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [الأحداث](https://opencode.ai/docs/ar/plugins#%D8%A7%D9%84%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB) يمكن للإضافات الاشتراك في الأحداث كما هو موضح أدناه في قسم الأمثلة. فيما يلي قائمة بالأحداث المتاحة. #### [أحداث الأوامر](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D8%A3%D9%88%D8%A7%D9%85%D8%B1) * `command.executed` #### [أحداث الملفات](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D9%85%D9%84%D9%81%D8%A7%D8%AA) * `file.edited` * `file.watcher.updated` #### [أحداث التثبيت](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D8%AA%D8%AB%D8%A8%D9%8A%D8%AA) * `installation.updated` #### [أحداث LSP](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-lsp) * `lsp.client.diagnostics` * `lsp.updated` #### [أحداث الرسائل](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D8%B1%D8%B3%D8%A7%D8%A6%D9%84) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [أحداث الأذونات](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D8%A3%D8%B0%D9%88%D9%86%D8%A7%D8%AA) * `permission.asked` * `permission.replied` #### [أحداث الخادم](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D8%AE%D8%A7%D8%AF%D9%85) * `server.connected` #### [أحداث الجلسة](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D8%AC%D9%84%D8%B3%D8%A9) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [أحداث Todo](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-todo) * `todo.updated` #### [أحداث shell](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-shell) * `shell.env` #### [أحداث الأدوات](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D8%A7%D9%84%D8%A3%D8%AF%D9%88%D8%A7%D8%AA) * `tool.execute.after` * `tool.execute.before` #### [أحداث واجهة TUI](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AD%D8%AF%D8%A7%D8%AB-%D9%88%D8%A7%D8%AC%D9%87%D8%A9-tui) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [أمثلة](https://opencode.ai/docs/ar/plugins#%D8%A3%D9%85%D8%AB%D9%84%D8%A9) ---------------------------------------------------------------------------- فيما يلي بعض أمثلة الإضافات التي يمكنك استخدامها لتوسيع opencode. * * * ### [إرسال إشعارات](https://opencode.ai/docs/ar/plugins#%D8%A5%D8%B1%D8%B3%D8%A7%D9%84-%D8%A5%D8%B4%D8%B9%D8%A7%D8%B1%D8%A7%D8%AA) أرسل إشعارات عند وقوع أحداث معينة: 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"'` } }, }} نستخدم `osascript` لتشغيل AppleScript على macOS. هنا نستخدمه لإرسال إشعارات. * * * ### [حماية .env](https://opencode.ai/docs/ar/plugins#%D8%AD%D9%85%D8%A7%D9%8A%D8%A9-env) امنع opencode من قراءة ملفات `.env`: 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") } }, }} * * * ### [حقن متغيرات البيئة](https://opencode.ai/docs/ar/plugins#%D8%AD%D9%82%D9%86-%D9%85%D8%AA%D8%BA%D9%8A%D8%B1%D8%A7%D8%AA-%D8%A7%D9%84%D8%A8%D9%8A%D8%A6%D8%A9) احقن متغيرات البيئة في جميع عمليات تنفيذ shell (أدوات الذكاء الاصطناعي وterminal المستخدم): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [أدوات مخصصة](https://opencode.ai/docs/ar/plugins#%D8%A3%D8%AF%D9%88%D8%A7%D8%AA-%D9%85%D8%AE%D8%B5%D8%B5%D8%A9) يمكن للإضافات أيضا إضافة أدوات مخصصة إلى opencode: 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})` }, }), }, }} تقوم الدالة المساعدة `tool` بإنشاء أداة مخصصة يمكن لـ opencode استدعاؤها. تأخذ دالة مخطط Zod وتعيد تعريف أداة يتضمن: * `description`: ما الذي تفعله الأداة * `args`: مخطط Zod لوسائط الأداة * `execute`: الدالة التي تُشغَّل عند استدعاء الأداة ستكون أدواتك المخصصة متاحة لـ opencode إلى جانب الأدوات المضمنة. * * * ### [التسجيل](https://opencode.ai/docs/ar/plugins#%D8%A7%D9%84%D8%AA%D8%B3%D8%AC%D9%8A%D9%84) استخدم `client.app.log()` بدلا من `console.log` للتسجيل البنيوي: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} المستويات: `debug`, `info`, `warn`, `error`. راجع [توثيق SDK](https://opencode.ai/docs/sdk) للتفاصيل. * * * ### [خطافات الضغط](https://opencode.ai/docs/ar/plugins#%D8%AE%D8%B7%D8%A7%D9%81%D8%A7%D8%AA-%D8%A7%D9%84%D8%B6%D8%BA%D8%B7) خصّص السياق الذي يتم تضمينه عند ضغط جلسة: 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`) }, }} يعمل الخطاف `experimental.session.compacting` قبل أن ينشئ نموذج اللغة الكبير (LLM) ملخص المتابعة. استخدمه لحقن سياق خاص بالمجال قد يفوته موجّه الضغط الافتراضي. يمكنك أيضا استبدال موجّه الضغط بالكامل عبر ضبط `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} عند ضبط `output.prompt` فإنه يستبدل موجّه الضغط الافتراضي بالكامل. يتم تجاهل المصفوفة `output.context` في هذه الحالة. --- # プラグイン | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/plugins#_top) プラグイン ===== OpenCode を拡張する独自のプラグインを作成します。 プラグインを使用すると、さまざまなイベントにフックして動作をカスタマイズすることで OpenCode を拡張できます。プラグインを作成して、新しい機能を追加したり、外部サービスと統合したり、OpenCode のデフォルトの動作を変更したりできます。 たとえば、コミュニティによって作成された [plugins](https://opencode.ai/docs/ecosystem#plugins) をチェックしてください。 * * * [プラグインの使用](https://opencode.ai/docs/ja/plugins#%E3%83%97%E3%83%A9%E3%82%B0%E3%82%A4%E3%83%B3%E3%81%AE%E4%BD%BF%E7%94%A8) ------------------------------------------------------------------------------------------------------------------------- プラグインをロードするには 2 つの方法があります。 * * * ### [ローカルファイルから](https://opencode.ai/docs/ja/plugins#%E3%83%AD%E3%83%BC%E3%82%AB%E3%83%AB%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%8B%E3%82%89) JavaScript または TypeScript ファイルをプラグインディレクトリに配置します。 * `.opencode/plugins/` - プロジェクトレベルのプラグイン * `~/.config/opencode/plugins/` - グローバルプラグイン これらのディレクトリ内のファイルは起動時に自動的にロードされます。 * * * ### [npm から](https://opencode.ai/docs/ja/plugins#npm-%E3%81%8B%E3%82%89) 設定ファイルで npm パッケージを指定します。 { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} 通常の npm パッケージとスコープ指定された npm パッケージの両方がサポートされています。 [ecosystem](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [プラグインのインストール](https://opencode.ai/docs/ja/plugins#%E3%83%97%E3%83%A9%E3%82%B0%E3%82%A4%E3%83%B3%E3%81%AE%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB) **npm プラグイン** は、起動時に Bun を使用して自動的にインストールされます。パッケージとその依存関係は `~/.cache/opencode/node_modules/` にキャッシュされます。 **ローカルプラグイン**は、プラグインディレクトリから直接ロードされます。外部パッケージを使用するには、config ディレクトリ内に `package.json` を作成するか ([Dependency](https://opencode.ai/docs/ja/plugins#dependencies) を参照)、プラグインを npm に公開して [config](https://opencode.ai/docs/config#plugins) に追加する必要があります。 * * * ### [ロード順序](https://opencode.ai/docs/ja/plugins#%E3%83%AD%E3%83%BC%E3%83%89%E9%A0%86%E5%BA%8F) プラグインはすべてのソースからロードされ、すべてのフックが順番に実行されます。ロード順序は次のとおりです。 1. グローバル設定 (`~/.config/opencode/opencode.json`) 2. プロジェクト設定 (`opencode.json`) 3. グローバルプラグインディレクトリ (`~/.config/opencode/plugins/`) 4. プロジェクトプラグインディレクトリ (`.opencode/plugins/`) 同じ名前とバージョンを持つ重複した npm パッケージは 1 回ロードされます。ただし、似た名前のローカルプラグインと npm プラグインは両方とも別々にロードされます。 * * * [プラグインを作成する](https://opencode.ai/docs/ja/plugins#%E3%83%97%E3%83%A9%E3%82%B0%E3%82%A4%E3%83%B3%E3%82%92%E4%BD%9C%E6%88%90%E3%81%99%E3%82%8B) --------------------------------------------------------------------------------------------------------------------------------------------- プラグインは、1 つ以上のプラグインをエクスポートする **JavaScript/TypeScript モジュール**です。 各関数はコンテキストオブジェクトを受け取り、フックオブジェクトを返します。 * * * ### [依存関係](https://opencode.ai/docs/ja/plugins#%E4%BE%9D%E5%AD%98%E9%96%A2%E4%BF%82) ローカルプラグインとカスタムツールは外部の npm パッケージを使用できます。必要な依存関係を含む `package.json` を config ディレクトリに追加します。 { "dependencies": { "shescape": "^2.1.0" }} OpenCode は起動時に `bun install` を実行してこれらをインストールします。プラグインとツールはそれらをインポートできるようになります。 import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [基本構造](https://opencode.ai/docs/ja/plugins#%E5%9F%BA%E6%9C%AC%E6%A7%8B%E9%80%A0) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} プラグイン関数は以下を受け取ります。 * `project`: 現在のプロジェクト情報。 * `directory`: 現在の作業ディレクトリ。 * `worktree`: git ワークツリーのパス。 * `client`: AI と対話するための OpenCode SDK クライアント。 * `$`: Bun の [コマンドを実行するためのシェル API](https://bun.com/docs/runtime/shell) 。 * * * ### [TypeScript のサポート](https://opencode.ai/docs/ja/plugins#typescript-%E3%81%AE%E3%82%B5%E3%83%9D%E3%83%BC%E3%83%88) TypeScript プラグインの場合、プラグインパッケージから型をインポートできます。 import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [イベント](https://opencode.ai/docs/ja/plugins#%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) 以下の「例」セクションに示すように、プラグインはイベントをサブスクライブできます。利用可能なさまざまなイベントのリストは次のとおりです。 #### [コマンドイベント](https://opencode.ai/docs/ja/plugins#%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `command.executed` #### [ファイルイベント](https://opencode.ai/docs/ja/plugins#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `file.edited` * `file.watcher.updated` #### [インストールイベント](https://opencode.ai/docs/ja/plugins#%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `installation.updated` #### [LSPイベント](https://opencode.ai/docs/ja/plugins#lsp%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `lsp.client.diagnostics` * `lsp.updated` #### [メッセージイベント](https://opencode.ai/docs/ja/plugins#%E3%83%A1%E3%83%83%E3%82%BB%E3%83%BC%E3%82%B8%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [許可イベント](https://opencode.ai/docs/ja/plugins#%E8%A8%B1%E5%8F%AF%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `permission.asked` * `permission.replied` #### [サーバーイベント](https://opencode.ai/docs/ja/plugins#%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `server.connected` #### [セッションイベント](https://opencode.ai/docs/ja/plugins#%E3%82%BB%E3%83%83%E3%82%B7%E3%83%A7%E3%83%B3%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [ToDo イベント](https://opencode.ai/docs/ja/plugins#todo-%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `todo.updated` #### [シェルイベント](https://opencode.ai/docs/ja/plugins#%E3%82%B7%E3%82%A7%E3%83%AB%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `shell.env` #### [ツールイベント](https://opencode.ai/docs/ja/plugins#%E3%83%84%E3%83%BC%E3%83%AB%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `tool.execute.after` * `tool.execute.before` #### [TUIイベント](https://opencode.ai/docs/ja/plugins#tui%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [例](https://opencode.ai/docs/ja/plugins#%E4%BE%8B) --------------------------------------------------- ここでは、OpenCode を拡張するために使用できるプラグインの例をいくつか示します。 * * * ### [通知を送信する](https://opencode.ai/docs/ja/plugins#%E9%80%9A%E7%9F%A5%E3%82%92%E9%80%81%E4%BF%A1%E3%81%99%E3%82%8B) 特定のイベントが発生したときに通知を送信します。 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"'` } }, }} macOS 上で AppleScript を実行するために `osascript` を使用しています。ここでは通知を送信するために使用しています。 * * * ### [ロギング](https://opencode.ai/docs/ja/plugins#%E3%83%AD%E3%82%AE%E3%83%B3%E3%82%B0) 構造化ログには `console.log` の代わりに `client.app.log()` を使用します。 export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} レベル: `debug`、`info`、`warn`、`error`。詳細については、[SDK ドキュメント](https://opencode.ai/docs/sdk) を参照してください。 * * * ### [圧縮フック](https://opencode.ai/docs/ja/plugins#%E5%9C%A7%E7%B8%AE%E3%83%95%E3%83%83%E3%82%AF) セッションが圧縮されたときに含まれるコンテキストをカスタマイズします。 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`) }, }} `experimental.session.compacting` フックは、LLM が継続概要を生成する前に起動します。これを使用して、デフォルトの圧縮プロンプトでは見逃されるドメイン固有のコンテキストを挿入します。 `output.prompt` を設定することで、圧縮プロンプトを完全に置き換えることもできます。 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} `output.prompt` を設定すると、デフォルトの圧縮プロンプトが完全に置き換えられます。この場合、`output.context` 配列は無視されます。 * * * ### [.env の保護](https://opencode.ai/docs/ja/plugins#env-%E3%81%AE%E4%BF%9D%E8%AD%B7) OpenCode が `.env` ファイルを読み取らないようにします。 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") } }, }} * * * ### [環境変数を挿入する](https://opencode.ai/docs/ja/plugins#%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0%E3%82%92%E6%8C%BF%E5%85%A5%E3%81%99%E3%82%8B) すべてのシェル実行 (AI ツールとユーザーターミナル) に環境変数を挿入します。 export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [カスタムツール](https://opencode.ai/docs/ja/plugins#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%84%E3%83%BC%E3%83%AB) プラグインは OpenCode にカスタムツールを追加することもできます。 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})` }, }), }, }} `tool` ヘルパーは、OpenCode が呼び出すことができるカスタムツールを作成します。 Zod スキーマ関数を受け取り、次のようなツール定義を返します。 * `description`: ツールの機能 * `args`: ツールの引数の Zod スキーマ * `execute`: ツールが呼び出されたときに実行される関数 カスタムツールは、組み込みツールと並行して OpenCode で使用できます。 * * * ### [ロギング](https://opencode.ai/docs/ja/plugins#%E3%83%AD%E3%82%AE%E3%83%B3%E3%82%B0-1) 構造化ログには `client.app.log()` の代わりに `console.log` を使用します。 export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} レベル: `debug`、`info`、`warn`、`error`。詳細については、[SDK ドキュメント](https://opencode.ai/docs/sdk) を参照してください。 * * * ### [圧縮フック](https://opencode.ai/docs/ja/plugins#%E5%9C%A7%E7%B8%AE%E3%83%95%E3%83%83%E3%82%AF-1) セッションが圧縮されたときに含まれるコンテキストをカスタマイズします。 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`) }, }} `experimental.session.compacting` フックは、LLM が継続概要を生成する前に起動します。これを使用して、デフォルトの圧縮プロンプトでは見逃されるドメイン固有のコンテキストを挿入します。 `output.prompt` を設定することで、圧縮プロンプトを完全に置き換えることもできます。 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} `output.prompt` を設定すると、デフォルトの圧縮プロンプトが完全に置き換えられます。この場合、`output.context` 配列は無視されます。 --- # Web | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/web#_top) Web === Korzystanie z opencode w przeglądarce. opencode może działać jako aplikacja internetowa w przeglądarce, zapewniając takie same możliwości kodowania AI bez konieczności korzystania z terminala. ![Sieć opencode - Nowa sesja](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Pierwsze kroki](https://opencode.ai/docs/pl/web#pierwsze-kroki) ----------------------------------------------------------------- Uruchom interfejs sieciowy, uruchamiając: opencode web Spowoduje to uruchomienie lokalnego serwera na `127.0.0.1` z losowo dostępnym portem i automatyczne otwarcie opencode w domyślnej przeglądarce. * * * [Konfiguracja](https://opencode.ai/docs/pl/web#konfiguracja) ------------------------------------------------------------- Możesz skonfigurować serwer WWW za pomocą flag wiersza poleceń lub w \[pliku konfiguracyjnym\] (./config). ### [Port](https://opencode.ai/docs/pl/web#port) Domyślnie opencode wybiera dostępny port. Możesz określić port: opencode web --port 4096 ### [Nazwa hosta](https://opencode.ai/docs/pl/web#nazwa-hosta) Domyślnie serwer łączy się z `127.0.0.1` (tylko localhost). Aby udostępnić opencode w swojej sieci: opencode web --hostname 0.0.0.0 Podczas korzystania z `0.0.0.0` opencode wyświetli zarówno adresy lokalne, jak i sieciowe: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [Wykrywanie mDNS](https://opencode.ai/docs/pl/web#wykrywanie-mdns) Włącz mDNS, aby Twój serwer był wykrywalny w sieci lokalnej: opencode web --mdns To automatycznie ustawia nazwę hosta na `0.0.0.0` i anonsuje serwer jako `opencode.local`. Możesz dostosować nazwę domeny mDNS, aby uruchamiała wiele instancji w tej samej sieci: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/pl/web#cors) Aby zezwolić na dodatkowe domeny dla CORS (przydatne w przypadku niestandardowych interfejsów): opencode web --cors https://example.com ### [Uwierzytelnianie](https://opencode.ai/docs/pl/web#uwierzytelnianie) Aby chronić dostęp, ustaw hasło za pomocą zmiennej środowiskowej `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web Domyślna nazwa użytkownika to `opencode`, ale można ją zmienić za pomocą `OPENCODE_SERVER_USERNAME`. * * * [Korzystanie z interfejsu internetowego](https://opencode.ai/docs/pl/web#korzystanie-z-interfejsu-internetowego) ----------------------------------------------------------------------------------------------------------------- Po uruchomieniu interfejs sieciowy zapewnia dostęp do sesji opencode. ### [Sesje](https://opencode.ai/docs/pl/web#sesje) Przeglądaj sesje i zarządzaj nimi ze strony głównej. Możesz zobaczyć aktywne sesje i rozpocząć nowe. ![opencode Web - Aktywna sesja](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Stan serwera](https://opencode.ai/docs/pl/web#stan-serwera) Kliknij „Zobacz serwery”, aby wyświetlić podłączone serwery i ich status. ![opencode Web - See Servers](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Podłączanie terminala](https://opencode.ai/docs/pl/web#pod%C5%82%C4%85czanie-terminala) ----------------------------------------------------------------------------------------- Możesz podłączyć terminal TUI do działającego serwera WWW: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Umożliwia to jednoczesne korzystanie z interfejsu sieciowego i terminala, współdzieląc te same sesje i stan. * * * [Plik konfiguracyjny](https://opencode.ai/docs/pl/web#plik-konfiguracyjny) --------------------------------------------------------------------------- Możesz także skonfigurować ustawienia serwera w pliku konfiguracyjnym `opencode.json`: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Flagi wiersza poleceń mają pierwszeństwo przed ustawieniami pliku konfiguracyjnego. --- # Web | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/web#_top) Web === 브라우저에서 OpenCode 사용하기. opencode는 브라우저에서 웹 응용 프로그램을 실행할 수 있으며 terminal을 필요로하지 않고 동일한 강력한 AI 코딩 경험을 제공합니다. ![opencode Web - 새로운 세션](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [시작하기](https://opencode.ai/docs/ko/web#%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0) ----------------------------------------------------------------------------- 실행하여 웹 인터페이스를 시작: opencode web `127.0.0.1`의 로컬 서버를 랜덤 사용 가능한 포트로 시작하고 기본 브라우저에서 opencode를 자동으로 엽니다. * * * [구성](https://opencode.ai/docs/ko/web#%EA%B5%AC%EC%84%B1) --------------------------------------------------------- 명령줄 플래그 또는 [config file](https://opencode.ai/docs/config) 에서 웹 서버를 구성할 수 있습니다. [포트](https://opencode.ai/docs/ko/web#%ED%8F%AC%ED%8A%B8) --------------------------------------------------------- 기본적으로 opencode는 사용할 수 있는 포트를 선택합니다. 포트를 지정할 수 있습니다: opencode web --port 4096 [호스트 이름](https://opencode.ai/docs/ko/web#%ED%98%B8%EC%8A%A4%ED%8A%B8-%EC%9D%B4%EB%A6%84) ----------------------------------------------------------------------------------------- 기본적으로 서버는 `127.0.0.1` (localhost only)에 바인딩합니다. 네트워크에서 opencode를 사용할 수 있도록: opencode web --hostname 0.0.0.0 `0.0.0.0`를 사용할 때, opencode는 로컬 및 네트워크 주소를 모두 표시합니다. Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS 발견](https://opencode.ai/docs/ko/web#mdns-%EB%B0%9C%EA%B2%AC) 로컬 네트워크에서 서버를 발견할 수 있는 mDNS: opencode web --mdns 이 자동으로 `0.0.0.0`에 hostname을 설정하고 `opencode.local`로 서버를 광고합니다. 동일한 네트워크에서 여러 인스턴스를 실행하려면 mDNS 도메인 이름을 지정할 수 있습니다. opencode web --mdns --mdns-domain myproject.local ###### [CORS](https://opencode.ai/docs/ko/web#cors) CORS에 대한 추가 도메인을 허용하려면 (사용자 정의 frontends에 적합) : opencode web --cors https://example.com ### [인증](https://opencode.ai/docs/ko/web#%EC%9D%B8%EC%A6%9D) 액세스를 보호하려면 `OPENCODE_SERVER_PASSWORD` 환경 변수를 사용하여 암호를 설정하십시오. OPENCODE_SERVER_PASSWORD=secret opencode web `opencode`에 대한 사용자의 기본값은 `OPENCODE_SERVER_USERNAME`로 변경할 수 있습니다. * * * [웹 인터페이스 사용](https://opencode.ai/docs/ko/web#%EC%9B%B9-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4-%EC%82%AC%EC%9A%A9) ------------------------------------------------------------------------------------------------------------------------- 시작되면 웹 인터페이스는 opencode 세션에 액세스 할 수 있습니다. [세션](https://opencode.ai/docs/ko/web#%EC%84%B8%EC%85%98) --------------------------------------------------------- 홈페이지에서 세션을 보고 관리합니다. 활성 세션을 볼 수 있으며 새로운 것을 시작합니다. ![opencode Web - Active Session](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) [서버 상태](https://opencode.ai/docs/ko/web#%EC%84%9C%EB%B2%84-%EC%83%81%ED%83%9C) ------------------------------------------------------------------------------- “See Servers”를 클릭하여 연결된 서버와 상태를 볼 수 있습니다. ![opencode Web - Servers 참조](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [터미널 연결](https://opencode.ai/docs/ko/web#%ED%84%B0%EB%AF%B8%EB%84%90-%EC%97%B0%EA%B2%B0) ----------------------------------------------------------------------------------------- 실행 웹 서버에 terminal TUI를 연결할 수 있습니다. # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 웹 인터페이스와 terminal을 동시에 사용할 수 있도록, 같은 세션과 상태를 공유합니다. * * * [구성 파일](https://opencode.ai/docs/ko/web#%EA%B5%AC%EC%84%B1-%ED%8C%8C%EC%9D%BC) ------------------------------------------------------------------------------- `opencode.json` config 파일에서 서버 설정을 구성할 수 있습니다: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Command line flags는 config 파일 설정에 대한 precedence를 가져옵니다. --- # キーバインド | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/keybinds#_top) キーバインド ====== キーバインドをカスタマイズします。 OpenCode には、`tui.json` を通じてカスタマイズできるキーバインドのリストがあります。 { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [リーダーキー](https://opencode.ai/docs/ja/keybinds#%E3%83%AA%E3%83%BC%E3%83%80%E3%83%BC%E3%82%AD%E3%83%BC) ------------------------------------------------------------------------------------------------------ OpenCode は、ほとんどのキーバインドに `leader` キーを使用します。これにより、ターミナルでの競合が回避されます。 デフォルトでは、`ctrl+x` がリーダーキーであり、ほとんどの操作では、最初にリーダーキーを押してからショートカットを押す必要があります。たとえば、新しいセッションを開始するには、まず `ctrl+x` を押してから、`n` を押します。 キーバインドにリーダーキーを使用する必要はありませんが、そうすることをお勧めします。 * * * [キーバインドを無効にする](https://opencode.ai/docs/ja/keybinds#%E3%82%AD%E3%83%BC%E3%83%90%E3%82%A4%E3%83%B3%E3%83%89%E3%82%92%E7%84%A1%E5%8A%B9%E3%81%AB%E3%81%99%E3%82%8B) ------------------------------------------------------------------------------------------------------------------------------------------------------------------ キーバインドを無効にするには、値「none」を指定してキーを `tui.json` に追加します。 { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [デスクトッププロンプトのショートカット](https://opencode.ai/docs/ja/keybinds#%E3%83%87%E3%82%B9%E3%82%AF%E3%83%88%E3%83%83%E3%83%97%E3%83%97%E3%83%AD%E3%83%B3%E3%83%97%E3%83%88%E3%81%AE%E3%82%B7%E3%83%A7%E3%83%BC%E3%83%88%E3%82%AB%E3%83%83%E3%83%88) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode デスクトップアプリのプロンプト入力は、テキストを編集するための一般的な Readline/Emacs スタイルのショートカットをサポートしています。これらは組み込みであり、現在 `opencode.json` を介して構成することはできません。 | ショートカット | アクション | | --- | --- | | `ctrl+a` | 現在の行の先頭に移動 | | `ctrl+e` | 現在の行の末尾に移動 | | `ctrl+b` | カーソルを 1 文字前に移動 | | `ctrl+f` | カーソルを 1 文字後に移動 | | `alt+b` | カーソルを 1 単語前に移動 | | `alt+f` | カーソルを 1 単語後に移動 | | `ctrl+d` | カーソル下の文字を削除 | | `ctrl+k` | 行末まで強制終了 | | `ctrl+u` | 行の先頭までキル | | `ctrl+w` | 前の単語を削除 | | `alt+d` | 次の単語を削除 | | `ctrl+t` | 文字を入れ替える | | `ctrl+g` | ポップオーバーをキャンセル/実行中の応答を中止する | * * * [Shift+Enter](https://opencode.ai/docs/ja/keybinds#shiftenter) --------------------------------------------------------------- 一部のターミナルでは、デフォルトでは Enter キーを使用して修飾キーを送信しません。エスケープシーケンスとして `Shift+Enter` を送信するようにターミナルを設定する必要がある場合があります。 ### [Windows Terminal](https://opencode.ai/docs/ja/keybinds#windows-terminal) 次の場所で `settings.json` を開きます。 %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json これをルートレベルの `actions` 配列に追加します。 "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ これをルートレベルの `keybindings` 配列に追加します。\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ ファイルを保存し、Windows Terminal を再起動するか、新しいタブを開きます。 --- # Tastebindinger | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/keybinds#_top) Tastebindinger ============== Tilpass tastebindingene dine. OpenCode har en liste over tastebindinger som du kan tilpasse gjennom `tui.json`. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Leader-tast](https://opencode.ai/docs/nb/keybinds#leader-tast) ---------------------------------------------------------------- OpenCode bruker en `leader`\-tast for de fleste tastebindinger. Dette unngår konflikter i terminalen din. Som standard er `ctrl+x` ledertasten, og de fleste handlinger krever at du først trykker på ledertasten og deretter snarveien. For å starte en ny økt, trykker du for eksempel først `ctrl+x` og deretter `n`. Du trenger ikke å bruke en ledertast for tastebindingene dine, men vi anbefaler at du gjør det. * * * [Deaktivering av tastebindinger](https://opencode.ai/docs/nb/keybinds#deaktivering-av-tastebindinger) ------------------------------------------------------------------------------------------------------ Du kan deaktivere en tastebinding ved å legge til tasten til `tui.json` med en verdi på “none”. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Snarveier i skrivebordsappen](https://opencode.ai/docs/nb/keybinds#snarveier-i-skrivebordsappen) -------------------------------------------------------------------------------------------------- Prompt-feltet for OpenCode-skrivebordsappen støtter vanlige snarveier i Readline/Emacs-stil for redigering av tekst. Disse er innebygd og foreløpig ikke konfigurerbare via `opencode.json`. | Snarvei | Handling | | --- | --- | | `ctrl+a` | Flytt til starten av gjeldende linje | | `ctrl+e` | Flytt til slutten av gjeldende linje | | `ctrl+b` | Flytt markøren ett tegn tilbake | | `ctrl+f` | Flytt markøren ett tegn fremover | | `alt+b` | Flytt markøren ett ord tilbake | | `alt+f` | Flytt markøren ett ord fremover | | `ctrl+d` | Slett tegn under markøren | | `ctrl+k` | Slett til slutten av linjen | | `ctrl+u` | Slett til starten av linjen | | `ctrl+w` | Slett forrige ord | | `alt+d` | Slett neste ord | | `ctrl+t` | Bytt om tegn | | `ctrl+g` | Avbryt popovers / avbryt kjøring av svar | * * * [Shift+Enter](https://opencode.ai/docs/nb/keybinds#shiftenter) --------------------------------------------------------------- Noen terminaler sender ikke modifikasjonstaster med Enter som standard. Du må kanskje konfigurere terminalen til å sende `Shift+Enter` som en escape-sekvens. ### [Windows Terminal](https://opencode.ai/docs/nb/keybinds#windows-terminal) Åpne `settings.json` på: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Legg dette til `actions`\-matrisen på rotnivå: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Legg dette til `keybindings`\-matrisen på rotnivå:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Lagre filen og start Windows Terminal på nytt eller åpne en ny fane. --- # Tuş atamaları | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/keybinds#_top) Tuş atamaları ============= Tuş bağlantılarınızı özelleştirin. opencode, `tui.json` aracılığıyla özelleştirebileceğiniz bir tuş bağlantıları listesine sahiptir. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "leader": "ctrl+x", "app_exit": "ctrl+c,ctrl+d,q", "editor_open": "e", "theme_list": "t", "sidebar_toggle": "b", "scrollbar_toggle": "none", "username_toggle": "none", "status_view": "s", "tool_details": "none", "session_export": "x", "session_new": "n", "session_list": "l", "session_timeline": "g", "session_fork": "none", "session_rename": "none", "session_share": "none", "session_unshare": "none", "session_interrupt": "escape", "session_compact": "c", "session_child_cycle": "right", "session_child_cycle_reverse": "left", "session_parent": "up", "messages_page_up": "pageup,ctrl+alt+b", "messages_page_down": "pagedown,ctrl+alt+f", "messages_line_up": "ctrl+alt+y", "messages_line_down": "ctrl+alt+e", "messages_half_page_up": "ctrl+alt+u", "messages_half_page_down": "ctrl+alt+d", "messages_first": "ctrl+g,home", "messages_last": "ctrl+alt+g,end", "messages_next": "none", "messages_previous": "none", "messages_copy": "y", "messages_undo": "u", "messages_redo": "r", "messages_last_user": "none", "messages_toggle_conceal": "h", "model_list": "m", "model_cycle_recent": "f2", "model_cycle_recent_reverse": "shift+f2", "model_cycle_favorite": "none", "model_cycle_favorite_reverse": "none", "variant_cycle": "ctrl+t", "command_list": "ctrl+p", "agent_list": "a", "agent_cycle": "tab", "agent_cycle_reverse": "shift+tab", "input_clear": "ctrl+c", "input_paste": "ctrl+v", "input_submit": "return", "input_newline": "shift+return,ctrl+return,alt+return,ctrl+j", "input_move_left": "left,ctrl+b", "input_move_right": "right,ctrl+f", "input_move_up": "up", "input_move_down": "down", "input_select_left": "shift+left", "input_select_right": "shift+right", "input_select_up": "shift+up", "input_select_down": "shift+down", "input_line_home": "ctrl+a", "input_line_end": "ctrl+e", "input_select_line_home": "ctrl+shift+a", "input_select_line_end": "ctrl+shift+e", "input_visual_line_home": "alt+a", "input_visual_line_end": "alt+e", "input_select_visual_line_home": "alt+shift+a", "input_select_visual_line_end": "alt+shift+e", "input_buffer_home": "home", "input_buffer_end": "end", "input_select_buffer_home": "shift+home", "input_select_buffer_end": "shift+end", "input_delete_line": "ctrl+shift+d", "input_delete_to_line_end": "ctrl+k", "input_delete_to_line_start": "ctrl+u", "input_backspace": "backspace,shift+backspace", "input_delete": "ctrl+d,delete,shift+delete", "input_undo": "ctrl+-,super+z", "input_redo": "ctrl+.,super+shift+z", "input_word_forward": "alt+f,alt+right,ctrl+right", "input_word_backward": "alt+b,alt+left,ctrl+left", "input_select_word_forward": "alt+shift+f,alt+shift+right", "input_select_word_backward": "alt+shift+b,alt+shift+left", "input_delete_word_forward": "alt+d,alt+delete,ctrl+delete", "input_delete_word_backward": "ctrl+w,ctrl+backspace,alt+backspace", "history_previous": "up", "history_next": "down", "terminal_suspend": "ctrl+z", "terminal_title_toggle": "none", "tips_toggle": "h", "display_thinking": "none" }} * * * [Leader tuşu](https://opencode.ai/docs/tr/keybinds#leader-tu%C5%9Fu) --------------------------------------------------------------------- opencode çoğu tuş ataması için `leader` anahtarını kullanır. Bu, terminalinizdeki çakışmaları önler. Varsayılan olarak `ctrl+x` lider tuştur ve çoğu eylem önce lider tuşa, ardından kısayola basmanızı gerektirir. Örneğin, yeni bir oturum başlatmak için önce `ctrl+x` tuşuna, ardından `n` tuşuna basarsınız. Tuş atamalarınız için lider anahtar kullanmanıza gerek yoktur ancak bunu yapmanızı öneririz. * * * [Tuş atamasını devre dışı bırak](https://opencode.ai/docs/tr/keybinds#tu%C5%9F-atamas%C4%B1n%C4%B1-devre-d%C4%B1%C5%9F%C4%B1-b%C4%B1rak) ----------------------------------------------------------------------------------------------------------------------------------------- Anahtarı yapılandırmanıza “none” değeriyle ekleyerek bir tuş atamasını devre dışı bırakabilirsiniz. { "$schema": "https://opencode.ai/tui.json", "keybinds": { "session_compact": "none" }} * * * [Masaüstü istemi kısayolları](https://opencode.ai/docs/tr/keybinds#masa%C3%BCst%C3%BC-istemi-k%C4%B1sayollar%C4%B1) -------------------------------------------------------------------------------------------------------------------- opencode masaüstü uygulaması bilgi istemi girişi, metni düzenlemek için yaygın Readline/Emacs tarzı kısayolları destekler. Bunlar yerleşiktir ve şu anda `opencode.json` aracılığıyla yapılandırılamaz. | Shortcut | Action | | --- | --- | | `ctrl+a` | Geçerli satırın başına git | | `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` | Satırın başına kadar öldür | | `ctrl+w` | Kill previous word | | `alt+d` | Kill next word | | `ctrl+t` | Transpose characters | | `ctrl+g` | Cancel popovers / abort running response | * * * [Shift+Enter](https://opencode.ai/docs/tr/keybinds#shiftenter) --------------------------------------------------------------- Bazı terminaller varsayılan olarak Enter ile değiştirici tuşlar göndermez. Terminalinizi, kaçış dizisi olarak `Shift+Enter` gönderecek şekilde yapılandırmanız gerekebilir. ### [Windows Terminali](https://opencode.ai/docs/tr/keybinds#windows-terminali) `settings.json` cihazınızı şu adreste açın: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json Bunu kök düzeyindeki `actions` dizisine ekleyin: "actions": [ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "id": "User.sendInput.ShiftEnterCustom" }]\ \ Bunu kök düzeyindeki `keybindings` dizisine ekleyin:\ \ "keybindings": [ { "keys": "shift+enter", "id": "User.sendInput.ShiftEnterCustom" }]\ \ Dosyayı kaydedin ve Windows Terminalini yeniden başlatın veya yeni bir sekme açın. --- # Serwery LSP | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/lsp#_top) Serwery LSP =========== OpenCode integruje się z serwerami LSP. OpenCode integruje się z protokołem Language Server Protocol (LSP), aby zapewnić modelom LLM kontekst bazy kodu. Wykorzystuje diagnostykę, aby przekazywać informacje zwrotne do LLM. * * * [Wbudowane](https://opencode.ai/docs/pl/lsp#wbudowane) ------------------------------------------------------- OpenCode posiada kilka wbudowanych serwerów LSP dla następujących języków: | Serwer LSP | Rozszerzenia | Wymagania | | --- | --- | --- | | astro | .astro | Automatyczna instalacja dla Astro | | bash | .sh, .bash, .zsh, .ksh | Automatycznie instaluje serwer języka bash | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Automatyczna instalacja dla C/C++ | | csharp | .cs | Zainstalowany `.NET SDK` | | clojure-lsp | .clj, .cljs, .cljc, .edn | Dostępne polecenie `clojure-lsp` | | dart | .dart | Dostępne polecenie `dart` | | deno | .ts, .tsx, .js, .jsx, .mjs | Dostępne polecenie `deno` (automatyczne wykrywanie deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | Dostępne polecenie `elixir` | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | Zależność `eslint` w projekcie | | fsharp | .fs, .fsi, .fsx, .fsscript | Zainstalowany `.NET SDK` | | gleam | .gleam | Dostępne polecenie `gleam` | | gopls | .go | Dostępne polecenie `go` | | hls | .hs, .lhs | Dostępne polecenie `haskell-language-server-wrapper` | | jdtls | .java | Zainstalowany `Java SDK (version 21+)` | | julials | .jl | Zainstalowane `julia` i `LanguageServer.jl` | | kotlin-ls | .kt, .kts | Automatyczna instalacja dla Kotlin | | lua-ls | .lua | Automatyczna instalacja dla Lua | | nixd | .nix | Dostępne polecenie `nixd` | | ocaml-lsp | .ml, .mli | Dostępne polecenie `ocamllsp` | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | Zależność `oxlint` w projekcie | | php intelephense | .php | Automatyczna instalacja dla PHP | | prisma | .prisma | Dostępne polecenie `prisma` | | pyright | .py, .pyi | Zainstalowana zależność `pyright` | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Dostępne polecenie `ruby` i `gem` | | rust | .rs | Dostępne polecenie `rust-analyzer` | | sourcekit-lsp | .swift, .objc, .objcpp | Zainstalowany `swift` (`xcode` na macOS) | | svelte | .svelte | Automatyczna instalacja dla aplikacji Svelte | | terraform | .tf, .tfvars | Automatyczna instalacja z wydań GitHub | | tinymist | .typ, .typc | Automatyczna instalacja z wydań GitHub | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | Zależność `typescript` w projekcie | | vue | .vue | Automatyczna instalacja dla Vue | | yaml-ls | .yaml, .yml | Automatycznie instaluje serwer języka yaml Red Hat | | zls | .zig, .zon | Dostępne polecenie `zig` | Serwery LSP są automatycznie włączane po wykryciu jednego z obsługiwanych plików i spełnieniu wymagań. * * * [Jak to działa](https://opencode.ai/docs/pl/lsp#jak-to-dzia%C5%82a) -------------------------------------------------------------------- Gdy OpenCode otwiera plik: 1. Sprawdza plik pod kątem wszystkich dostępnych serwerów LSP. 2. Uruchamia odpowiedni serwer LSP, jeśli jeszcze nie działa. * * * [Konfiguracja](https://opencode.ai/docs/pl/lsp#konfiguracja) ------------------------------------------------------------- Możesz dostosować serwery LSP poprzez sekcję `lsp` w konfiguracji OpenCode. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Każdy serwer LSP obsługuje następujące właściwości: | Właściwość | Typ | Opis | | --- | --- | --- | | `disabled` | boolean | Ustaw na `true`, aby wyłączyć ten serwer LSP | | `command` | string\[\] | Polecenie uruchomienia serwera LSP | | `extensions` | string\[\] | Rozszerzenia plików, które powinny używać tego serwera | | `env` | object | Zmienne środowiskowe ustawiane podczas uruchamiania | | `initialization` | object | Opcje inicjalizacji do wysłania do serwera LSP | Spójrzmy na kilka przykładów. * * * ### [Zmienne środowiskowe](https://opencode.ai/docs/pl/lsp#zmienne-%C5%9Brodowiskowe) Użyj `env`, aby ustawić zmienne środowiskowe podczas uruchamiania serwera LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Opcje inicjalizacji](https://opencode.ai/docs/pl/lsp#opcje-inicjalizacji) Użyj właściwości `initialization`, aby przekazać niestandardowe opcje inicjalizacji do serwera LSP. Są one wysyłane w żądaniu `initialize` protokołu LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Wyłączanie serwerów LSP](https://opencode.ai/docs/pl/lsp#wy%C5%82%C4%85czanie-serwer%C3%B3w-lsp) Aby wyłączyć **wszystkie** serwery LSP globalnie, ustaw `lsp` na `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} Aby wyłączyć **określony** serwer LSP, ustaw `disabled` na `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Niestandardowe serwery LSP](https://opencode.ai/docs/pl/lsp#niestandardowe-serwery-lsp) Możesz dodać niestandardowe serwery LSP, podając polecenie i rozszerzenia plików: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Dodatkowe informacje](https://opencode.ai/docs/pl/lsp#dodatkowe-informacje) ----------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/pl/lsp#php-intelephense) PHP Intelephense oferuje funkcje premium poprzez klucz licencyjny. Możesz użyć klucza licencyjnego, umieszczając go (sam klucz) w pliku tekstowym pod adresem: * macOS/Linux: `$HOME/intelephense/license.txt` * Windows: `%USERPROFILE%/intelephense/license.txt` Plik powinien zawierać wyłącznie klucz licencyjny, bez białych znaków. --- # Serveurs LSP | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/lsp#_top) Serveurs LSP ============ OpenCode s'intègre à vos serveurs LSP. OpenCode s’intègre via le protocole LSP (Language Server Protocol) pour aider le LLM à interagir avec votre base de code. Il utilise des diagnostics pour fournir des commentaires au LLM. * * * [Serveurs intégrés](https://opencode.ai/docs/fr/lsp#serveurs-int%C3%A9gr%C3%A9s) --------------------------------------------------------------------------------- OpenCode est livré avec plusieurs serveurs LSP intégrés pour les langages populaires : | Serveur LSP | Extensions | Prérequis | | --- | --- | --- | | astro | .astro | Installation automatique pour les projets Astro | | bash | .sh, .bash, .zsh, .ksh | Installe automatiquement le serveur bash-language-server | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Installation automatique pour les projets C/C++ | | csharp | .cs | `.NET SDK` installé | | clojure-lsp | .clj, .cljs, .cljc, .edn | Commande `clojure-lsp` disponible | | dart | .dart | Commande `dart` disponible | | deno | .ts, .tsx, .js, .jsx, .mjs | Commande `deno` disponible (détection automatique deno.json/deno.jsonc) | | elixir-ls | .ex, .ex | Commande `elixir` disponible | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | Dépendance `eslint` dans le projet | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installé | | gleam | .gleam | Commande `gleam` disponible | | gopls | .go | Commande `go` disponible | | hls | .hs, .lhs | Commande `haskell-language-server-wrapper` disponible | | jdtls | .java | `Java SDK (version 21+)` installé | | julials | .jl | `julia` et `LanguageServer.jl` installés | | kotlin-ls | .kt, .kts | Installation automatique pour les projets Kotlin | | lua-ls | .lua | Installation automatique pour les projets Lua | | nixd | .nix | Commande `nixd` disponible | | ocaml-lsp | .ml, .mli | Commande `ocamllsp` disponible | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | Dépendance `oxlint` dans le projet | | php intelephense | .php | Installation automatique pour les projets PHP | | prisma | .prisma | Commande `prisma` disponible | | pyright | .py, .pyi | Dépendance `pyright` installée | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Commandes `ruby` et `gem` disponibles | | rust | .rs | Commande `rust-analyzer` disponible | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` installé (`xcode` sur macOS) | | svelte | .svelte | Installation automatique pour les projets Svelte | | terraform | .tf, .tfvars | Installation automatique à partir des versions GitHub | | tinymist | .typ, .typc | Installation automatique à partir des versions GitHub | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | Dépendance `typescript` dans le projet | | vue | .vue | Installation automatique pour les projets Vue | | yaml-ls | .yaml, .yml | Installe automatiquement le serveur yaml-language-server de Red Hat | | zls | .zig, .zon | Commande `zig` disponible | Les serveurs LSP sont automatiquement activés lorsque l’une des extensions de fichier ci-dessus est détectée et que les exigences sont remplies. * * * [Comment ça marche](https://opencode.ai/docs/fr/lsp#comment-%C3%A7a-marche) ---------------------------------------------------------------------------- Lorsque opencode ouvre un fichier, il : 1. Vérifie l’extension du fichier par rapport à tous les serveurs LSP activés. 2. Démarre le serveur LSP approprié s’il n’est pas déjà en cours d’exécution. * * * [Configuration](https://opencode.ai/docs/fr/lsp#configuration) --------------------------------------------------------------- Vous pouvez personnaliser les serveurs LSP via la section `lsp` de votre configuration opencode. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Chaque serveur LSP prend en charge les éléments suivants : | Propriété | Type | Description | | --- | --- | --- | | `disabled` | booléen | Définissez ceci sur `true` pour désactiver le serveur LSP | | `command` | chaîne\[\] | La commande pour démarrer le serveur LSP | | `extensions` | chaîne\[\] | Extensions de fichiers que ce serveur LSP doit gérer | | `env` | objet | Variables d’environnement à définir lors du démarrage du serveur | | `initialization` | objet | Options d’initialisation à envoyer au serveur LSP | Regardons quelques exemples. * * * ### [Variables d’environnement](https://opencode.ai/docs/fr/lsp#variables-denvironnement) Utilisez la propriété `env` pour définir les variables d’environnement lors du démarrage du serveur LSP : { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Options d’initialisation](https://opencode.ai/docs/fr/lsp#options-dinitialisation) Utilisez la propriété `initialization` pour transmettre les options d’initialisation au serveur LSP. Il s’agit de paramètres spécifiques au serveur envoyés lors de la requête LSP `initialize` : { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Désactivation des serveurs LSP](https://opencode.ai/docs/fr/lsp#d%C3%A9sactivation-des-serveurs-lsp) Pour désactiver **tous** les serveurs LSP globalement, définissez `lsp` sur `false` : { "$schema": "https://opencode.ai/config.json", "lsp": false} Pour désactiver un serveur LSP **spécifique**, définissez `disabled` sur `true` : { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Serveurs LSP personnalisés](https://opencode.ai/docs/fr/lsp#serveurs-lsp-personnalis%C3%A9s) Vous pouvez ajouter des serveurs LSP personnalisés en spécifiant les extensions de commande et de fichier : { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Informations supplémentaires](https://opencode.ai/docs/fr/lsp#informations-suppl%C3%A9mentaires) -------------------------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/fr/lsp#php-intelephense) PHP Intelephense offre des fonctionnalités premium via une clé de licence. Vous pouvez fournir une clé de licence en plaçant (uniquement) la clé dans un fichier texte à l’adresse : * macOS/Linux : `$HOME/intelephense/license.txt` * Windows : `%USERPROFILE%/intelephense/license.txt` Le fichier doit contenir uniquement la clé de licence sans contenu supplémentaire. --- # Servidores LSP | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/lsp#_top) Servidores LSP ============== OpenCode se integra con sus servidores LSP. OpenCode se integra con su protocolo de servidor de idiomas (LSP) para ayudar a LLM a interactuar con su código base. Utiliza diagnósticos para proporcionar retroalimentación al LLM. * * * [Incorporados](https://opencode.ai/docs/es/lsp#incorporados) ------------------------------------------------------------- OpenCode viene con varios servidores LSP integrados para idiomas populares: | Servidor LSP | Extensiones | Requisitos | | --- | --- | --- | | astro | .astro | Autoinstalaciones para proyectos Astro | | bash | .sh, .bash, .zsh, .ksh | Autoinstala el servidor en lenguaje bash | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Instalaciones automáticas para proyectos C/C++ | | csharp | .cs | `.NET SDK` instalado | | clojure-lsp | .clj, .cljs, .cljc, .edn | Comando `clojure-lsp` disponible | | dart | .dart | Comando `dart` disponible | | deno | .ts, .tsx, .js, .jsx, .mjs | Comando `deno` disponible (detecta automáticamente deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | Comando `elixir` disponible | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` dependencia en proyecto | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` instalado | | gleam | .gleam | Comando `gleam` disponible | | gopls | .go | Comando `go` disponible | | hls | .hs, .lhs | Comando `haskell-language-server-wrapper` disponible | | jdtls | .java | `Java SDK (version 21+)` instalado | | julials | .jl | `julia` y `LanguageServer.jl` instalados | | kotlin-ls | .kt, .kts | Autoinstalaciones para proyectos Kotlin | | lua-ls | .lua | Autoinstalaciones para proyectos Lua | | nixd | .nix | Comando `nixd` disponible | | ocaml-lsp | .ml, .mli | Comando `ocamllsp` disponible | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` dependencia en proyecto | | php intelephense | .php | Autoinstalaciones para proyectos PHP | | prisma | .prisma | Comando `prisma` disponible | | pyright | .py, .pyi | Dependencia `pyright` instalada | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Comandos `ruby` y `gem` disponibles | | rust | .rs | Comando `rust-analyzer` disponible | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` instalado (`xcode` en macOS) | | svelte | .svelte | Autoinstalaciones para proyectos Svelte | | terraform | .tf, .tfvars | Instalaciones automáticas desde versiones GitHub | | tinymist | .typ, .typc | Instalaciones automáticas desde versiones GitHub | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependencia en proyecto | | vue | .vue | Autoinstalaciones para proyectos Vue | | yaml-ls | .yaml, .yml | Autoinstala Red Hat yaml-language-server | | zls | .zig, .zon | Comando `zig` disponible | Los servidores LSP se habilitan automáticamente cuando se detecta una de las extensiones de archivo anteriores y se cumplen los requisitos. * * * [Cómo funciona](https://opencode.ai/docs/es/lsp#c%C3%B3mo-funciona) -------------------------------------------------------------------- Cuando opencode abre un archivo: 1. Comprueba la extensión del archivo con todos los servidores LSP habilitados. 2. Inicia el servidor LSP apropiado si aún no se está ejecutando. * * * [Configuración](https://opencode.ai/docs/es/lsp#configuraci%C3%B3n) -------------------------------------------------------------------- Puede personalizar los servidores LSP a través de la sección `lsp` en su configuración opencode. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Cada servidor LSP admite lo siguiente: | Propiedad | Tipo | Descripción | | --- | --- | --- | | `disabled` | booleano | Establezca esto en `true` para deshabilitar el servidor LSP | | `command` | cadena\[\] | El comando para iniciar el servidor LSP | | `extensions` | cadena\[\] | Extensiones de archivo que este servidor LSP debería manejar | | `env` | objeto | Variables de entorno para configurar al iniciar el servidor | | `initialization` | objeto | Opciones de inicialización para enviar al servidor LSP | Veamos algunos ejemplos. * * * ### [Variables de entorno](https://opencode.ai/docs/es/lsp#variables-de-entorno) Utilice la propiedad `env` para establecer variables de entorno al iniciar el servidor LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Opciones de inicialización](https://opencode.ai/docs/es/lsp#opciones-de-inicializaci%C3%B3n) Utilice la propiedad `initialization` para pasar opciones de inicialización al servidor LSP. Estas son configuraciones específicas del servidor enviadas durante la solicitud LSP `initialize`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Deshabilitar servidores LSP](https://opencode.ai/docs/es/lsp#deshabilitar-servidores-lsp) Para deshabilitar **todos** los servidores LSP globalmente, configure `lsp` en `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} Para deshabilitar un servidor LSP **específico**, configure `disabled` en `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Servidores LSP personalizados](https://opencode.ai/docs/es/lsp#servidores-lsp-personalizados) Puede agregar servidores LSP personalizados especificando el comando y las extensiones de archivo: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Información adicional](https://opencode.ai/docs/es/lsp#informaci%C3%B3n-adicional) ------------------------------------------------------------------------------------ ### [PHP Intelephense](https://opencode.ai/docs/es/lsp#php-intelephense) PHP Intelephense ofrece funciones premium a través de una clave de licencia. Puede proporcionar una clave de licencia colocando (únicamente) la clave en un archivo de texto en: * En macOS/Linux: `$HOME/intelephense/license.txt` * En Windows: `%USERPROFILE%/intelephense/license.txt` El archivo debe contener sólo la clave de licencia sin contenido adicional. --- # LSP-servere | OpenCode [Gå til indhold](https://opencode.ai/docs/da/lsp#_top) LSP-servere =========== OpenCode integreres med dine LSP-servere. OpenCode integreres med Language Server Protocol (LSP) for at hjælpe LLM med at interagere med din kodebase. Den bruger diagnostik til at give feedback til LLM. * * * [Indbyggede](https://opencode.ai/docs/da/lsp#indbyggede) --------------------------------------------------------- OpenCode leveres med flere indbyggede LSP-servere til populære sprog: | LSP Server | Udvidelser | Krav | | --- | --- | --- | | astro | .astro | Autoinstallationer til Astro-projekter | | bash | .sh,.bash,.zsh,.ksh | Autoinstallerer bash-language-server | | clangd | .c,.cpp,.cc,.cxx,.c++,.h,.hpp,.hh,.hxx,.h++ | Autoinstallationer for C/C++ projekter | | csharp | .cs | `.NET SDK` installere | | clojure-lsp | .clj,.cljs,.cljc,.edn | `clojure-lsp` kommando tilgængelig | | dart | .dart | `dart` kommando tilgængelig | | deno | .ts,.tsx,.js,.jsx,.mjs | `deno` kommando tilgængelig (auto-detects deno.json/deno.jsonc) | | elixir-ls | .ex,.exs | `elixir` kommando tilgængelig | | eslint | .ts,.tsx,.js,.jsx,.mjs,.cjs,.mts,.cts,.vue | `eslint` afhængighed i projekt | | fsharp | .fs,.fsi,.fsx,.fsscript | `.NET SDK` installere | | gleam | .gleam | `gleam` kommando tilgængelig | | gopls | .go | `go` kommando tilgængelig | | hls | .hs,.lhs | `haskell-language-server-wrapper` kommando tilgængelig | | jdtls | .java | `Java SDK (version 21+)` installere | | julials | .jl | `julia` og `LanguageServer.jl` installeret | | kotlin-ls | .kt,.kts | Autoinstallationer til Kotlin-projekter | | lua-ls | .lua | Autoinstallationer til Lua-projekter | | nixd | .nix | `nixd` kommando tilgængelig | | ocaml-lsp | .ml,.mli | `ocamllsp` kommando tilgængelig | | oxlint | .ts,.tsx,.js,.jsx,.mjs,.cjs,.mts,.cts,.vue,.astro,.svelte | `oxlint` afhængighed i projekt | | php intelephense | .php | Automatiske installationer til PHP-projekter | | prisma | .prisma | `prisma` kommando tilgængelig | | pyright | .py,.pyi | `pyright` afhængig installeret | | ruby-lsp (rubocop) | .rb,.rake,.gemspec,.ru | `ruby` og `gem` kommandoer tilgængelige | | rust | .rs | `rust-analyzer` kommando tilgængelig | | sourcekit-lsp | .swift,.objc,.objcpp | `swift` installere (`xcode` på macOS) | | svelte | .svelte | Autoinstallationer til Svelte-projekter | | terraform | .tf,.tfvars | Automatiske installationer fra GitHub-udgivelser | | tinymist | .typ,.typc | Automatiske installationer fra GitHub-udgivelser | | typescript | .ts,.tsx,.js,.jsx,.mjs,.cjs,.mts,.cts | `typescript` afhængighed i projekt | | vue | .vue | Autoinstallationer til Vue-projekter | | yaml-ls | .yaml,.yml | Autoinstallerer Red Hat yaml-language-server | | zls | .zig,.zon | `zig` kommando tilgængelig | LSP-servere aktiveres automatisk, når en af ​​ovenstående filtypenavne opdages, og kravene er opfyldt. * * * [Sådan fungerer det](https://opencode.ai/docs/da/lsp#s%C3%A5dan-fungerer-det) ------------------------------------------------------------------------------ Når opencode åbner en fil, vil den: 1. Kontrollerer filtypenavnet mod alle aktiverede LSP-servere. 2. Starter den relevante LSP-server, hvis den ikke allerede kører. * * * [Konfiguration](https://opencode.ai/docs/da/lsp#konfiguration) --------------------------------------------------------------- Du kan tilpasse LSP-servere gennem sektionen `lsp` i din opencode-konfiguration. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Hver LSP- server understøtter følgende: | Egenskab | Type | Beskrivelse | | --- | --- | --- | | `disabled` | boolean | Indstil dette til `true` for at deaktivere LSP-serveren | | `command` | string\[\] | Kommandoen til at starte LSP-serveren | | `extensions` | string\[\] | Filtypenavne, som denne LSP-server skal håndtere | | `env` | object | Miljøvariabler, der skal indstilles, når serveren starter | | `initialization` | object | Initialiseringsmuligheder for at sende til LSP-serveren | Lad os se på nogle eksempler. * * * ### [Miljøvariabler](https://opencode.ai/docs/da/lsp#milj%C3%B8variabler) Brug egenskaben `env` til at indstille miljøvariabler, når du starter LSP-serveren: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Initialiseringsmuligheder](https://opencode.ai/docs/da/lsp#initialiseringsmuligheder) Brug egenskaben `initialization` til at videregive initialiseringsindstillinger til LSP-serveren. Disse er serverspecifikke indstillinger sendt under LSP `initialize` anmodningen: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Deaktivering af LSP-servere](https://opencode.ai/docs/da/lsp#deaktivering-af-lsp-servere) For at deaktivere **alle** LSP-servere globalt, skal du indstille `lsp` til `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} For at deaktivere en **specifik** LSP-server skal du indstille `disabled` til `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Brugerdefinerede LSP-servere](https://opencode.ai/docs/da/lsp#brugerdefinerede-lsp-servere) Du kan tilføje brugerdefinerede LSP-servere ved at angive kommandoen og filtypenavne: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Yderligere oplysninger](https://opencode.ai/docs/da/lsp#yderligere-oplysninger) --------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/da/lsp#php-intelephense) PHP Intelephense tilbyder premium funktioner gennem en licensnøgle. Du kan angive en licensnøgle ved at placere (kun) nøglen i en tekstfil på: * På macOS/Linux: `$HOME/intelephense/license.txt` * På Windows: `%USERPROFILE%/intelephense/license.txt` Filen bør kun indeholde licensnøglen uden yderligere indhold. --- # Verktøy | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/tools#_top) Verktøy ======= Administrer verktøyene en LLM kan bruke. Verktøy lar LLM utføre handlinger i kodebasen din. OpenCode kommer med et sett med innebygde verktøy, men du kan utvide det med [egendefinerte verktøy](https://opencode.ai/docs/custom-tools) eller [MCP servere](https://opencode.ai/docs/mcp-servers) . Som standard er alle verktøy **aktivert** og trenger ikke tillatelse for å kjøre. Du kan kontrollere verktøyets oppførsel gjennom [tillatelser](https://opencode.ai/docs/permissions) . * * * [Konfigurasjon](https://opencode.ai/docs/nb/tools#konfigurasjon) ----------------------------------------------------------------- Bruk feltet `permission` for å kontrollere verktøyets oppførsel. Du kan tillate, avslå eller kreve godkjenning for hvert verktøy. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Du kan også bruke jokertegn for å kontrollere flere verktøy samtidig. For eksempel, for å kreve godkjenning for alle verktøy fra en MCP-server: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Finn ut mer](https://opencode.ai/docs/permissions) om konfigurering av tillatelser. * * * [Innebygd](https://opencode.ai/docs/nb/tools#innebygd) ------------------------------------------------------- Her er alle de innebygde verktøyene som er tilgjengelige i OpenCode. * * * ### [bash](https://opencode.ai/docs/nb/tools#bash) Utfør skallkommandoer i prosjektmiljøet ditt. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Dette verktøyet lar LLM kjøre terminalkommandoer som `npm install`, `git status` eller en hvilken som helst annen skallkommando. * * * ### [edit](https://opencode.ai/docs/nb/tools#edit) Endre eksisterende filer ved å bruke eksakte strengerstatninger. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Dette verktøyet utfører nøyaktige redigeringer av filer ved å erstatte eksakte teksttreff. Det er den primære måten LLM endrer kode på. * * * ### [write](https://opencode.ai/docs/nb/tools#write) Opprett nye filer eller overskriv eksisterende. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Bruk denne for å la LLM lage nye filer. Den vil overskrive eksisterende filer hvis de allerede eksisterer. * * * ### [read](https://opencode.ai/docs/nb/tools#read) Les filinnholdet fra kodebasen din. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Dette verktøyet leser filer og returnerer innholdet. Den støtter lesing av spesifikke linjeområder for store filer. * * * ### [grep](https://opencode.ai/docs/nb/tools#grep) Søk i filinnhold ved hjelp av regulære uttrykk. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Rask innholdssøk på tvers av kodebasen din. Støtter full regex-syntaks og filmønsterfiltrering. * * * ### [glob](https://opencode.ai/docs/nb/tools#glob) Finn filer etter mønstermatching. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Søk etter filer ved å bruke glob-mønstre som `**/*.js` eller `src/**/*.ts`. Returnerer samsvarende filbaner sortert etter endringstid. * * * ### [list](https://opencode.ai/docs/nb/tools#list) List filer og kataloger i en gitt bane. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Dette verktøyet viser kataloginnhold. Den aksepterer glob-mønstre for å filtrere resultater. * * * ### [lsp (eksperimentell)](https://opencode.ai/docs/nb/tools#lsp-eksperimentell) Samhandle med dine konfigurerte LSP-servere for å få kodeintelligens-funksjoner som definisjoner, referanser, hover-informasjon og kallhierarki. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Støttede operasjoner inkluderer `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` og `outgoingCalls`. For å konfigurere hvilke LSP-servere som er tilgjengelige for prosjektet ditt, se [LSP-servere](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/nb/tools#patch) Bruk patcher på filer. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Dette verktøyet bruker oppdateringsfiler til kodebasen din. Nyttig for å påføre diffs og patcher fra forskjellige kilder. * * * ### [skill](https://opencode.ai/docs/nb/tools#skill) Last inn en [ferdighet](https://opencode.ai/docs/skills) (en `SKILL.md` fil) og returner innholdet i samtalen. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/nb/tools#todowrite) Administrer gjøremålslister under kodingsøkter. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Oppretter og oppdaterer oppgavelister for å spore fremdrift under komplekse operasjoner. LLM bruker dette til å organisere flertrinnsoppgaver. * * * ### [todoread](https://opencode.ai/docs/nb/tools#todoread) Les eksisterende gjøremålslister. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Leser gjeldende gjøremålslistestatus. Brukes av LLM for å spore hvilke oppgaver som venter eller er fullført. * * * ### [webfetch](https://opencode.ai/docs/nb/tools#webfetch) Hent nettinnhold. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Lar LLM hente og lese nettsider. Nyttig for å slå opp dokumentasjon eller forske på nettressurser. * * * ### [websearch](https://opencode.ai/docs/nb/tools#websearch) Søk på nettet for informasjon. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Utfører nettsøk med Exa AI for å finne relevant informasjon på nettet. Nyttig for å undersøke emner, finne aktuelle hendelser eller samle informasjon utover treningsdataavbruddet. Ingen API-nøkkel kreves — verktøyet kobles direkte til Exa AIs vertsbaserte MCP-tjeneste uten autentisering. * * * ### [question](https://opencode.ai/docs/nb/tools#question) Still brukeren spørsmål under utførelse. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Dette verktøyet lar LLM stille spørsmål til brukeren under en oppgave. Det er nyttig for: * Samle brukerpreferanser eller krav * Avklarende tvetydige instruksjoner * Få beslutninger om gjennomføringsvalg * Tilbyr valg om hvilken retning du skal ta Hvert spørsmål inkluderer en overskrift, spørsmålsteksten og en liste over alternativer. Brukere kan velge fra de angitte alternativene eller skrive inn et tilpasset svar. Når det er flere spørsmål, kan brukerne navigere mellom dem før de sender inn alle svarene. * * * [Egendefinerte verktøy](https://opencode.ai/docs/nb/tools#egendefinerte-verkt%C3%B8y) -------------------------------------------------------------------------------------- Egendefinerte verktøy lar deg definere dine egne funksjoner som LLM kan kalle. Disse er definert i konfigurasjonsfilen din og kan kjøre vilkårlig kode. [Finn ut mer](https://opencode.ai/docs/custom-tools) om å lage tilpassede verktøy. * * * [MCP servere](https://opencode.ai/docs/nb/tools#mcp-servere) ------------------------------------------------------------- MCP (Model Context Protocol) servere lar deg integrere eksterne verktøy og tjenester. Dette inkluderer databasetilgang, API-integrasjoner og tredjepartstjenester. [Les mer](https://opencode.ai/docs/mcp-servers) om konfigurering av MCP-servere. * * * [Internaler](https://opencode.ai/docs/nb/tools#internaler) ----------------------------------------------------------- Internt bruker verktøy som `grep`, `glob` og `list` [ripgrep](https://github.com/BurntSushi/ripgrep) i bakgrunnen. Som standard respekterer ripgrep `.gitignore`\-mønstre, noe som betyr at filer og kataloger som er oppført i `.gitignore` vil bli ekskludert fra søk og oppføringer. * * * ### [Ignorer mønstre](https://opencode.ai/docs/nb/tools#ignorer-m%C3%B8nstre) For å inkludere filer som normalt vil bli ignorert, lag en `.ignore`\-fil i prosjektroten. Denne filen kan eksplisitt tillate visse stier. !node_modules/!dist/!build/ For eksempel lar denne `.ignore` filen ripgrep søke i `node_modules/`, `dist/` og `build/` kataloger selv om de er oppført i `.gitignore`. --- # Værktøjer | OpenCode [Gå til indhold](https://opencode.ai/docs/da/tools#_top) Værktøjer ========= Administrer de værktøjer, en LLM kan bruge. Verktøy lar LLM utføre handlinger i kodebasen din. OpenCode kommer med et sett med innebygde verktøy, men du kan utvide det med [egendefinerte verktøy](https://opencode.ai/docs/custom-tools) eller [MCP servere](https://opencode.ai/docs/mcp-servers) . Som standard er alle verktøy **aktivert** og trenger ikke tillatelse for at kjøre. Du kan kontrollere verktøyets oppførsel gjennom [tillatelser](https://opencode.ai/docs/permissions) . * * * [Konfiguration](https://opencode.ai/docs/da/tools#konfiguration) ----------------------------------------------------------------- Brug feltet `permission` for at kontrollere verktøyets oppførsel. Du kan tillate, avslå eller kreve godkjenning for hvert verktøy. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Du kan også bruge jokertegn for at kontrollere flere verktøy samtidig. For eksempel, for at kreve godkjenning for alle verktøy fra en MCP-server: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Finn ut mer](https://opencode.ai/docs/permissions) om konfigurering av tillatelser. * * * [Indbyggede](https://opencode.ai/docs/da/tools#indbyggede) ----------------------------------------------------------- Her er alle de innebygde verktøyene som er tilgængelige i OpenCode. * * * ### [bash](https://opencode.ai/docs/da/tools#bash) Utfør shellkommandoer i prosjektmiljøet ditt. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Dette verktøyet lar LLM kjøre terminalkommandoer som `npm install`, `git status` eller en hvilken som helst annen shell-kommando. * * * ### [edit](https://opencode.ai/docs/da/tools#edit) Endre eksisterende filer ved at bruge eksakte strengerstatninger. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Dette verktøyet utfører nøyaktige redigeringer av filer ved at erstatte eksakte teksttreff. Det er den primære måten LLM endrer kode på. * * * ### [write](https://opencode.ai/docs/da/tools#write) Opret nye filer eller overskriv eksisterende. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Brug denne for at la LLM lage nye filer. Den vil overskrive eksisterende filer hvis de allerede eksisterer. * * * ### [read](https://opencode.ai/docs/da/tools#read) Les filinnholdet fra kodebasen din. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Dette verktøyet leser filer og returnerer innholdet. Den støtter lesing av spesifikke linjeområder for store filer. * * * ### [grep](https://opencode.ai/docs/da/tools#grep) Søk i filinnhold ved hjelp av regulære uttrykk. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Rask innholdssøk på tvers av kodebasen din. Støtter full regex-syntaks og filmønsterfiltrering. * * * ### [glob](https://opencode.ai/docs/da/tools#glob) Finn filer etter mønstermatching. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Søk etter filer ved at bruge glob-mønstre som `**/*.js` eller `src/**/*.ts`. Returnerer samsvarende filbaner sortert etter endringstid. * * * ### [list](https://opencode.ai/docs/da/tools#list) List filer og kataloger i en gitt bane. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Dette verktøyet viser kataloginnhold. Den aksepterer glob-mønstre for at filtrere resultater. * * * ### [lsp (experimental)](https://opencode.ai/docs/da/tools#lsp-experimental) Samhandle med dine konfigurerte LSP-servere for at få kodeintelligensfunksjoner som definisjoner, referanser, sveveinformasjon og anropshierarki. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Støttede operasjoner inkluderer `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` og `outgoingCalls`. For at konfigurere hvilke LSP-servere som er tilgængelige for prosjektet ditt, se [LSP-servere](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/da/tools#patch) Brug patcher på filer. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Dette verktøyet bruger opdateringsfiler til kodebasen din. Nyttig for at påføre diff og lapper fra forskjellige kilder. * * * ### [skill](https://opencode.ai/docs/da/tools#skill) Last inn en [ferdighet](https://opencode.ai/docs/skills) (en `SKILL.md` fil) og returner innholdet i samtalen. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/da/tools#todowrite) Administrer to-doslister under kodingssessioner. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Opreter og opdaterer oppgavelister for at spore fremdrift under komplekse operasjoner. LLM bruger dette til at organisere flertrinnsoppgaver. * * * ### [todoread](https://opencode.ai/docs/da/tools#todoread) Les eksisterende to-doslister. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Leser nuværende to-doslistestatus. Bruges av LLM for at spore hvilke oppgaver som venter eller er fullført. * * * ### [webfetch](https://opencode.ai/docs/da/tools#webfetch) Hent nettinnhold. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Lar LLM hente og lese nettsider. Nyttig for at slå opp dokumentasjon eller forske på nettressurser. * * * ### [websearch](https://opencode.ai/docs/da/tools#websearch) Søk på nettet for informasjon. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Utfører nettsøk med Exa AI for at finne relevant informasjon på nettet. Nyttig for at undersøke emner, finne aktuelle hendelser eller samle informasjon utover treningsdataavbruddet. Ingen API-nøgle kreves — verktøyet kobles direkte til Exa AIs vertsbaserte MCP-tjeneste uten autentisering. * * * ### [question](https://opencode.ai/docs/da/tools#question) Still brugeren spørsmål under utførelse. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Dette verktøyet lar LLM stille spørsmål til brugeren under en oppgave. Det er nyttig for: * Samle brugerpreferanser eller krav * Avklarende tvetydige instruksjoner * Få beslutninger om gjennomføringsvalg * Tilbyr valg om hvilken retning du skal ta Hvert spørsmål inkluderer en overskrift, spørsmålsteksten og en liste over alternativer. Brugere kan velge fra de angitte alternativene eller skrive inn et brugerdefineret svar. Når det er flere spørsmål, kan brugerne navigere mellom dem før de sender inn alle svarene. * * * [Brugerdefinerede værktøjer](https://opencode.ai/docs/da/tools#brugerdefinerede-v%C3%A6rkt%C3%B8jer) ----------------------------------------------------------------------------------------------------- Egendefinerte verktøy lar deg definere dine egne funksjoner som LLM kan kalle. Disse er definert i konfigurasjonsfilen din og kan kjøre vilkårlig kode. [Finn ut mer](https://opencode.ai/docs/custom-tools) om at lage tilpassede verktøy. * * * [MCP-servere](https://opencode.ai/docs/da/tools#mcp-servere) ------------------------------------------------------------- MCP (Model Context Protocol) servere lar deg integrere eksterne verktøy og tjenester. Dette inkluderer databasetilgang, API-integrasjoner og tredjepartstjenester. [Les mer](https://opencode.ai/docs/mcp-servers) om konfigurering av MCP-servere. * * * [Interne](https://opencode.ai/docs/da/tools#interne) ----------------------------------------------------- Internt bruger verktøy som `grep`, `glob` og `list` [ripgrep](https://github.com/BurntSushi/ripgrep) under panseret. Som standard respekterer ripgrep `.gitignore`\-mønstre, noe som betyr at filer og kataloger som er oppført i `.gitignore` vil bli ekskludert fra søk og lister. * * * ### [Ignoreringsmønstre](https://opencode.ai/docs/da/tools#ignoreringsm%C3%B8nstre) For at inkludere filer som normalt vil bli ignorert, lag en `.ignore`\-fil i prosjektroten. Denne filen kan eksplisitt tillate visse stier. !node_modules/!dist/!build/ For eksempel lar denne `.ignore` filen ripgrep søke i `node_modules/`, `dist/` og `build/` kataloger selv om de er oppført i `.gitignore`. --- # Dépannage | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/troubleshooting#_top) Dépannage ========= Problèmes courants et comment les résoudre. Pour déboguer les problèmes avec OpenCode, commencez par vérifier les journaux et les données locales qu’il stocke sur le disque. * * * [Journaux](https://opencode.ai/docs/fr/troubleshooting#journaux) ----------------------------------------------------------------- Les fichiers journaux sont écrits dans : * **macOS/Linux** : `~/.local/share/opencode/log/` * **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.local\share\opencode\log` Les fichiers journaux sont nommés avec des horodatages (par exemple, `2025-01-09T123456.log`) et les 10 fichiers journaux les plus récents sont conservés. Vous pouvez définir le niveau de journalisation avec l’option de ligne de commande `--log-level` pour obtenir des informations de débogage plus détaillées. Par exemple, `opencode --log-level DEBUG`. * * * [Stockage](https://opencode.ai/docs/fr/troubleshooting#stockage) ----------------------------------------------------------------- opencode stocke les données de session et autres données d’application sur le disque à l’emplacement : * **macOS/Linux** : `~/.local/share/opencode/` * **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.local\share\opencode` Ce répertoire contient : * `auth.json` - Données d’authentification telles que les clés API, les jetons OAuth * `log/` - Journaux d’applications * `project/` - Données spécifiques au projet telles que les données de session et de message * Si le projet se trouve dans un dépôt Git, il est stocké dans `.//storage/` * S’il ne s’agit pas d’un dépôt Git, il est stocké dans `./global/storage/` * * * [Application de bureau](https://opencode.ai/docs/fr/troubleshooting#application-de-bureau) ------------------------------------------------------------------------------------------- OpenCode Desktop exécute un serveur OpenCode local (le side-car `opencode-cli`) en arrière-plan. La plupart des problèmes sont causés par un plugin qui se comporte mal, un cache corrompu ou un mauvais paramètre du serveur. ### [Vérifications rapides](https://opencode.ai/docs/fr/troubleshooting#v%C3%A9rifications-rapides) * Quittez complètement et relancez l’application. * Si l’application affiche un écran d’erreur, cliquez sur **Redémarrer** et copiez les détails de l’erreur. * macOS uniquement : menu `OpenCode` -> **Recharger la vue Web** (aide si l’interface utilisateur est vide/gelée). * * * ### [Désactiver les plugins](https://opencode.ai/docs/fr/troubleshooting#d%C3%A9sactiver-les-plugins) Si l’application de bureau plante au lancement, se bloque ou se comporte étrangement, commencez par désactiver les plugins. #### [Vérifiez la configuration globale](https://opencode.ai/docs/fr/troubleshooting#v%C3%A9rifiez-la-configuration-globale) Ouvrez votre fichier de configuration global et recherchez une clé `plugin`. * **macOS/Linux** : `~/.config/opencode/opencode.jsonc` (ou `~/.config/opencode/opencode.json`) * **macOS/Linux** (anciennes installations) : `~/.local/share/opencode/opencode.jsonc` * **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.config\opencode\opencode.jsonc` Si vous avez configuré des plugins, désactivez-les temporairement en supprimant la clé ou en la définissant sur un tableau vide : { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Vérifiez les répertoires des plugins](https://opencode.ai/docs/fr/troubleshooting#v%C3%A9rifiez-les-r%C3%A9pertoires-des-plugins) OpenCode peut également charger des plugins locaux à partir du disque. Écartez-les temporairement (ou renommez le dossier) et redémarrez l’application de bureau : * **Plugins mondiaux** * **macOS/Linux** : `~/.config/opencode/plugins/` * **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.config\opencode\plugins` * **Plugins de projet** (uniquement si vous utilisez une configuration par projet) * `/.opencode/plugins/` Si l’application recommence à fonctionner, réactivez les plugins un par un pour trouver celui à l’origine du problème. * * * ### [Vider le cache](https://opencode.ai/docs/fr/troubleshooting#vider-le-cache) Si la désactivation des plugins ne résout pas le problème (ou si l’installation d’un plugin est bloquée), videz le cache afin que OpenCode puisse le reconstruire. 1. Quittez complètement OpenCode Desktop. 2. Supprimez le répertoire cache : * **macOS** : Finder -> `Cmd+Shift+G` -> coller `~/.cache/opencode` * **Linux** : supprimez `~/.cache/opencode` (ou exécutez `rm -rf ~/.cache/opencode`) * **Windows** : appuyez sur `WIN+R` et collez `%USERPROFILE%\.cache\opencode` 3. Redémarrez le bureau OpenCode. * * * ### [Résoudre les problèmes de connexion au serveur](https://opencode.ai/docs/fr/troubleshooting#r%C3%A9soudre-les-probl%C3%A8mes-de-connexion-au-serveur) OpenCode Desktop peut soit démarrer son propre serveur local (par défaut), soit se connecter à un serveur URL que vous avez configuré. Si vous voyez une boîte de dialogue **« Échec de la connexion »** (ou si l’application ne dépasse jamais l’écran de démarrage), recherchez un serveur personnalisé URL. #### [Effacer le serveur par défaut du bureau URL](https://opencode.ai/docs/fr/troubleshooting#effacer-le-serveur-par-d%C3%A9faut-du-bureau-url) Depuis l’écran d’accueil, cliquez sur le nom du serveur (avec le point d’état) pour ouvrir le sélecteur de serveur. Dans la section **Serveur par défaut**, cliquez sur **Effacer**. #### [Supprimez `server.port` / `server.hostname` de votre configuration](https://opencode.ai/docs/fr/troubleshooting#supprimez-serverport--serverhostname-de-votre-configuration) Si votre `opencode.json(c)` contient une section `server`, supprimez-la temporairement et redémarrez l’application de bureau. #### [Vérifier les variables d’environnement](https://opencode.ai/docs/fr/troubleshooting#v%C3%A9rifier-les-variables-denvironnement) Si `OPENCODE_PORT` est défini dans votre environnement, l’application de bureau tentera d’utiliser ce port pour le serveur local. * Désactivez `OPENCODE_PORT` (ou choisissez un port libre) et redémarrez. * * * ### [Linux : Problèmes Wayland / X11](https://opencode.ai/docs/fr/troubleshooting#linux-probl%C3%A8mes-wayland--x11) Sur Linux, certaines configurations Wayland peuvent provoquer des fenêtres vides ou des erreurs de composition. * Si vous êtes sur Wayland et que l’application est vide/plante, essayez de la lancer avec `OC_ALLOW_WAYLAND=1`. * Si cela aggrave les choses, supprimez-le et essayez plutôt de le lancer sous une session X11. * * * ### [Windows : exécution WebView2](https://opencode.ai/docs/fr/troubleshooting#windows-ex%C3%A9cution-webview2) Sur Windows, OpenCode Desktop nécessite Microsoft Edge **WebView2 Runtime**. Si l’application s’ouvre sur une fenêtre vide ou ne démarre pas, installez/mettez à jour WebView2 et réessayez. * * * ### [Windows : problèmes de performances généraux](https://opencode.ai/docs/fr/troubleshooting#windows-probl%C3%A8mes-de-performances-g%C3%A9n%C3%A9raux) Si vous rencontrez des performances lentes, des problèmes d’accès aux fichiers ou des problèmes de terminal sur Windows, essayez d’utiliser [WSL (Windows Sous-système pour Linux)](https://opencode.ai/docs/windows-wsl) . WSL fournit un environnement Linux qui fonctionne de manière plus transparente avec les fonctionnalités de OpenCode. * * * ### [Les notifications ne s’affichent pas](https://opencode.ai/docs/fr/troubleshooting#les-notifications-ne-saffichent-pas) OpenCode Desktop affiche uniquement les notifications système lorsque : * les notifications sont activées pour OpenCode dans les paramètres de votre système d’exploitation, et * la fenêtre de l’application n’est pas ciblée. * * * ### [Réinitialiser le stockage des applications de bureau (dernier recours)](https://opencode.ai/docs/fr/troubleshooting#r%C3%A9initialiser-le-stockage-des-applications-de-bureau-dernier-recours) Si l’application ne démarre pas et que vous ne pouvez pas effacer les paramètres depuis l’interface utilisateur, réinitialisez l’état enregistré de l’application de bureau. 1. Quittez le bureau OpenCode. 2. Recherchez et supprimez ces fichiers (ils se trouvent dans le répertoire de données de l’application OpenCode Desktop) : * `opencode.settings.dat` (serveur de bureau par défaut URL) * `opencode.global.dat` et `opencode.workspace.*.dat` (état de l’interface utilisateur comme les serveurs/projets récents) Pour trouver rapidement le répertoire : * **macOS** : Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (puis recherchez les noms de fichiers ci-dessus) * **Linux** : recherchez sous `~/.local/share` les noms de fichiers ci-dessus * **Windows** : appuyez sur `WIN+R` -> `%APPDATA%` (puis recherchez les noms de fichiers ci-dessus) * * * [Obtenir de l’aide](https://opencode.ai/docs/fr/troubleshooting#obtenir-de-laide) ---------------------------------------------------------------------------------- Si vous rencontrez des problèmes avec OpenCode : 1. **Signaler les problèmes le GitHub** La meilleure façon de signaler des bogues ou de demander des fonctionnalités consiste à utiliser notre référentiel GitHub : [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Avant de créer un nouveau problème, recherchez les problèmes existants pour voir si votre problème a déjà été signalé. 2. **Rejoignez notre Discord** Pour obtenir de l’aide en temps réel et une discussion communautaire, rejoignez notre serveur Discord : [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Problèmes courants](https://opencode.ai/docs/fr/troubleshooting#probl%C3%A8mes-courants) ------------------------------------------------------------------------------------------ Voici quelques problèmes courants et comment les résoudre. * * * ### [OpenCode ne démarre pas](https://opencode.ai/docs/fr/troubleshooting#opencode-ne-d%C3%A9marre-pas) 1. Vérifiez les journaux pour les messages d’erreur 2. Essayez d’exécuter avec `--print-logs` pour voir la sortie dans le terminal 3. Assurez-vous d’avoir la dernière version avec `opencode upgrade` * * * ### [Problèmes d’authentification](https://opencode.ai/docs/fr/troubleshooting#probl%C3%A8mes-dauthentification) 1. Essayez de vous réauthentifier avec la commande `/connect` dans le TUI 2. Vérifiez que vos clés API sont valides 3. Assurez-vous que votre réseau autorise les connexions au API du fournisseur. * * * ### [Modèle non disponible](https://opencode.ai/docs/fr/troubleshooting#mod%C3%A8le-non-disponible) 1. Vérifiez que vous êtes authentifié auprès du fournisseur 2. Vérifiez que le nom du modèle dans votre configuration est correct 3. Certains modèles peuvent nécessiter un accès ou des abonnements spécifiques Si vous rencontrez `ProviderModelNotFoundError`, vous avez probablement tort faire référence à un modèle quelque part. Les modèles doivent être référencés comme suit : `/` Exemples : * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` Pour déterminer à quels modèles vous avez accès, exécutez `opencode models` * * * ### [ErreurInit du fournisseur](https://opencode.ai/docs/fr/troubleshooting#erreurinit-du-fournisseur) Si vous rencontrez une ProviderInitError, vous avez probablement une configuration non valide ou corrompue. Pour résoudre ce problème : 1. Tout d’abord, vérifiez que votre fournisseur est correctement configuré en suivant le [guide du fournisseur](https://opencode.ai/docs/providers) 2. Si le problème persiste, essayez d’effacer votre configuration stockée : rm -rf ~/.local/share/opencode Sur Windows, appuyez sur `WIN+R` et supprimez : `%USERPROFILE%\.local\share\opencode` 3. Ré-authentifiez-vous auprès de votre fournisseur à l’aide de la commande `/connect` dans le TUI. * * * ### [Problèmes liés à AI\_APICallError et au package du fournisseur](https://opencode.ai/docs/fr/troubleshooting#probl%C3%A8mes-li%C3%A9s-%C3%A0-ai_apicallerror-et-au-package-du-fournisseur) Si vous rencontrez des erreurs d’appel API, cela peut être dû à des packages de fournisseurs obsolètes. opencode installe dynamiquement les packages du fournisseur (OpenAI, Anthropic, Google, etc.) selon les besoins et les met en cache localement. Pour résoudre les problèmes liés au package du fournisseur : 1. Videz le cache du package du fournisseur : rm -rf ~/.cache/opencode Sur Windows, appuyez sur `WIN+R` et supprimez : `%USERPROFILE%\.cache\opencode` 2. Redémarrez opencode pour réinstaller les derniers packages du fournisseur Cela forcera opencode à télécharger les versions les plus récentes des packages du fournisseur, ce qui résout souvent les problèmes de compatibilité avec les paramètres du modèle et les modifications de API. * * * ### [Le copier/coller ne fonctionne pas sur Linux](https://opencode.ai/docs/fr/troubleshooting#le-copiercoller-ne-fonctionne-pas-sur-linux) Les utilisateurs de Linux doivent disposer de l’un des utilitaires de presse-papiers suivants installés pour que la fonctionnalité copier/coller fonctionne : **Pour les systèmes X11 :** apt install -y xclip# orapt install -y xsel **Pour les systèmes Wayland :** apt install -y wl-clipboard **Pour les environnements sans tête :** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode détectera si vous utilisez Wayland et préférez `wl-clipboard`, sinon il essaiera de trouver les outils du presse-papiers dans l’ordre : `xclip` et `xsel`. --- # Web | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/web#_top) Web === Usa OpenCode nel browser. OpenCode puo funzionare come applicazione web nel browser, offrendo la stessa potente esperienza di coding AI senza bisogno di un terminale. ![OpenCode Web - Nuova sessione](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Per iniziare](https://opencode.ai/docs/it/web#per-iniziare) ------------------------------------------------------------- Avvia l’interfaccia web eseguendo: opencode web Questo avvia un server locale su `127.0.0.1` con una porta disponibile scelta a caso e apre automaticamente OpenCode nel browser predefinito. * * * [Configurazione](https://opencode.ai/docs/it/web#configurazione) ----------------------------------------------------------------- Puoi configurare il server web con i flag della riga di comando o nel tuo [file di config](https://opencode.ai/docs/config) . ### [Porta](https://opencode.ai/docs/it/web#porta) Per impostazione predefinita, OpenCode sceglie una porta disponibile. Puoi specificare una porta: opencode web --port 4096 ### [Nome host](https://opencode.ai/docs/it/web#nome-host) Per impostazione predefinita, il server si lega a `127.0.0.1` (solo localhost). Per rendere OpenCode accessibile sulla rete: opencode web --hostname 0.0.0.0 Usando `0.0.0.0`, OpenCode mostrera sia l’indirizzo locale sia quello di rete: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [Scoperta mDNS](https://opencode.ai/docs/it/web#scoperta-mdns) Abilita mDNS per rendere il server individuabile sulla rete locale: opencode web --mdns Questo imposta automaticamente l’hostname a `0.0.0.0` e pubblicizza il server come `opencode.local`. Puoi personalizzare il nome di dominio mDNS per eseguire piu istanze sulla stessa rete: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/it/web#cors) Per consentire domini aggiuntivi per CORS (utile per frontend personalizzati): opencode web --cors https://example.com ### [Autenticazione](https://opencode.ai/docs/it/web#autenticazione) Per proteggere l’accesso, imposta una password usando la variabile d’ambiente `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web Lo username predefinito e `opencode`, ma puo essere cambiato con `OPENCODE_SERVER_USERNAME`. * * * [Usa l’interfaccia web](https://opencode.ai/docs/it/web#usa-linterfaccia-web) ------------------------------------------------------------------------------ Una volta avviata, l’interfaccia web ti da accesso alle tue sessioni OpenCode. ### [Sessioni](https://opencode.ai/docs/it/web#sessioni) Visualizza e gestisci le sessioni dalla homepage. Puoi vedere le sessioni attive e avviarne di nuove. ![OpenCode Web - Sessione attiva](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Stato del server](https://opencode.ai/docs/it/web#stato-del-server) Fai clic su “See Servers” per vedere i server connessi e il loro stato. ![OpenCode Web - See Servers](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Collegare un terminale](https://opencode.ai/docs/it/web#collegare-un-terminale) --------------------------------------------------------------------------------- Puoi collegare una TUI da terminale a un server web gia in esecuzione: # Avvia il web serveropencode web --port 4096 # In un altro terminale, collega la TUIopencode attach http://localhost:4096 Questo ti permette di usare contemporaneamente interfaccia web e terminale, condividendo le stesse sessioni e lo stesso stato. * * * [File di configurazione](https://opencode.ai/docs/it/web#file-di-configurazione) --------------------------------------------------------------------------------- Puoi anche configurare le impostazioni del server nel file di config `opencode.json`: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} I flag della riga di comando hanno precedenza sulle impostazioni del file di config. --- # Web | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/web#_top) Web === 在瀏覽器中使用 OpenCode。 OpenCode 可以作為 Web 應用程式在瀏覽器中執行,無需終端機即可獲得同樣強大的 AI 編碼體驗。 ![OpenCode Web - New Session](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [快速開始](https://opencode.ai/docs/zh-tw/web#%E5%BF%AB%E9%80%9F%E9%96%8B%E5%A7%8B) -------------------------------------------------------------------------------- 執行以下指令啟動 Web 介面: opencode web 這會在 `127.0.0.1` 上啟動一個本地伺服器,使用隨機可用連接埠,並自動在預設瀏覽器中開啟 OpenCode。 * * * [設定](https://opencode.ai/docs/zh-tw/web#%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------ 你可以透過命令列旗標或[設定檔](https://opencode.ai/docs/config) 來設定 Web 伺服器。 ### [連接埠](https://opencode.ai/docs/zh-tw/web#%E9%80%A3%E6%8E%A5%E5%9F%A0) 預設情況下,OpenCode 會選擇一個可用連接埠。你也可以指定連接埠: opencode web --port 4096 ### [主機名稱](https://opencode.ai/docs/zh-tw/web#%E4%B8%BB%E6%A9%9F%E5%90%8D%E7%A8%B1) 預設情況下,伺服器繫結到 `127.0.0.1`(僅限本地存取)。要使 OpenCode 在網路中可存取: opencode web --hostname 0.0.0.0 使用 `0.0.0.0` 時,OpenCode 會同時顯示本地位址和網路位址: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS 探索](https://opencode.ai/docs/zh-tw/web#mdns-%E6%8E%A2%E7%B4%A2) 啟用 mDNS 可以讓你的伺服器在本地網路中被自動探索: opencode web --mdns 這會自動將主機名稱設定為 `0.0.0.0`,並將伺服器廣播為 `opencode.local`。 你可以自訂 mDNS 網域名稱,以便在同一網路中執行多個實例: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/zh-tw/web#cors) 要為 CORS 新增額外的允許網域(適用於自訂前端): opencode web --cors https://example.com ### [身分驗證](https://opencode.ai/docs/zh-tw/web#%E8%BA%AB%E5%88%86%E9%A9%97%E8%AD%89) 要保護伺服器存取,可以透過 `OPENCODE_SERVER_PASSWORD` 環境變數設定密碼: OPENCODE_SERVER_PASSWORD=secret opencode web 使用者名稱預設為 `opencode`,可以透過 `OPENCODE_SERVER_USERNAME` 進行更改。 * * * [使用 Web 介面](https://opencode.ai/docs/zh-tw/web#%E4%BD%BF%E7%94%A8-web-%E4%BB%8B%E9%9D%A2) ------------------------------------------------------------------------------------------ 啟動後,Web 介面提供對 OpenCode 工作階段的存取。 ### [工作階段](https://opencode.ai/docs/zh-tw/web#%E5%B7%A5%E4%BD%9C%E9%9A%8E%E6%AE%B5) 在主頁上查看和管理你的工作階段。你可以查看進行中的工作階段,也可以建立新的工作階段。 ![OpenCode Web - Active Session](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [伺服器狀態](https://opencode.ai/docs/zh-tw/web#%E4%BC%BA%E6%9C%8D%E5%99%A8%E7%8B%80%E6%85%8B) 點擊「See Servers」可以查看已連線的伺服器及其狀態。 ![OpenCode Web - See Servers](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [連接終端機](https://opencode.ai/docs/zh-tw/web#%E9%80%A3%E6%8E%A5%E7%B5%82%E7%AB%AF%E6%A9%9F) ------------------------------------------------------------------------------------------ 你可以將終端機 TUI 連接到正在執行的 Web 伺服器: # 啟動 Web 伺服器opencode web --port 4096 # 在另一個終端機中連接 TUIopencode attach http://localhost:4096 這樣你就可以同時使用 Web 介面和終端機,共享相同的工作階段和狀態。 * * * [設定檔](https://opencode.ai/docs/zh-tw/web#%E8%A8%AD%E5%AE%9A%E6%AA%94) ---------------------------------------------------------------------- 你也可以在 `opencode.json` 設定檔中設定伺服器選項: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} 命令列旗標的優先順序高於設定檔中的設定。 --- # Web | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/web#_top) Web === 在浏览器中使用 OpenCode。 OpenCode 可以作为 Web 应用在浏览器中运行,无需终端即可获得同样强大的 AI 编码体验。 ![OpenCode Web - New Session](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [快速开始](https://opencode.ai/docs/zh-cn/web#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) -------------------------------------------------------------------------------- 运行以下命令启动 Web 界面: opencode web 这会在 `127.0.0.1` 上启动一个本地服务器,使用随机可用端口,并自动在默认浏览器中打开 OpenCode。 * * * [配置](https://opencode.ai/docs/zh-cn/web#%E9%85%8D%E7%BD%AE) ------------------------------------------------------------ 你可以通过命令行标志或[配置文件](https://opencode.ai/docs/config) 来配置 Web 服务器。 ### [端口](https://opencode.ai/docs/zh-cn/web#%E7%AB%AF%E5%8F%A3) 默认情况下,OpenCode 会选择一个可用端口。你也可以指定端口: opencode web --port 4096 ### [主机名](https://opencode.ai/docs/zh-cn/web#%E4%B8%BB%E6%9C%BA%E5%90%8D) 默认情况下,服务器绑定到 `127.0.0.1`(仅限本地访问)。要使 OpenCode 在网络中可访问: opencode web --hostname 0.0.0.0 使用 `0.0.0.0` 时,OpenCode 会同时显示本地地址和网络地址: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS 发现](https://opencode.ai/docs/zh-cn/web#mdns-%E5%8F%91%E7%8E%B0) 启用 mDNS 可以让你的服务器在本地网络中被自动发现: opencode web --mdns 这会自动将主机名设置为 `0.0.0.0`,并将服务器广播为 `opencode.local`。 你可以自定义 mDNS 域名,以便在同一网络中运行多个实例: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/zh-cn/web#cors) 要为 CORS 添加额外的允许域名(适用于自定义前端): opencode web --cors https://example.com ### [身份验证](https://opencode.ai/docs/zh-cn/web#%E8%BA%AB%E4%BB%BD%E9%AA%8C%E8%AF%81) 要保护服务器访问,可以通过 `OPENCODE_SERVER_PASSWORD` 环境变量设置密码: OPENCODE_SERVER_PASSWORD=secret opencode web 用户名默认为 `opencode`,可以通过 `OPENCODE_SERVER_USERNAME` 进行更改。 * * * [使用 Web 界面](https://opencode.ai/docs/zh-cn/web#%E4%BD%BF%E7%94%A8-web-%E7%95%8C%E9%9D%A2) ------------------------------------------------------------------------------------------ 启动后,Web 界面提供对 OpenCode 会话的访问。 ### [会话](https://opencode.ai/docs/zh-cn/web#%E4%BC%9A%E8%AF%9D) 在主页上查看和管理你的会话。你可以查看活跃的会话,也可以创建新的会话。 ![OpenCode Web - Active Session](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [服务器状态](https://opencode.ai/docs/zh-cn/web#%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%8A%B6%E6%80%81) 点击”See Servers”可以查看已连接的服务器及其状态。 ![OpenCode Web - See Servers](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [连接终端](https://opencode.ai/docs/zh-cn/web#%E8%BF%9E%E6%8E%A5%E7%BB%88%E7%AB%AF) -------------------------------------------------------------------------------- 你可以将终端 TUI 连接到正在运行的 Web 服务器: # 启动 Web 服务器opencode web --port 4096 # 在另一个终端中连接 TUIopencode attach http://localhost:4096 这样你就可以同时使用 Web 界面和终端,共享相同的会话和状态。 * * * [配置文件](https://opencode.ai/docs/zh-cn/web#%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6) -------------------------------------------------------------------------------- 你也可以在 `opencode.json` 配置文件中设置服务器选项: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} 命令行标志的优先级高于配置文件中的设置。 --- # الويب | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/web#_top) الويب ===== استخدام OpenCode في متصفحك. يمكن تشغيل OpenCode كتطبيق ويب داخل متصفحك، ليمنحك تجربة البرمجة القوية بالذكاء الاصطناعي نفسها دون الحاجة إلى terminal. ![OpenCode Web - جلسة جديدة](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [البدء](https://opencode.ai/docs/ar/web#%D8%A7%D9%84%D8%A8%D8%AF%D8%A1) ------------------------------------------------------------------------ ابدأ تشغيل واجهة الويب عبر تنفيذ: opencode web يؤدي ذلك إلى تشغيل خادم محلي على `127.0.0.1` بمنفذ عشوائي متاح، ويفتح OpenCode تلقائيا في المتصفح الافتراضي لديك. * * * [الإعدادات](https://opencode.ai/docs/ar/web#%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF%D8%A7%D8%AA) ---------------------------------------------------------------------------------------------------- يمكنك ضبط خادم الويب باستخدام خيارات CLI أو عبر [ملف الإعدادات](https://opencode.ai/docs/config) . ### [المنفذ](https://opencode.ai/docs/ar/web#%D8%A7%D9%84%D9%85%D9%86%D9%81%D8%B0) افتراضيا، يختار OpenCode منفذا متاحا. يمكنك تحديد منفذ: opencode web --port 4096 ### [اسم المضيف](https://opencode.ai/docs/ar/web#%D8%A7%D8%B3%D9%85-%D8%A7%D9%84%D9%85%D8%B6%D9%8A%D9%81) افتراضيا، يرتبط الخادم بـ `127.0.0.1` (للاستخدام المحلي فقط). لجعل OpenCode متاحا على شبكتك: opencode web --hostname 0.0.0.0 عند استخدام `0.0.0.0` سيعرض OpenCode كلا من عناوين الوصول المحلي وعناوين الشبكة: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [اكتشاف mDNS](https://opencode.ai/docs/ar/web#%D8%A7%D9%83%D8%AA%D8%B4%D8%A7%D9%81-mdns) فعّل mDNS لجعل خادمك قابلا للاكتشاف على الشبكة المحلية: opencode web --mdns يضبط ذلك تلقائيا اسم المضيف إلى `0.0.0.0` ويعلن عن الخادم باسم `opencode.local`. يمكنك تخصيص اسم نطاق mDNS لتشغيل عدة نسخ على الشبكة نفسها: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/ar/web#cors) للسماح بنطاقات إضافية عبر CORS (مفيد للواجهات الأمامية المخصصة): opencode web --cors https://example.com ### [المصادقة](https://opencode.ai/docs/ar/web#%D8%A7%D9%84%D9%85%D8%B5%D8%A7%D8%AF%D9%82%D8%A9) لحماية الوصول، عيّن كلمة مرور عبر متغير البيئة `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web اسم المستخدم الافتراضي هو `opencode`، ويمكن تغييره عبر `OPENCODE_SERVER_USERNAME`. * * * [استخدام واجهة الويب](https://opencode.ai/docs/ar/web#%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85-%D9%88%D8%A7%D8%AC%D9%87%D8%A9-%D8%A7%D9%84%D9%88%D9%8A%D8%A8) ---------------------------------------------------------------------------------------------------------------------------------------------------------------- بعد التشغيل، تتيح لك واجهة الويب الوصول إلى جلسات OpenCode الخاصة بك. ### [الجلسات](https://opencode.ai/docs/ar/web#%D8%A7%D9%84%D8%AC%D9%84%D8%B3%D8%A7%D8%AA) اعرض جلساتك وأدرها من الصفحة الرئيسية. يمكنك رؤية الجلسات النشطة وبدء جلسات جديدة. ![OpenCode Web - جلسة نشطة](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [حالة الخادم](https://opencode.ai/docs/ar/web#%D8%AD%D8%A7%D9%84%D8%A9-%D8%A7%D9%84%D8%AE%D8%A7%D8%AF%D9%85) انقر على “See Servers” لعرض الخوادم المتصلة وحالتها. ![OpenCode Web - See Servers (عرض الخوادم)](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [إرفاق terminal](https://opencode.ai/docs/ar/web#%D8%A5%D8%B1%D9%81%D8%A7%D9%82-terminal) ------------------------------------------------------------------------------------------ يمكنك إرفاق واجهة terminal (TUI) بخادم ويب قيد التشغيل: # ابدأ خادم الويبopencode web --port 4096 # في محطة طرفية أخرى، اربط TUIopencode attach http://localhost:4096 يتيح لك ذلك استخدام واجهة الويب وterminal في الوقت نفسه، مع مشاركة الجلسات والحالة نفسها. * * * [ملف الإعدادات](https://opencode.ai/docs/ar/web#%D9%85%D9%84%D9%81-%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF%D8%A7%D8%AA) --------------------------------------------------------------------------------------------------------------------------- يمكنك أيضا ضبط إعدادات الخادم داخل ملف الإعدادات `opencode.json`: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} تكون خيارات CLI ذات أولوية أعلى من إعدادات ملف الإعدادات. --- # Web | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/web#_top) Web === Tarayıcınızda opencode'u kullanma. opencode, tarayıcınızda bir web uygulaması olarak çalışabilir ve bir terminale ihtiyaç duymadan aynı güçlü AI kodlama deneyimini sağlayabilir. ![opencode Web - Yeni Oturum](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Başlarken](https://opencode.ai/docs/tr/web#ba%C5%9Flarken) ------------------------------------------------------------ Aşağıdakileri çalıştırarak web arayüzünü başlatın: opencode web Bu, `127.0.0.1` üzerinde rastgele kullanılabilir bir bağlantı noktasına sahip yerel bir sunucuyu başlatır ve opencode’u varsayılan tarayıcınızda otomatik olarak açar. * * * [Yapılandırma](https://opencode.ai/docs/tr/web#yap%C4%B1land%C4%B1rma) ----------------------------------------------------------------------- Web sunucusunu komut satırı bayraklarıyla veya [config dosyanızda](https://opencode.ai/docs/config) yapılandırabilirsiniz. ### [Port](https://opencode.ai/docs/tr/web#port) opencode varsayılan olarak kullanılabilir bir bağlantı noktasını seçer. Bir bağlantı noktası belirtebilirsiniz: opencode web --port 4096 ### [Ana makine adı](https://opencode.ai/docs/tr/web#ana-makine-ad%C4%B1) Varsayılan olarak sunucu `127.0.0.1` (yalnızca localhost) öğesine bağlanır. opencode’u ağınızda erişilebilir kılmak için: opencode web --hostname 0.0.0.0 `0.0.0.0` kullanıldığında, opencode hem yerel hem de ağ adreslerini gösterecektir: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS Keşfi](https://opencode.ai/docs/tr/web#mdns-ke%C5%9Ffi) Sunucunuzun yerel ağda bulunabilir olmasını sağlamak için mDNS’yi etkinleştirin: opencode web --mdns Bu, ana bilgisayar adını otomatik olarak `0.0.0.0` olarak ayarlar ve sunucuyu `opencode.local` olarak tanıtır. Aynı ağ üzerinde birden fazla örneği çalıştıracak şekilde mDNS alan adını özelleştirebilirsiniz: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/tr/web#cors) CORS’a yönelik ek alan adlarına izin vermek için (özel ön uçlar için kullanışlıdır): opencode web --cors https://example.com ### [Kimlik Doğrulaması](https://opencode.ai/docs/tr/web#kimlik-do%C4%9Frulamas%C4%B1) Erişimi korumak için `OPENCODE_SERVER_PASSWORD` ortam değişkenini kullanarak bir parola ayarlayın: OPENCODE_SERVER_PASSWORD=secret opencode web Kullanıcı adı varsayılan olarak `opencode` şeklindedir ancak `OPENCODE_SERVER_USERNAME` ile değiştirilebilir. * * * [Web Arayüzünü Kullanma](https://opencode.ai/docs/tr/web#web-aray%C3%BCz%C3%BCn%C3%BC-kullanma) ------------------------------------------------------------------------------------------------ Web arayüzü başlatıldığında opencode oturumlarınıza erişim sağlar. ### [Oturum](https://opencode.ai/docs/tr/web#oturum) Oturumlarınızı ana sayfadan görüntüleyin ve yönetin. Aktif oturumları görebilir ve yenilerini başlatabilirsiniz. ![opencode Web - Etkin Oturum](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Sunucu Durumu](https://opencode.ai/docs/tr/web#sunucu-durumu) Bağlı sunucuları ve durumlarını görüntülemek için “Sunucuları Gör” seçeneğini tıklayın. ![opencode Web - Sunuculara bakın](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Terminal Takma](https://opencode.ai/docs/tr/web#terminal-takma) ----------------------------------------------------------------- Çalışan bir web sunucusuna bir terminal TUI’si ekleyebilirsiniz: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Bu, aynı oturumları ve durumu paylaşarak hem web arayüzünü hem de terminali aynı anda kullanmanıza olanak tanır. * * * [Yapılandırma Dosyası](https://opencode.ai/docs/tr/web#yap%C4%B1land%C4%B1rma-dosyas%C4%B1) -------------------------------------------------------------------------------------------- Sunucu ayarlarını `opencode.json` yapılandırma dosyanızda da yapılandırabilirsiniz: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Komut satırı bayrakları yapılandırma dosyası ayarlarından önceliklidir. --- # Web | OpenCode [Gå til indhold](https://opencode.ai/docs/da/web#_top) Web === Brug af OpenCode i din browser. OpenCode kan køre som en webapplikation i din browser, hvilket giver den samme kraftfulde AI-kodningsoplevelse uden behov for en terminal. ![OpenCode Web - Ny session](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Kom godt i gang](https://opencode.ai/docs/da/web#kom-godt-i-gang) ------------------------------------------------------------------- Start webgrænsefladen ved at køre: opencode web Dette starter en lokal server på `127.0.0.1` med en tilfældig tilgængelig port og åbner automatisk OpenCode i din standardbrowser. * * * [Konfiguration](https://opencode.ai/docs/da/web#konfiguration) --------------------------------------------------------------- Du kan konfigurere webserveren ved hjælp af kommandolinjeflag eller i din [config-fil](https://opencode.ai/docs/config) . ### [Port](https://opencode.ai/docs/da/web#port) Som standard vælger OpenCode en tilgængelig port. Du kan angive en port: opencode web --port 4096 ### [Værtsnavn](https://opencode.ai/docs/da/web#v%C3%A6rtsnavn) Som standard binder serveren til `127.0.0.1` (kun lokal vært). Sådan gør du OpenCode tilgængelig på dit netværk: opencode web --hostname 0.0.0.0 Når du bruger `0.0.0.0`, vil OpenCode vise både lokale adresser og netværksadresser: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [mDNS-opdagelse](https://opencode.ai/docs/da/web#mdns-opdagelse) Aktiver mDNS for at gøre din server synlig på det lokale netværk: opencode web --mdns Dette indstiller automatisk værtsnavnet til `0.0.0.0` og annoncerer serveren som `opencode.local`. Du kan tilpasse mDNS-domænenavnet til at køre flere forekomster på det samme netværk: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/da/web#cors) For at tillade yderligere domæner til CORS (nyttigt til brugerdefinerede frontends): opencode web --cors https://example.com ### [Godkendelse](https://opencode.ai/docs/da/web#godkendelse) For at beskytte adgangen skal du angive en adgangskode ved hjælp af `OPENCODE_SERVER_PASSWORD` miljøvariablen: OPENCODE_SERVER_PASSWORD=secret opencode web Brugernavnet er som standard `opencode`, men kan ændres med `OPENCODE_SERVER_USERNAME`. * * * [Brug af webgrænsefladen](https://opencode.ai/docs/da/web#brug-af-webgr%C3%A6nsefladen) ---------------------------------------------------------------------------------------- Når den er startet, giver webgrænsefladen adgang til dine OpenCode-sessioner. ### [Sessioner](https://opencode.ai/docs/da/web#sessioner) Se og administrer dine sessioner fra hjemmesiden. Du kan se aktive sessioner og starte nye. ![OpenCode Web - Active Session](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Serverstatus](https://opencode.ai/docs/da/web#serverstatus) Klik på “Se servere” for at se tilsluttede servere og deres status. ![OpenCode Web - Se servere](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Tilslutning af en terminal](https://opencode.ai/docs/da/web#tilslutning-af-en-terminal) ----------------------------------------------------------------------------------------- Du kan vedhæfte en terminal TUI til en kørende webserver: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Dette giver dig mulighed for at bruge både webgrænsefladen og terminalen samtidigt og dele de samme sessioner og tilstand. * * * [Konfigurationsfil](https://opencode.ai/docs/da/web#konfigurationsfil) ----------------------------------------------------------------------- Du kan også konfigurere serverindstillinger i din `opencode.json`\-konfigurationsfil: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} Kommandolinjeflag har forrang over konfigurationsfilindstillinger. --- # Eklentiler | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/plugins#_top) Eklentiler ========== OpenCode'u genişletmek için kendi eklentilerinizi yazın. Eklentiler, çeşitli olaylara bağlanarak ve davranışı özelleştirerek OpenCode’u genişletmenize olanak tanır. Yeni özellikler eklemek, harici hizmetlerle entegrasyon sağlamak veya OpenCode’un varsayılan davranışını değiştirmek için eklentiler oluşturabilirsiniz. Örnekler için topluluk tarafından oluşturulan [eklentilere](https://opencode.ai/docs/ecosystem#plugins) göz atın. * * * [Eklenti kullanımı](https://opencode.ai/docs/tr/plugins#eklenti-kullan%C4%B1m%C4%B1) ------------------------------------------------------------------------------------- Eklentileri yüklemenin iki yolu vardır. * * * ### [Yerel dosyalardan](https://opencode.ai/docs/tr/plugins#yerel-dosyalardan) JavaScript veya TypeScript dosyalarını eklenti dizinine yerleştirin. * `.opencode/plugins/` - Proje düzeyinde eklentiler * `~/.config/opencode/plugins/` - Genel eklentiler Bu dizinlerdeki dosyalar başlangıçta otomatik olarak yüklenir. * * * ### [npm’den](https://opencode.ai/docs/tr/plugins#npmden) Yapılandırma dosyanızda npm paketlerini belirtin. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Hem normal hem de kapsamlı npm paketleri desteklenir. [Ekosistem](https://opencode.ai/docs/ecosystem#plugins) ’deki mevcut eklentilere göz atın. * * * ### [Eklentiler nasıl kurulur?](https://opencode.ai/docs/tr/plugins#eklentiler-nas%C4%B1l-kurulur) **npm eklentileri** başlangıçta Bun kullanılarak otomatik olarak yüklenir. Paketler ve bağımlılıkları `~/.cache/opencode/node_modules/`’da önbelleğe alınır. **Yerel eklentiler** doğrudan eklenti dizininden yüklenir. Harici paketleri kullanmak için, sisteminizin dizininde bir `package.json` oluşturmanız (bkz. [Bağımlılıklar](https://opencode.ai/docs/tr/plugins#dependencies) ) veya eklentiyi npm ve [yapılandırmanıza eklemeniz](https://opencode.ai/docs/config#plugins) gerekir. * * * ### [Yükleme sırası](https://opencode.ai/docs/tr/plugins#y%C3%BCkleme-s%C4%B1ras%C4%B1) Eklentiler tüm kaynaklardan yüklenir ve tüm kancalar sırayla çalışır. Yükleme sırası şöyledir: 1. Global config (`~/.config/opencode/opencode.json`) 2. Project config (`opencode.json`) 3. Global eklenti dizini (`~/.config/opencode/plugins/`) 4. Proje eklenti dizini (`.opencode/plugins/`) Aynı ad ve sürüme sahip yinelenen npm paketleri bir kez yüklenir. Ancak benzer adlara sahip bir yerel eklenti ve bir npm eklentisinin her ikisi de ayrı ayrı yüklenir. * * * [Eklenti oluşturma](https://opencode.ai/docs/tr/plugins#eklenti-olu%C5%9Fturma) -------------------------------------------------------------------------------- Eklenti, bir veya daha fazla eklenti işlevini dışa aktaran bir **JavaScript/TypeScript modülüdür**. Her işlev bir bağlam nesnesi alır ve bir kanca nesnesi döndürür. * * * ### [Bağımlılıklar](https://opencode.ai/docs/tr/plugins#ba%C4%9F%C4%B1ml%C4%B1l%C4%B1klar) Yerel eklentiler ve özel araçlar harici npm paketlerini kullanabilir. İhtiyacınız olan bağımlılıkları içeren config dizininize bir `package.json` ekleyin. { "dependencies": { "shescape": "^2.1.0" }} OpenCode bunları yüklemek için başlangıçta `bun install` komutunu çalıştırır. Eklentileriniz ve araçlarınız daha sonra bunları içe aktarabilir. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Temel yapı](https://opencode.ai/docs/tr/plugins#temel-yap%C4%B1) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} Eklenti işlevi şunları alır: * `project`: Mevcut proje bilgisi. * `directory`: Güncel çalışma dizini. * `worktree`: Git çalışma ağacı yolu. * `client`: Yapay zeka ile etkileşim kurmak için bir OpenCode SDK istemcisi. * `$`: Bun’un komutları yürütmek için kullandığı [shell API](https://bun.com/docs/runtime/shell) . * * * ### [TypeScript desteği](https://opencode.ai/docs/tr/plugins#typescript-deste%C4%9Fi) TypeScript eklentileri için türleri eklenti paketinden içe aktarabilirsiniz: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Olaylar](https://opencode.ai/docs/tr/plugins#olaylar) Eklentiler aşağıdaki Örnekler bölümünde görüldüğü gibi etkinliklere abone olabilirler. Burada mevcut farklı etkinliklerin bir listesi bulunmaktadır. #### [Komut Olayları](https://opencode.ai/docs/tr/plugins#komut-olaylar%C4%B1) * `command.executed` #### [Dosya Olayları](https://opencode.ai/docs/tr/plugins#dosya-olaylar%C4%B1) * `file.edited` * `file.watcher.updated` #### [Kurulum Olayları](https://opencode.ai/docs/tr/plugins#kurulum-olaylar%C4%B1) * `installation.updated` #### [LSP Olayları](https://opencode.ai/docs/tr/plugins#lsp-olaylar%C4%B1) * `lsp.client.diagnostics` * `lsp.updated` #### [Mesaj Olayları](https://opencode.ai/docs/tr/plugins#mesaj-olaylar%C4%B1) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [İzin Olayları](https://opencode.ai/docs/tr/plugins#i%CC%87zin-olaylar%C4%B1) * `permission.asked` * `permission.replied` #### [Sunucu Olayları](https://opencode.ai/docs/tr/plugins#sunucu-olaylar%C4%B1) * `server.connected` #### [Oturum Olayları](https://opencode.ai/docs/tr/plugins#oturum-olaylar%C4%B1) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Yapılacaklar Olayları](https://opencode.ai/docs/tr/plugins#yap%C4%B1lacaklar-olaylar%C4%B1) * `todo.updated` #### [Kabuk Olayları](https://opencode.ai/docs/tr/plugins#kabuk-olaylar%C4%B1) * `shell.env` #### [Araç Olayları](https://opencode.ai/docs/tr/plugins#ara%C3%A7-olaylar%C4%B1) * `tool.execute.after` * `tool.execute.before` #### [TUI Olayları](https://opencode.ai/docs/tr/plugins#tui-olaylar%C4%B1) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Örnekler](https://opencode.ai/docs/tr/plugins#%C3%B6rnekler) -------------------------------------------------------------- OpenCode’u genişletmek için kullanabileceğiniz bazı eklenti örneklerini burada bulabilirsiniz. * * * ### [Bildirim Gönderme](https://opencode.ai/docs/tr/plugins#bildirim-g%C3%B6nderme) Belirli olaylar meydana geldiğinde bildirim gönderin: 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"'` } }, }} macOS’ta AppleScript’i çalıştırmak için `osascript` kullanıyoruz. Burada bildirim göndermek için kullanıyoruz. * * * ### [.env Koruması](https://opencode.ai/docs/tr/plugins#env-korumas%C4%B1) OpenCode’un `.env` dosyalarını okumasını önleyin: 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") } }, }} * * * ### [Ortam değişkenlerini enjekte etme](https://opencode.ai/docs/tr/plugins#ortam-de%C4%9Fi%C5%9Fkenlerini-enjekte-etme) Ortam değişkenlerini tüm kabuk yürütmeye (AI araçları ve kullanıcı terminalleri) enjekte edin: export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Özel araçlar](https://opencode.ai/docs/tr/plugins#%C3%B6zel-ara%C3%A7lar) Eklentiler ayrıca OpenCode’a özel araçlar da ekleyebilir: 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})` }, }), }, }} `tool` yardımcısı, OpenCode’un çağırabileceği özel bir araç oluşturur. Bir Zod şeması işlevini alır ve aşağıdakileri içeren bir araç tanımı döndürür: * `description`: Araç ne yapar? * `args`: Aracın argümanları için Zod şeması * `execute`: Araç çağrıldığında çalışan fonksiyon Özel araçlarınız, yerleşik araçların yanı sıra OpenCode’a da hazır olacaktır. * * * ### [Günlüğe kaydetme](https://opencode.ai/docs/tr/plugins#g%C3%BCnl%C3%BC%C4%9Fe-kaydetme) Yapılandırılmış günlük kaydı için `console.log` yerine `client.app.log()` kullanın: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Seviyeler: `debug`, `info`, `warn`, `error`. Ayrıntılar için [SDK belgelerine](https://opencode.ai/docs/sdk) bakın. * * * ### [Sıkıştırma kancaları](https://opencode.ai/docs/tr/plugins#s%C4%B1k%C4%B1%C5%9Ft%C4%B1rma-kancalar%C4%B1) Bir oturum sıkıştırıldığında içerilen bağlamı özelleştirin: 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`) }, }} `experimental.session.compacting` kancası, LLM bir devam özeti oluşturmadan önce tetiklenir. Varsayılan sıkıştırma isteminin kaçıracağı etki alanına özgü bağlamı enjekte etmek için bunu kullanın. Ayrıca `output.prompt` ayarını yaparak sıkıştırma istemini tamamen değiştirebilirsiniz: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} `output.prompt` ayarlandığında, varsayılan sıkıştırma isteminin tamamen yerini alır. Bu durumda `output.context` dizisi dikkate alınmaz. --- # Wtyczki | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/plugins#_top) Wtyczki ======= Napisz własną wtyczkę, aby rozszerzyć opencode. Wtyczki umożliwiające wyłączenie opencode poprzez podjęcie różnych zdarzeń i zachowanie. Można utworzyć wtyczkę, aby sprawdzić nowe funkcje, integrować się z usługami lub sprawdzaniem zachowania opencode. Aby znaleźć się z przykładami, przejrzyj [wtyczki](https://opencode.ai/docs/ecosystem#plugins) utworzone przez społeczność. * * * [Użyj wtyczki](https://opencode.ai/docs/pl/plugins#u%C5%BCyj-wtyczki) ---------------------------------------------------------------------- Istnieją dwa sposoby ładowania wtyczek. * * * ### [Z plików lokalnych](https://opencode.ai/docs/pl/plugins#z-plik%C3%B3w-lokalnych) Miejsce plików JavaScript lub TypeScript w katalogu wtyczki. * `.opencode/plugins/` - Wtyczki na poziomie projektu * `~/.config/opencode/plugins/` - Wtyczki globalne Pliki w tych katalogach są automatycznie ładowane podczas uruchamiania. * * * ### [Z npm](https://opencode.ai/docs/pl/plugins#z-npm) szczegółowy pakiet npm w pliku konfiguracyjnym. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Obsługiwane są zarówno pakiety zwykłe, jak i pakiety npm o określonym zakresie. Przeglądaj dostępną wtyczkę w [ekosystemie](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Sposób instalacji wtyczek](https://opencode.ai/docs/pl/plugins#spos%C3%B3b-instalacji-wtyczek) **wtyczki npm** są instalowane automatycznie przy użyciu Bun podczas uruchamiania. Pakiety i ich zależności są buforowane w `~/.cache/opencode/node_modules/`. **Wtyczki lokalne** są ładowane bezpośrednio z katalogu wtyczek. Aby uzyskać dostęp do zewnętrznych pakietów, musisz zainstalować `package.json` w swoim katalogu konfiguracyjnym (zobacz [Zależności](https://opencode.ai/docs/pl/plugins#dependencies) ) lub opublikować wtyczkę w npm i [dodaj ją do swojej konfiguracji](https://opencode.ai/docs/config#plugins) . * * * ### [Kolejność ładowania](https://opencode.ai/docs/pl/plugins#kolejno%C5%9B%C4%87-%C5%82adowania) Wtyczki są ładowane ze wszystkich źródeł, a wszystkie hooki napisane po kolei. Kolejność ładowania do: 1. Konfiguracja globalna (`~/.config/opencode/opencode.json`) 2. Konfiguracja projektu (`opencode.json`) 3. Globalny katalog wtyczek (`~/.config/opencode/plugins/`) 4. Katalog wtyczek projektu (`.opencode/plugins/`) Zduplikowane pakiety npm o tej samej nazwie i wersji są ładowane raz. Równie ważny jest dostęp lokalny i zewnętrzny npm o dodatkowych nazwach, które są zewnętrzne. * * * [Utwórz wtyczkę](https://opencode.ai/docs/pl/plugins#utw%C3%B3rz-wtyczk%C4%99) ------------------------------------------------------------------------------- Wtyczka do **moduł JavaScript/TypeScript**, który eksportuje jeden lub więcej wtyczek funkcje. dostępna funkcja korzystania z obiektu kontekstu i głównego obiektu hooks. * * * ### [Zależności](https://opencode.ai/docs/pl/plugins#zale%C5%BCno%C5%9Bci) Lokalne narzędzie i narzędzie, które można wykorzystać z zewnętrznych pakietów npm. Dodaj `package.json` do swojego katalogu konfiguracyjnego z zależnościami. { "dependencies": { "shescape": "^2.1.0" }} opencode uruchomienie `bun install` przy uruchomieniu, aby je uruchomić. Twoje dodatkowe funkcje będą dostępne po zaimportowaniu. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Podstawowa struktura](https://opencode.ai/docs/pl/plugins#podstawowa-struktura) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} Funkcja dostępu do: * `project`: Aktualne informacje o projekcie. * `directory`: Bieżący katalog roboczy. * `worktree`: Ścieżka eksploatacyjna Git. * `client`: Klient SDK z opencode do sztucznej inteligencji. * `$`: [API obudowy](https://bun.com/docs/runtime/shell) Buna do wykonywania oprogramowania. * * * ### [Obsługa TypeScriptu](https://opencode.ai/docs/pl/plugins#obs%C5%82uga-typescriptu) W przypadku wtyczek TypeScript możesz importować typy z pakietu wtyczek: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [Wydarzenia](https://opencode.ai/docs/pl/plugins#wydarzenia) Wtyczki mogą subskrybować zdarzenia, jak zastosować poniżej sekcji Przykłady. Oto lista różnych działań. #### [Wydarzenia dowodzenia](https://opencode.ai/docs/pl/plugins#wydarzenia-dowodzenia) * `command.executed` #### [Plik Wydarzenia](https://opencode.ai/docs/pl/plugins#plik-wydarzenia) * `file.edited` * `file.watcher.updated` #### [Wydarzenia instalacyjne](https://opencode.ai/docs/pl/plugins#wydarzenia-instalacyjne) * `installation.updated` #### [Wydarzenia LSP](https://opencode.ai/docs/pl/plugins#wydarzenia-lsp) * `lsp.client.diagnostics` * `lsp.updated` #### [Wydarzenia w wiadomościach](https://opencode.ai/docs/pl/plugins#wydarzenia-w-wiadomo%C5%9Bciach) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [Wydarzenia związane z uprawnieniami](https://opencode.ai/docs/pl/plugins#wydarzenia-zwi%C4%85zane-z-uprawnieniami) * `permission.asked` * `permission.replied` #### [Wydarzenia serwerowe](https://opencode.ai/docs/pl/plugins#wydarzenia-serwerowe) * `server.connected` #### [Wydarzenia sesyjne](https://opencode.ai/docs/pl/plugins#wydarzenia-sesyjne) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [Wydarzenia do zrobienia](https://opencode.ai/docs/pl/plugins#wydarzenia-do-zrobienia) * `todo.updated` #### [Wydarzenia shell](https://opencode.ai/docs/pl/plugins#wydarzenia-shell) * `shell.env` #### [Wydarzenia narzędziowe](https://opencode.ai/docs/pl/plugins#wydarzenia-narz%C4%99dziowe) * `tool.execute.after` * `tool.execute.before` #### [Wydarzenia TUI](https://opencode.ai/docs/pl/plugins#wydarzenia-tui) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Przykłady](https://opencode.ai/docs/pl/plugins#przyk%C5%82ady) ---------------------------------------------------------------- Oto kilka dostępnych wtyczek, które można udostępnić do opencode. * * * ### [Wysyłaj powiadomienia](https://opencode.ai/docs/pl/plugins#wysy%C5%82aj-powiadomienia) Wysyłaj powiadomienia, gdy wystąpią określone zdarzenia: 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"'` } }, }} Używamy `osascript` do uruchamiania AppleScript na macOS. Tutaj możesz przejść do wysyłania pozostałości. * * * ### [ochrona .env](https://opencode.ai/docs/pl/plugins#ochrona-env) Zablokuj opencode czytanie plików `.env`: 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") } }, }} * * * ### [Wstrzyknij zmienne środowiskowe](https://opencode.ai/docs/pl/plugins#wstrzyknij-zmienne-%C5%9Brodowiskowe) Wstrzyknij zmienne konsekwencje dla wszystkich wykonań (narzędzia AI i terminale użytkownika): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Niestandardowe narzędzia](https://opencode.ai/docs/pl/plugins#niestandardowe-narz%C4%99dzia) Wtyczki mogą również dodawać niestandardowe narzędzia do opencode: 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})` }, }), }, }} Pomocnik `tool` tworzy narzędzie użytkowe, które może wywołać kod opencode. Pobierane schematu Zoda i narzędzie wyszukiwania za pomocą: * `description`: Co robi do narzędzia * `args`: Schemat Zoda dla narzędzi argumentów * `execute`: Funkcja uruchamiania po wywołaniu narzędzia Twoje narzędzie będzie dostępne dla otwartego kodu wraz z narzędziami użytkowymi. * * * ### [Logowanie](https://opencode.ai/docs/pl/plugins#logowanie) użyj `client.app.log()` zamiast `console.log` do rejestracji strukturalnego: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Poziomy: `debug`, `info`, `warn`, `error`. Aby uzyskać szczegółowe informacje, zobacz [dokumentację pakietu SDK](https://opencode.ai/docs/sdk) . * * * ### [Haki zagęszczające](https://opencode.ai/docs/pl/plugins#haki-zag%C4%99szczaj%C4%85ce) Dostosuj kontekst dołączony podczas kompaktowania sesji: 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`) }, }} Hak `experimental.session.compacting` jest uruchamiany, zanim LLM wygeneruje podsumowanie kontynuacji. go, aby wstrzyknąć kontekst kontekstu dla domeny, której nie dostrzeżono przez domyślny monit o zagęszczenie. Można także umieścić kompletny monit o zagęszczenie, ustawiając `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Gdy urządzenie jest `output.prompt`, jest całkowicie dostępne na domyślnym monit o zagęszczanie. Tablica `output.context` jest w tym przypadku poniesiona. --- # Интернет | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/web#_top) Интернет ======== Использование opencode в вашем браузере. opencode может работать как веб-приложение в вашем браузере, обеспечивая такой же мощный опыт кодирования AI без необходимости использования терминала. ![opencode Web — новый сеанс](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [Начало работы](https://opencode.ai/docs/ru/web#%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%BE-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%8B) --------------------------------------------------------------------------------------------------------------------------- Запустите веб-интерфейс, выполнив: opencode web Это запустит локальный сервер `127.0.0.1` со случайным доступным портом и автоматически откроет opencode в браузере по умолчанию. * * * [Конфигурация](https://opencode.ai/docs/ru/web#%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B3%D1%83%D1%80%D0%B0%D1%86%D0%B8%D1%8F) ------------------------------------------------------------------------------------------------------------------------- Вы можете настроить веб-сервер с помощью CLI-флагов или в файле [config file](https://opencode.ai/docs/config) . ### [Порт](https://opencode.ai/docs/ru/web#%D0%BF%D0%BE%D1%80%D1%82) По умолчанию opencode выбирает доступный порт. Вы можете указать порт: opencode web --port 4096 ### [Имя хоста](https://opencode.ai/docs/ru/web#%D0%B8%D0%BC%D1%8F-%D1%85%D0%BE%D1%81%D1%82%D0%B0) По умолчанию сервер привязывается к `127.0.0.1` (только локальный хост). Чтобы сделать opencode доступным в вашей сети: opencode web --hostname 0.0.0.0 При использовании `0.0.0.0` opencode будет отображать как локальные, так и сетевые адреса: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [Обнаружение mDNS](https://opencode.ai/docs/ru/web#%D0%BE%D0%B1%D0%BD%D0%B0%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5-mdns) Включите mDNS, чтобы ваш сервер был доступен для обнаружения в локальной сети: opencode web --mdns Это автоматически устанавливает имя хоста `0.0.0.0` и объявляет сервер как `opencode.local`. Вы можете настроить доменное имя mDNS для запуска нескольких экземпляров в одной сети: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/ru/web#cors) Чтобы разрешить дополнительные домены для CORS (полезно для пользовательских интерфейсов): opencode web --cors https://example.com ### [Аутентификация](https://opencode.ai/docs/ru/web#%D0%B0%D1%83%D1%82%D0%B5%D0%BD%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F) Чтобы защитить доступ, установите пароль, используя переменную среды `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web Имя пользователя по умолчанию — `opencode`, но его можно изменить с помощью `OPENCODE_SERVER_USERNAME`. * * * [Использование веб-интерфейса](https://opencode.ai/docs/ru/web#%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B2%D0%B5%D0%B1-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D1%84%D0%B5%D0%B9%D1%81%D0%B0) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- После запуска веб-интерфейс предоставляет доступ к вашим сеансам opencode. ### [Сессии](https://opencode.ai/docs/ru/web#%D1%81%D0%B5%D1%81%D1%81%D0%B8%D0%B8) Просматривайте свои сеансы и управляйте ими с главной страницы. Вы можете видеть активные сеансы и начинать новые. ![opencode Web — активный сеанс](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [Статус сервера](https://opencode.ai/docs/ru/web#%D1%81%D1%82%D0%B0%D1%82%D1%83%D1%81-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D0%B0) Нажмите «Просмотреть серверы», чтобы просмотреть подключенные серверы и их статус. ![opencode Web — см. Серверы](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [Подключение терминала](https://opencode.ai/docs/ru/web#%D0%BF%D0%BE%D0%B4%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D1%82%D0%B5%D1%80%D0%BC%D0%B8%D0%BD%D0%B0%D0%BB%D0%B0) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Вы можете подключить TUI терминала к работающему веб-серверу: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 Это позволяет вам одновременно использовать веб-интерфейс и терминал, используя одни и те же сеансы и состояние. * * * [Конфигурационный файл](https://opencode.ai/docs/ru/web#%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B3%D1%83%D1%80%D0%B0%D1%86%D0%B8%D0%BE%D0%BD%D0%BD%D1%8B%D0%B9-%D1%84%D0%B0%D0%B9%D0%BB) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Вы также можете настроить параметры сервера в файле конфигурации `opencode.json`: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} CLI-флаги имеют приоритет над настройками файла конфигурации. --- # เว็บ | OpenCode [Skip to content](https://opencode.ai/docs/th/web#_top) เว็บ ==== การใช้ OpenCode ในเบราว์เซอร์ของคุณ OpenCode สามารถทำงานเป็นเว็บแอปพลิเคชันในเบราว์เซอร์ของคุณได้ โดยมอบประสบการณ์การเขียนโค้ด AI อันทรงพลังแบบเดียวกันโดยไม่ต้องใช้ terminal ![เว็บ OpenCode - เซสชันใหม่](https://opencode.ai/docs/_astro/web-homepage-new-session.BB1mEdgo_Z1AT1v3.webp) [เริ่มต้นใช้งาน](https://opencode.ai/docs/th/web#%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%95%E0%B9%89%E0%B8%99%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เริ่มเว็บอินเตอร์เฟสด้วยการรัน: opencode web สิ่งนี้จะเริ่มต้นเซิร์ฟเวอร์ท้องถิ่นบน `127.0.0.1` ด้วยพอร์ตที่มีอยู่แบบสุ่มและเปิด OpenCode โดยอัตโนมัติในเบราว์เซอร์เริ่มต้นของคุณ * * * [การกำหนดค่า](https://opencode.ai/docs/th/web#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2) --------------------------------------------------------------------------------------------------------------------------------------------------- คุณสามารถกำหนดค่าเว็บเซิร์ฟเวอร์ได้โดยใช้แฟล็กบรรทัดคำสั่งหรือใน [ไฟล์กำหนดค่า](https://opencode.ai/docs/config) ### [พอร์ต](https://opencode.ai/docs/th/web#%E0%B8%9E%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B8%95) ตามค่าเริ่มต้น OpenCode จะเลือกพอร์ตที่พร้อมใช้งาน คุณสามารถระบุพอร์ต: opencode web --port 4096 ### [ชื่อโฮสต์](https://opencode.ai/docs/th/web#%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B9%82%E0%B8%AE%E0%B8%AA%E0%B8%95%E0%B9%8C) ตามค่าเริ่มต้น เซิร์ฟเวอร์จะเชื่อมโยงกับ `127.0.0.1` (เฉพาะโลคัลโฮสต์เท่านั้น) หากต้องการให้ OpenCode เข้าถึงได้บนเครือข่ายของคุณ: opencode web --hostname 0.0.0.0 เมื่อใช้ `0.0.0.0` OpenCode จะแสดงทั้งที่อยู่ในท้องถิ่นและเครือข่าย: Local access: http://localhost:4096 Network access: http://192.168.1.100:4096 ### [การค้นพบ mDNS](https://opencode.ai/docs/th/web#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%84%E0%B9%89%E0%B8%99%E0%B8%9E%E0%B8%9A-mdns) เปิดใช้งาน mDNS เพื่อให้เซิร์ฟเวอร์ของคุณค้นพบได้บนเครือข่ายท้องถิ่น: opencode web --mdns สิ่งนี้จะตั้งชื่อโฮสต์เป็น `0.0.0.0` โดยอัตโนมัติและโฆษณาเซิร์ฟเวอร์เป็น `opencode.local` คุณสามารถปรับแต่งชื่อโดเมน mDNS เพื่อเรียกใช้หลายอินสแตนซ์บนเครือข่ายเดียวกันได้: opencode web --mdns --mdns-domain myproject.local ### [CORS](https://opencode.ai/docs/th/web#cors) หากต้องการอนุญาตโดเมนเพิ่มเติมสำหรับ CORS (มีประโยชน์สำหรับส่วนหน้าที่กำหนดเอง): opencode web --cors https://example.com ### [การรับรองความถูกต้อง](https://opencode.ai/docs/th/web#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%96%E0%B8%B9%E0%B8%81%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87) เพื่อป้องกันการเข้าถึง ให้ตั้งรหัสผ่านโดยใช้ตัวแปรสภาพแวดล้อม `OPENCODE_SERVER_PASSWORD`: OPENCODE_SERVER_PASSWORD=secret opencode web ชื่อผู้ใช้มีค่าเริ่มต้นเป็น `opencode` แต่สามารถเปลี่ยนได้ด้วย `OPENCODE_SERVER_USERNAME` * * * [การใช้เว็บอินเตอร์เฟส](https://opencode.ai/docs/th/web#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B9%80%E0%B8%A7%E0%B9%87%E0%B8%9A%E0%B8%AD%E0%B8%B4%E0%B8%99%E0%B9%80%E0%B8%95%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B9%80%E0%B8%9F%E0%B8%AA) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เมื่อเริ่มต้นแล้ว เว็บอินเตอร์เฟสจะให้สิทธิ์การเข้าถึงเซสชัน OpenCode ของคุณ ### [เซสชัน](https://opencode.ai/docs/th/web#%E0%B9%80%E0%B8%8B%E0%B8%AA%E0%B8%8A%E0%B8%B1%E0%B8%99) ดูและจัดการเซสชันของคุณจากหน้าแรก คุณสามารถดูเซสชันที่ใช้งานอยู่และเริ่มต้นเซสชันใหม่ได้ ![OpenCode Web - เซสชันที่ใช้งานอยู่](https://opencode.ai/docs/_astro/web-homepage-active-session.BbK4Ph6e_Z1O7nO1.webp) ### [สถานะเซิร์ฟเวอร์](https://opencode.ai/docs/th/web#%E0%B8%AA%E0%B8%96%E0%B8%B2%E0%B8%99%E0%B8%B0%E0%B9%80%E0%B8%8B%E0%B8%B4%E0%B8%A3%E0%B9%8C%E0%B8%9F%E0%B9%80%E0%B8%A7%E0%B8%AD%E0%B8%A3%E0%B9%8C) คลิก “ดูเซิร์ฟเวอร์” เพื่อดูเซิร์ฟเวอร์ที่เชื่อมต่อและสถานะ ![เว็บ OpenCode - ดูเซิร์ฟเวอร์](https://opencode.ai/docs/_astro/web-homepage-see-servers.BpCOef2l_ZB0rJd.webp) * * * [การต่อ terminal](https://opencode.ai/docs/th/web#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%95%E0%B9%88%E0%B8%AD-terminal) ------------------------------------------------------------------------------------------------------------------- คุณสามารถแนบ terminal TUI กับเว็บเซิร์ฟเวอร์ที่ทำงานอยู่: # Start the web serveropencode web --port 4096 # In another terminal, attach the TUIopencode attach http://localhost:4096 ซึ่งจะทำให้คุณสามารถใช้ทั้งเว็บอินเทอร์เฟซและ terminal พร้อมกัน โดยแชร์เซสชันและสถานะเดียวกัน * * * [ไฟล์กำหนดค่า](https://opencode.ai/docs/th/web#%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2) ------------------------------------------------------------------------------------------------------------------------------------------------------------- คุณยังสามารถกำหนดการตั้งค่าเซิร์ฟเวอร์ในไฟล์กำหนดค่า `opencode.json` ของคุณได้: { "server": { "port": 4096, "hostname": "0.0.0.0", "mdns": true, "cors": ["https://example.com"] }} ธงบรรทัดคำสั่งมีความสำคัญเหนือกว่าการตั้งค่าไฟล์กำหนดค่า --- # Плагины | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/plugins#_top) Плагины ======= Напишите свои собственные плагины для расширения opencode. Плагины позволяют расширять opencode, подключаясь к различным событиям и настраивая поведение. Вы можете создавать плагины для добавления новых функций, интеграции с внешними сервисами или изменения поведения opencode по умолчанию. Для примера ознакомьтесь с [plugins](https://opencode.ai/docs/ecosystem#plugins) , созданными сообществом. * * * [Используйте плагин](https://opencode.ai/docs/ru/plugins#%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D1%83%D0%B9%D1%82%D0%B5-%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD) ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Есть два способа загрузки плагинов. * * * ### [Из локальных файлов](https://opencode.ai/docs/ru/plugins#%D0%B8%D0%B7-%D0%BB%D0%BE%D0%BA%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D1%85-%D1%84%D0%B0%D0%B9%D0%BB%D0%BE%D0%B2) Поместите файлы JavaScript или TypeScript в каталог плагина. * `.opencode/plugins/` – плагины уровня проекта. * `~/.config/opencode/plugins/` — глобальные плагины Файлы в этих каталогах автоматически загружаются при запуске. * * * ### [Из npm](https://opencode.ai/docs/ru/plugins#%D0%B8%D0%B7-npm) Укажите пакеты npm в файле конфигурации. { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]} Поддерживаются как обычные, так и ограниченные пакеты npm. Просмотрите доступные плагины в папке [ecosystem](https://opencode.ai/docs/ecosystem#plugins) . * * * ### [Как устанавливаются плагины](https://opencode.ai/docs/ru/plugins#%D0%BA%D0%B0%D0%BA-%D1%83%D1%81%D1%82%D0%B0%D0%BD%D0%B0%D0%B2%D0%BB%D0%B8%D0%B2%D0%B0%D1%8E%D1%82%D1%81%D1%8F-%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD%D1%8B) **Плагины npm** устанавливаются автоматически с помощью Bun при запуске. Пакеты и их зависимости кэшируются в `~/.cache/opencode/node_modules/`. **Локальные плагины** загружаются непосредственно из каталога плагинов. Чтобы использовать внешние пакеты, вы должны создать `package.json` в своем каталоге конфигурации (см. [Зависимости](https://opencode.ai/docs/ru/plugins#dependencies) ) или опубликовать плагин в npm и [добавить его в свой config](https://opencode.ai/docs/config#plugins) . * * * ### [Порядок загрузки](https://opencode.ai/docs/ru/plugins#%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BE%D0%BA-%D0%B7%D0%B0%D0%B3%D1%80%D1%83%D0%B7%D0%BA%D0%B8) Плагины загружаются из всех источников, и все хуки запускаются последовательно. Порядок загрузки следующий: 1. Глобальная конфигурация (`~/.config/opencode/opencode.json`) 2. Конфигурация проекта (`opencode.json`) 3. Глобальный каталог плагинов (`~/.config/opencode/plugins/`) 4. Каталог плагинов проекта (`.opencode/plugins/`) Дубликаты пакетов npm с тем же именем и версией загружаются один раз. Однако локальный плагин и плагин npm со схожими именами загружаются отдельно. * * * [Создать плагин](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B7%D0%B4%D0%B0%D1%82%D1%8C-%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD) -------------------------------------------------------------------------------------------------------------------------------------- Плагин — это **модуль JavaScript/TypeScript**, который экспортирует один или несколько плагинов. функции. Каждая функция получает объект контекста и возвращает объект перехватчика. * * * ### [Зависимости](https://opencode.ai/docs/ru/plugins#%D0%B7%D0%B0%D0%B2%D0%B8%D1%81%D0%B8%D0%BC%D0%BE%D1%81%D1%82%D0%B8) Локальные плагины и специальные инструменты могут использовать внешние пакеты npm. Добавьте `package.json` в каталог конфигурации с необходимыми вам зависимостями. { "dependencies": { "shescape": "^2.1.0" }} opencode запускает `bun install` при запуске для их установки. Затем ваши плагины и инструменты смогут импортировать их. import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, }} * * * ### [Базовая структура](https://opencode.ai/docs/ru/plugins#%D0%B1%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D1%8F-%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0) export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here }} Функция плагина получает: * `project`: Текущая информация о проекте. * `directory`: текущий рабочий каталог. * `worktree`: путь к рабочему дереву git. * `client`: клиент SDK с открытым кодом для взаимодействия с ИИ. * `$`: [Bun shell API](https://bun.com/docs/runtime/shell) для выполнения команд. * * * ### [Поддержка TypeScript](https://opencode.ai/docs/ru/plugins#%D0%BF%D0%BE%D0%B4%D0%B4%D0%B5%D1%80%D0%B6%D0%BA%D0%B0-typescript) Для плагинов TypeScript вы можете импортировать типы из пакета плагина: import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations }} * * * ### [События](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F) Плагины могут подписываться на события, как показано ниже в разделе «Примеры». Вот список различных доступных событий. #### [Командные события](https://opencode.ai/docs/ru/plugins#%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D0%BD%D1%8B%D0%B5-%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F) * `command.executed` #### [События файла](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-%D1%84%D0%B0%D0%B9%D0%BB%D0%B0) * `file.edited` * `file.watcher.updated` #### [События установки](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-%D1%83%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B8) * `installation.updated` #### [События LSP](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-lsp) * `lsp.client.diagnostics` * `lsp.updated` #### [События сообщений](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-%D1%81%D0%BE%D0%BE%D0%B1%D1%89%D0%B5%D0%BD%D0%B8%D0%B9) * `message.part.removed` * `message.part.updated` * `message.removed` * `message.updated` #### [События разрешения](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-%D1%80%D0%B0%D0%B7%D1%80%D0%B5%D1%88%D0%B5%D0%BD%D0%B8%D1%8F) * `permission.asked` * `permission.replied` #### [События сервера](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D0%B0) * `server.connected` #### [События сессии](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-%D1%81%D0%B5%D1%81%D1%81%D0%B8%D0%B8) * `session.created` * `session.compacted` * `session.deleted` * `session.diff` * `session.error` * `session.idle` * `session.status` * `session.updated` #### [События](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-1) * `todo.updated` #### [События shell](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-shell) * `shell.env` #### [События инструмента](https://opencode.ai/docs/ru/plugins#%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F-%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%B0) * `tool.execute.after` * `tool.execute.before` #### [Мероприятия TUI](https://opencode.ai/docs/ru/plugins#%D0%BC%D0%B5%D1%80%D0%BE%D0%BF%D1%80%D0%B8%D1%8F%D1%82%D0%B8%D1%8F-tui) * `tui.prompt.append` * `tui.command.execute` * `tui.toast.show` * * * [Примеры](https://opencode.ai/docs/ru/plugins#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B) ------------------------------------------------------------------------------------------ Вот несколько примеров плагинов, которые вы можете использовать для расширения opencode. * * * ### [Отправлять уведомления](https://opencode.ai/docs/ru/plugins#%D0%BE%D1%82%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D1%8F%D1%82%D1%8C-%D1%83%D0%B2%D0%B5%D0%B4%D0%BE%D0%BC%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F) Отправляйте уведомления при возникновении определенных событий: 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"'` } }, }} Мы используем `osascript` для запуска AppleScript на macOS. Здесь мы используем его для отправки уведомлений. * * * ### [Защита .env](https://opencode.ai/docs/ru/plugins#%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0-env) Запретите открытому коду читать файлы `.env`: 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") } }, }} * * * ### [Внедрение переменных среды](https://opencode.ai/docs/ru/plugins#%D0%B2%D0%BD%D0%B5%D0%B4%D1%80%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D1%8B%D1%85-%D1%81%D1%80%D0%B5%D0%B4%D1%8B) Внедряйте переменные среды во все shell-процессы выполнения (инструменты искусственного интеллекта и пользовательские terminal): export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, }} * * * ### [Пользовательские инструменты](https://opencode.ai/docs/ru/plugins#%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B5-%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B) Плагины также могут добавлять в opencode собственные инструменты: 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})` }, }), }, }} Помощник `tool` создает собственный инструмент, который может вызывать opencode. Он принимает функцию схемы Zod и возвращает определение инструмента: * `description`: Что делает инструмент * `args`: схема Zod для аргументов инструмента. * `execute`: функция, которая запускается при вызове инструмента. Ваши пользовательские инструменты будут доступны для открытия кода наряду со встроенными инструментами. * * * ### [Ведение журнала](https://opencode.ai/docs/ru/plugins#%D0%B2%D0%B5%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B6%D1%83%D1%80%D0%BD%D0%B0%D0%BB%D0%B0) Используйте `client.app.log()` вместо `console.log` для структурированного ведения журнала: export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, })} Уровни: `debug`, `info`, `warn`, `error`. Подробности см. в документации SDK\]([https://opencode.ai/docs/sdk](https://opencode.ai/docs/sdk) ). * * * ### [Хуки сжатия](https://opencode.ai/docs/ru/plugins#%D1%85%D1%83%D0%BA%D0%B8-%D1%81%D0%B6%D0%B0%D1%82%D0%B8%D1%8F) Настройте контекст, включаемый при сжатии сеанса: 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`) }, }} Хук `experimental.session.compacting` срабатывает до того, как LLM сгенерирует сводку для продолжения. Используйте его для внедрения контекста, специфичного для домена, который будет пропущен при запросе на сжатие по умолчанию. Вы также можете полностью заменить запрос на уплотнение, установив `output.prompt`: 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 status2. Which files are being modified and by whom3. Any blockers or dependencies between agents4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work.` }, }} Если установлен `output.prompt`, он полностью заменяет приглашение на сжатие по умолчанию. Массив `output.context` в этом случае игнорируется. --- # LSPサーバー | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/lsp#_top) LSPサーバー ======= OpenCode は LSP サーバーと統合します。 OpenCode は言語サーバープロトコル (LSP) と統合して、LLM がコードベースと対話できるようにします。診断を使用して LLM にフィードバックを提供します。 * * * [組み込み](https://opencode.ai/docs/ja/lsp#%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF) ----------------------------------------------------------------------------- OpenCode には、一般的な言語用のいくつかの組み込み LSP サーバーが付属しています。 | 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 | `.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 | | 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 サーバーは自動的に有効になります。 * * * [仕組み](https://opencode.ai/docs/ja/lsp#%E4%BB%95%E7%B5%84%E3%81%BF) ------------------------------------------------------------------- OpenCode がファイルを開くと、次のようになります。 1. 有効なすべての LSP サーバーに対してファイル拡張子をチェックします。 2. 適切な LSP サーバーがまだ実行されていない場合は開始します。 * * * [設定](https://opencode.ai/docs/ja/lsp#%E8%A8%AD%E5%AE%9A) --------------------------------------------------------- OpenCode 設定の `lsp` セクションを通じて LSP サーバーをカスタマイズできます。 { "$schema": "https://opencode.ai/config.json", "lsp": {}} 各 LSP サーバーは以下をサポートします。 | プロパティ | タイプ | 説明 | | --- | --- | --- | | `disabled` | ブール値 | LSP サーバーを無効にするには、これを `true` に設定します。 | | `command` | 文字列\[\] | LSP サーバーを起動するコマンド | | `extensions` | 文字列\[\] | この LSP サーバーが処理するファイル拡張子 | | `env` | オブジェクト | サーバーの起動時に設定する環境変数 | | `initialization` | オブジェクト | LSP サーバーに送信する初期化オプション | いくつかの例を見てみましょう。 * * * ### [環境変数](https://opencode.ai/docs/ja/lsp#%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0) LSP サーバーの起動時に `env` プロパティを使用して環境変数を設定します。 { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [初期化オプション](https://opencode.ai/docs/ja/lsp#%E5%88%9D%E6%9C%9F%E5%8C%96%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%B3) `initialization` プロパティを使用して、初期化オプションを LSP サーバーに渡します。これらは、LSP `initialize` リクエスト中に送信されるサーバー固有の設定です。 { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [LSPサーバーの無効化](https://opencode.ai/docs/ja/lsp#lsp%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E3%81%AE%E7%84%A1%E5%8A%B9%E5%8C%96) **すべて** LSP サーバーをグローバルに無効にするには、`lsp` を `false` に設定します。 { "$schema": "https://opencode.ai/config.json", "lsp": false} **特定** LSP サーバーを無効にするには、`disabled` を `true` に設定します。 { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [カスタム LSP サーバー](https://opencode.ai/docs/ja/lsp#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0-lsp-%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC) コマンドとファイル拡張子を指定して、カスタム LSP サーバーを追加できます。 { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [追加情報](https://opencode.ai/docs/ja/lsp#%E8%BF%BD%E5%8A%A0%E6%83%85%E5%A0%B1) ----------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/ja/lsp#php-intelephense) PHP Intelephense は、ライセンスキーを通じてプレミアム機能を提供します。ライセンスキーを指定するには、次の場所にあるテキストファイルにキー (のみ) を配置します。 * macOS/Linux の場合: `$HOME/intelephense/license.txt` * Windows の場合: `%USERPROFILE%/intelephense/license.txt` ファイルにはライセンスキーのみが含まれており、追加のコンテンツは含まれていません。 --- # LSP Server | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/lsp#_top) LSP Server ========== OpenCode lässt sich in Ihren LSP-Server integrieren. OpenCode lässt sich in Ihr Language Server Protocol (LSP) integrieren, um die Interaktion von LLM mit Ihrer Codebasis zu unterstützen. Es verwendet Diagnosefunktionen, um dem LLM Feedback zu geben. * * * [Integriert](https://opencode.ai/docs/de/lsp#integriert) --------------------------------------------------------- OpenCode verfügt über mehrere integrierte LSP-Server für gängige Sprachen: | LSP Server | Erweiterungen | Anforderungen | | --- | --- | --- | | astro | .astro | Automatische Installation für Astro-Projekte | | bash | .sh, .bash, .zsh, .ksh | Installiert den bash-language-server automatisch | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Automatische Installation für C/C++-Projekte | | csharp | .cs | `.NET SDK` installed | | clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp`\-Befehl verfügbar | | dart | .dart | `dart`\-Befehl verfügbar | | deno | .ts, .tsx, .js, .jsx, .mjs | `deno`\-Befehl verfügbar (automatische Erkennung von deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | `elixir`\-Befehl verfügbar | | 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`\-Befehl verfügbar | | gopls | .go | `go`\-Befehl verfügbar | | hls | .hs, .lhs | `haskell-language-server-wrapper`\-Befehl verfügbar | | jdtls | .java | `Java SDK (version 21+)` installiert | | kotlin-ls | .kt, .kts | Automatische Installation für Kotlin-Projekte | | lua-ls | .lua | Automatische Installation für Lua-Projekte | | nixd | .nix | `nixd`\-Befehl verfügbar | | ocaml-lsp | .ml, .mli | `ocamllsp`\-Befehl verfügbar | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` dependency in project | | php intelephense | .php | Automatische Installation für PHP-Projekte | | prisma | .prisma | `prisma`\-Befehl verfügbar | | pyright | .py, .pyi | `pyright` dependency installed | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Befehle `ruby` und `gem` verfügbar | | rust | .rs | `rust-analyzer`\-Befehl verfügbar | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` installed (`xcode` on macOS) | | svelte | .svelte | Automatische Installation für Svelte-Projekte | | terraform | .tf, .tfvars | Automatische Installation von GitHub-Releases | | tinymist | .typ, .typc | Automatische Installation von GitHub-Releases | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project | | vue | .vue | Automatische Installation für Vue-Projekte | | yaml-ls | .yaml, .yml | Installiert den Red Hat yaml-language-server automatisch | | zls | .zig, .zon | `zig`\-Befehl verfügbar | LSP-Server werden automatisch aktiviert, wenn eine der oben genannten Dateierweiterungen erkannt wird und die Anforderungen erfüllt sind. * * * [Funktionsweise](https://opencode.ai/docs/de/lsp#funktionsweise) ----------------------------------------------------------------- Wenn OpenCode eine Datei öffnet, geschieht Folgendes: 1. Überprüft die Dateierweiterung anhand aller aktivierten LSP-Server. 2. Startet den entsprechenden LSP-Server, falls er noch nicht ausgeführt wird. * * * [Konfiguration](https://opencode.ai/docs/de/lsp#konfiguration) --------------------------------------------------------------- Sie können LSP-Server über den Abschnitt `lsp` in Ihrer OpenCode-Konfiguration anpassen. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Jeder LSP-Server unterstützt Folgendes: | Eigentum | Geben Sie | ein Beschreibung | | --- | --- | --- | | `disabled` | boolescher Wert | Setzen Sie dies auf `true`, um den LSP-Server zu deaktivieren | | `command` | string\[\] | Der Befehl zum Starten des LSP-Servers | | `extensions` | string\[\] | Dateierweiterungen, die dieser LSP-Server verarbeiten soll | | `env` | Objekt | Umgebungsvariablen, die beim Starten des Servers festgelegt werden | | `initialization` | Objekt | Initialisierungsoptionen zum Senden an den LSP-Server | Schauen wir uns einige Beispiele an. * * * ### [Umgebungsvariablen](https://opencode.ai/docs/de/lsp#umgebungsvariablen) Verwenden Sie die Eigenschaft `env`, um Umgebungsvariablen festzulegen, wenn Sie den Server LSP starten: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Initialisierungsoptionen](https://opencode.ai/docs/de/lsp#initialisierungsoptionen) Verwenden Sie die Eigenschaft `initialization`, um Initialisierungsoptionen an den Server LSP zu übergeben. Dies sind serverspezifische Einstellungen, die während der LSP `initialize`\-Anfrage gesendet werden: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Deaktivieren von LSP-Servern](https://opencode.ai/docs/de/lsp#deaktivieren-von-lsp-servern) Um **alle** LSP-Server global zu deaktivieren, setzen Sie `lsp` auf `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} Um einen **bestimmten** LSP-Server zu deaktivieren, setzen Sie `disabled` auf `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Benutzerdefinierter LSP-Server](https://opencode.ai/docs/de/lsp#benutzerdefinierter-lsp-server) Sie können einen benutzerdefinierten LSP-Server hinzufügen, indem Sie den Befehl und die Dateierweiterungen angeben: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Weitere Informationen](https://opencode.ai/docs/de/lsp#weitere-informationen) ------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/de/lsp#php-intelephense) PHP Intelepense bietet Premium-Funktionen über einen Lizenzschlüssel. Sie können einen Lizenzschlüssel bereitstellen, indem Sie (nur) den Schlüssel in eine Textdatei einfügen unter: * Auf macOS/Linux: `$HOME/intelephense/license.txt` * Unter Windows: `%USERPROFILE%/intelephense/license.txt` Die Datei sollte nur den Lizenzschlüssel ohne zusätzlichen Inhalt enthalten. --- # Tools | OpenCode [Skip to content](https://opencode.ai/docs/tools#_top) Tools ===== Manage the tools an LLM can use. Tools allow the LLM to perform actions in your codebase. OpenCode comes with a set of built-in tools, but you can extend it with [custom tools](https://opencode.ai/docs/custom-tools) or [MCP servers](https://opencode.ai/docs/mcp-servers) . By default, all tools are **enabled** and don’t need permission to run. You can control tool behavior through [permissions](https://opencode.ai/docs/permissions) . * * * [Configure](https://opencode.ai/docs/tools#configure) ------------------------------------------------------ Use the `permission` field to control tool behavior. You can allow, deny, or require approval for each tool. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} You can also use wildcards to control multiple tools at once. For example, to require approval for all tools from an MCP server: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Learn more](https://opencode.ai/docs/permissions) about configuring permissions. * * * [Built-in](https://opencode.ai/docs/tools#built-in) ---------------------------------------------------- Here are all the built-in tools available in OpenCode. * * * ### [bash](https://opencode.ai/docs/tools#bash) Execute shell commands in your project environment. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} This tool allows the LLM to run terminal commands like `npm install`, `git status`, or any other shell command. * * * ### [edit](https://opencode.ai/docs/tools#edit) Modify existing files using exact string replacements. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} This tool performs precise edits to files by replacing exact text matches. It’s the primary way the LLM modifies code. * * * ### [write](https://opencode.ai/docs/tools#write) Create new files or overwrite existing ones. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Use this to allow the LLM to create new files. It will overwrite existing files if they already exist. * * * ### [read](https://opencode.ai/docs/tools#read) Read file contents from your codebase. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} This tool reads files and returns their contents. It supports reading specific line ranges for large files. * * * ### [grep](https://opencode.ai/docs/tools#grep) Search file contents using regular expressions. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Fast content search across your codebase. Supports full regex syntax and file pattern filtering. * * * ### [glob](https://opencode.ai/docs/tools#glob) Find files by pattern matching. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Search for files using glob patterns like `**/*.js` or `src/**/*.ts`. Returns matching file paths sorted by modification time. * * * ### [list](https://opencode.ai/docs/tools#list) List files and directories in a given path. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} This tool lists directory contents. It accepts glob patterns to filter results. * * * ### [lsp (experimental)](https://opencode.ai/docs/tools#lsp-experimental) Interact with your configured LSP servers to get code intelligence features like definitions, references, hover info, and call hierarchy. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Supported operations include `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls`, and `outgoingCalls`. To configure which LSP servers are available for your project, see [LSP Servers](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/tools#patch) Apply patches to files. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} This tool applies patch files to your codebase. Useful for applying diffs and patches from various sources. * * * ### [skill](https://opencode.ai/docs/tools#skill) Load a [skill](https://opencode.ai/docs/skills) (a `SKILL.md` file) and return its content in the conversation. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/tools#todowrite) Manage todo lists during coding sessions. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Creates and updates task lists to track progress during complex operations. The LLM uses this to organize multi-step tasks. * * * ### [todoread](https://opencode.ai/docs/tools#todoread) Read existing todo lists. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Reads the current todo list state. Used by the LLM to track what tasks are pending or completed. * * * ### [webfetch](https://opencode.ai/docs/tools#webfetch) Fetch web content. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Allows the LLM to fetch and read web pages. Useful for looking up documentation or researching online resources. * * * ### [websearch](https://opencode.ai/docs/tools#websearch) Search the web for information. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Performs web searches using Exa AI to find relevant information online. Useful for researching topics, finding current events, or gathering information beyond the training data cutoff. No API key is required — the tool connects directly to Exa AI’s hosted MCP service without authentication. * * * ### [question](https://opencode.ai/docs/tools#question) Ask the user questions during execution. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} This tool allows the LLM to ask the user questions during a task. It’s useful for: * Gathering user preferences or requirements * Clarifying ambiguous instructions * Getting decisions on implementation choices * Offering choices about what direction to take Each question includes a header, the question text, and a list of options. Users can select from the provided options or type a custom answer. When there are multiple questions, users can navigate between them before submitting all answers. * * * [Custom tools](https://opencode.ai/docs/tools#custom-tools) ------------------------------------------------------------ Custom tools let you define your own functions that the LLM can call. These are defined in your config file and can execute arbitrary code. [Learn more](https://opencode.ai/docs/custom-tools) about creating custom tools. * * * [MCP servers](https://opencode.ai/docs/tools#mcp-servers) ---------------------------------------------------------- MCP (Model Context Protocol) servers allow you to integrate external tools and services. This includes database access, API integrations, and third-party services. [Learn more](https://opencode.ai/docs/mcp-servers) about configuring MCP servers. * * * [Internals](https://opencode.ai/docs/tools#internals) ------------------------------------------------------ Internally, tools like `grep`, `glob`, and `list` use [ripgrep](https://github.com/BurntSushi/ripgrep) under the hood. By default, ripgrep respects `.gitignore` patterns, which means files and directories listed in your `.gitignore` will be excluded from searches and listings. * * * ### [Ignore patterns](https://opencode.ai/docs/tools#ignore-patterns) To include files that would normally be ignored, create a `.ignore` file in your project root. This file can explicitly allow certain paths. !node_modules/!dist/!build/ For example, this `.ignore` file allows ripgrep to search within `node_modules/`, `dist/`, and `build/` directories even if they’re listed in `.gitignore`. --- # 工具 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/tools#_top) 工具 == 管理 LLM 可以使用的工具。 工具允许 LLM 在您的代码库中执行操作。OpenCode 自带一组内置工具,您也可以通过[自定义工具](https://opencode.ai/docs/custom-tools) 或 [MCP 服务器](https://opencode.ai/docs/mcp-servers) 来扩展它。 默认情况下,所有工具都是**启用**的,且无需权限即可运行。您可以通过[权限](https://opencode.ai/docs/permissions) 来控制工具的行为。 * * * [配置](https://opencode.ai/docs/zh-cn/tools#%E9%85%8D%E7%BD%AE) -------------------------------------------------------------- 使用 `permission` 字段来控制工具行为。您可以对每个工具设置允许、拒绝或需要审批。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} 您还可以使用通配符同时控制多个工具。例如,要求某个 MCP 服务器的所有工具都需要审批: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [了解更多](https://opencode.ai/docs/permissions) 关于配置权限的内容。 * * * [内置工具](https://opencode.ai/docs/zh-cn/tools#%E5%86%85%E7%BD%AE%E5%B7%A5%E5%85%B7) ---------------------------------------------------------------------------------- 以下是 OpenCode 中所有可用的内置工具。 * * * ### [bash](https://opencode.ai/docs/zh-cn/tools#bash) 在项目环境中执行 shell 命令。 { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} 该工具允许 LLM 运行终端命令,例如 `npm install`、`git status` 或其他任何 shell 命令。 * * * ### [edit](https://opencode.ai/docs/zh-cn/tools#edit) 通过精确的字符串替换来修改现有文件。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 该工具通过替换精确匹配的文本来对文件进行编辑。这是 LLM 修改代码的主要方式。 * * * ### [write](https://opencode.ai/docs/zh-cn/tools#write) 创建新文件或覆盖现有文件。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 使用此工具允许 LLM 创建新文件。如果文件已存在,则会覆盖现有文件。 * * * ### [read](https://opencode.ai/docs/zh-cn/tools#read) 读取代码库中的文件内容。 { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} 该工具读取文件并返回其内容。它支持对大文件读取指定行范围。 * * * ### [grep](https://opencode.ai/docs/zh-cn/tools#grep) 使用正则表达式搜索文件内容。 { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} 在代码库中快速搜索内容。支持完整的正则表达式语法和文件模式过滤。 * * * ### [glob](https://opencode.ai/docs/zh-cn/tools#glob) 通过模式匹配查找文件。 { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} 使用 `**/*.js` 或 `src/**/*.ts` 等 glob 模式搜索文件。返回按修改时间排序的匹配文件路径。 * * * ### [list](https://opencode.ai/docs/zh-cn/tools#list) 列出指定路径下的文件和目录。 { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} 该工具用于列出目录内容。它接受 glob 模式来过滤结果。 * * * ### [lsp(实验性)](https://opencode.ai/docs/zh-cn/tools#lsp%E5%AE%9E%E9%AA%8C%E6%80%A7) 与已配置的 LSP 服务器交互,获取代码智能功能,如定义跳转、引用查找、悬停信息和调用层次结构。 { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} 支持的操作包括 `goToDefinition`、`findReferences`、`hover`、`documentSymbol`、`workspaceSymbol`、`goToImplementation`、`prepareCallHierarchy`、`incomingCalls` 和 `outgoingCalls`。 要配置项目可用的 LSP 服务器,请参阅 [LSP 服务器](https://opencode.ai/docs/lsp) 。 * * * ### [patch](https://opencode.ai/docs/zh-cn/tools#patch) 对文件应用补丁。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 该工具将补丁文件应用到您的代码库中。适用于应用来自各种来源的 diff 和补丁。 * * * ### [skill](https://opencode.ai/docs/zh-cn/tools#skill) 加载一个[技能](https://opencode.ai/docs/skills) (即 `SKILL.md` 文件)并在对话中返回其内容。 { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/zh-cn/tools#todowrite) 在编码会话中管理待办事项列表。 { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} 创建和更新任务列表以跟踪复杂操作的进度。LLM 使用此工具来组织多步骤任务。 * * * ### [todoread](https://opencode.ai/docs/zh-cn/tools#todoread) 读取现有的待办事项列表。 { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} 读取当前待办事项列表的状态。LLM 使用此工具来跟踪哪些任务待处理、哪些已完成。 * * * ### [webfetch](https://opencode.ai/docs/zh-cn/tools#webfetch) 获取网页内容。 { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} 允许 LLM 获取并读取网页内容。适用于查阅文档或研究在线资源。 * * * ### [websearch](https://opencode.ai/docs/zh-cn/tools#websearch) 在网络上搜索信息。 { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} 使用 Exa AI 进行网络搜索以查找相关信息。适用于研究主题、了解时事动态或获取超出训练数据截止日期的信息。 无需 API 密钥——该工具无需身份验证即可直接连接到 Exa AI 的托管 MCP 服务。 * * * ### [question](https://opencode.ai/docs/zh-cn/tools#question) 在执行过程中向用户提问。 { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} 该工具允许 LLM 在执行任务期间向用户提问。适用于以下场景: * 收集用户偏好或需求 * 澄清模糊的指令 * 获取实现方案的决策 * 提供方向选择的选项 每个问题包含标题、问题正文和选项列表。用户可以从提供的选项中选择,也可以输入自定义答案。当有多个问题时,用户可以在提交所有答案之前在各问题之间切换浏览。 * * * [自定义工具](https://opencode.ai/docs/zh-cn/tools#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%B7%A5%E5%85%B7) -------------------------------------------------------------------------------------------- 自定义工具允许您定义 LLM 可以调用的自定义函数。这些函数在您的配置文件中定义,可以执行任意代码。 [了解更多](https://opencode.ai/docs/custom-tools) 关于创建自定义工具的内容。 * * * [MCP 服务器](https://opencode.ai/docs/zh-cn/tools#mcp-%E6%9C%8D%E5%8A%A1%E5%99%A8) -------------------------------------------------------------------------------- MCP(Model Context Protocol)服务器允许您集成外部工具和服务,包括数据库访问、API 集成和第三方服务。 [了解更多](https://opencode.ai/docs/mcp-servers) 关于配置 MCP 服务器的内容。 * * * [内部机制](https://opencode.ai/docs/zh-cn/tools#%E5%86%85%E9%83%A8%E6%9C%BA%E5%88%B6) ---------------------------------------------------------------------------------- 在内部,`grep`、`glob` 和 `list` 等工具底层使用 [ripgrep](https://github.com/BurntSushi/ripgrep) 。默认情况下,ripgrep 遵循 `.gitignore` 中的模式,这意味着 `.gitignore` 中列出的文件和目录将被排除在搜索和列表结果之外。 * * * ### [忽略模式](https://opencode.ai/docs/zh-cn/tools#%E5%BF%BD%E7%95%A5%E6%A8%A1%E5%BC%8F) 要包含通常会被忽略的文件,请在项目根目录下创建一个 `.ignore` 文件。该文件可以显式允许某些路径。 !node_modules/!dist/!build/ 例如,这个 `.ignore` 文件允许 ripgrep 在 `node_modules/`、`dist/` 和 `build/` 目录中进行搜索,即使它们已在 `.gitignore` 中列出。 --- # Ferramentas | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/tools#_top) Ferramentas =========== Gerencie as ferramentas que um LLM pode usar. As ferramentas permitem que o LLM execute ações em sua base de código. O opencode vem com um conjunto de ferramentas integradas, mas você pode estendê-lo com [ferramentas personalizadas](https://opencode.ai/docs/custom-tools) ou [servidores MCP](https://opencode.ai/docs/mcp-servers) . Por padrão, todas as ferramentas estão **ativadas** e não precisam de permissão para serem executadas. Você pode controlar o comportamento das ferramentas através de [permissões](https://opencode.ai/docs/permissions) . * * * [Configuração](https://opencode.ai/docs/pt-br/tools#configura%C3%A7%C3%A3o) ---------------------------------------------------------------------------- Use o campo `permission` para controlar o comportamento das ferramentas. Você pode permitir, negar ou exigir aprovação para cada ferramenta. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Você também pode usar curingas para controlar várias ferramentas ao mesmo tempo. Por exemplo, para exigir aprovação para todas as ferramentas de um servidor MCP: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Saiba mais](https://opencode.ai/docs/permissions) sobre como configurar permissões. * * * [Integradas](https://opencode.ai/docs/pt-br/tools#integradas) -------------------------------------------------------------- Aqui estão todas as ferramentas integradas disponíveis no opencode. * * * ### [bash](https://opencode.ai/docs/pt-br/tools#bash) Execute comandos de shell no ambiente do seu projeto. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Esta ferramenta permite que o LLM execute comandos de terminal como `npm install`, `git status` ou qualquer outro comando de shell. * * * ### [edit](https://opencode.ai/docs/pt-br/tools#edit) Modifique arquivos existentes usando substituições de string exatas. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Esta ferramenta realiza edições precisas em arquivos substituindo correspondências de texto exatas. É a principal forma como o LLM modifica o código. * * * ### [write](https://opencode.ai/docs/pt-br/tools#write) Crie novos arquivos ou sobrescreva os existentes. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Use isso para permitir que o LLM crie novos arquivos. Ele sobrescreverá arquivos existentes se já existirem. * * * ### [read](https://opencode.ai/docs/pt-br/tools#read) Leia o conteúdo dos arquivos da sua base de código. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Esta ferramenta lê arquivos e retorna seus conteúdos. Suporta a leitura de intervalos de linhas específicos para arquivos grandes. * * * ### [grep](https://opencode.ai/docs/pt-br/tools#grep) Pesquise o conteúdo dos arquivos usando expressões regulares. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Busca rápida de conteúdo em sua base de código. Suporta a sintaxe completa de regex e filtragem de padrões de arquivos. * * * ### [glob](https://opencode.ai/docs/pt-br/tools#glob) Encontre arquivos por correspondência de padrões. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Pesquise arquivos usando padrões glob como `**/*.js` ou `src/**/*.ts`. Retorna caminhos de arquivos correspondentes ordenados por tempo de modificação. * * * ### [list](https://opencode.ai/docs/pt-br/tools#list) Liste arquivos e diretórios em um determinado caminho. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Esta ferramenta lista o conteúdo do diretório. Aceita padrões glob para filtrar resultados. * * * ### [lsp (experimental)](https://opencode.ai/docs/pt-br/tools#lsp-experimental) Interaja com seus servidores LSP configurados para obter recursos de inteligência de código, como definições, referências, informações de hover e hierarquia de chamadas. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} As operações suportadas incluem `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` e `outgoingCalls`. Para configurar quais servidores LSP estão disponíveis para seu projeto, veja [Servidores LSP](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/pt-br/tools#patch) Aplique patches a arquivos. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Esta ferramenta aplica arquivos de patch à sua base de código. Útil para aplicar diffs e patches de várias fontes. * * * ### [skill](https://opencode.ai/docs/pt-br/tools#skill) Carregue uma [skill](https://opencode.ai/docs/skills) (um arquivo `SKILL.md`) e retorne seu conteúdo na conversa. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/pt-br/tools#todowrite) Gerencie listas de tarefas durante sessões de codificação. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Cria e atualiza listas de tarefas para acompanhar o progresso durante operações complexas. O LLM usa isso para organizar tarefas de múltiplas etapas. * * * ### [todoread](https://opencode.ai/docs/pt-br/tools#todoread) Leia listas de tarefas existentes. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Lê o estado atual da lista de tarefas. Usado pelo LLM para acompanhar quais tarefas estão pendentes ou concluídas. * * * ### [webfetch](https://opencode.ai/docs/pt-br/tools#webfetch) Busque conteúdo da web. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Permite que o LLM busque e leia páginas da web. Útil para consultar documentação ou pesquisar recursos online. * * * ### [websearch](https://opencode.ai/docs/pt-br/tools#websearch) Pesquise na web por informações. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Realiza buscas na web usando Exa AI para encontrar informações relevantes online. Útil para pesquisar tópicos, encontrar eventos atuais ou reunir informações além do limite de dados de treinamento. Nenhuma chave de API é necessária — a ferramenta se conecta diretamente ao serviço MCP hospedado da Exa AI sem autenticação. * * * ### [question](https://opencode.ai/docs/pt-br/tools#question) Faça perguntas ao usuário durante a execução. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Esta ferramenta permite que o LLM faça perguntas ao usuário durante uma tarefa. É útil para: * Coletar preferências ou requisitos do usuário * Esclarecer instruções ambíguas * Obter decisões sobre escolhas de implementação * Oferecer opções sobre qual direção seguir Cada pergunta inclui um cabeçalho, o texto da pergunta e uma lista de opções. Os usuários podem selecionar entre as opções fornecidas ou digitar uma resposta personalizada. Quando há várias perguntas, os usuários podem navegar entre elas antes de enviar todas as respostas. * * * [Ferramentas personalizadas](https://opencode.ai/docs/pt-br/tools#ferramentas-personalizadas) ---------------------------------------------------------------------------------------------- Ferramentas personalizadas permitem que você defina suas próprias funções que o LLM pode chamar. Estas são definidas em seu arquivo de configuração e podem executar código arbitrário. [Saiba mais](https://opencode.ai/docs/custom-tools) sobre como criar ferramentas personalizadas. * * * [Servidores MCP](https://opencode.ai/docs/pt-br/tools#servidores-mcp) ---------------------------------------------------------------------- Servidores MCP (Model Context Protocol) permitem que você integre ferramentas e serviços externos. Isso inclui acesso a bancos de dados, integrações de API e serviços de terceiros. [Saiba mais](https://opencode.ai/docs/mcp-servers) sobre como configurar servidores MCP. * * * [Internos](https://opencode.ai/docs/pt-br/tools#internos) ---------------------------------------------------------- Internamente, ferramentas como `grep`, `glob` e `list` usam [ripgrep](https://github.com/BurntSushi/ripgrep) por trás dos panos. Por padrão, o ripgrep respeita padrões `.gitignore`, o que significa que arquivos e diretórios listados em seu `.gitignore` serão excluídos de buscas e listagens. * * * ### [Padrões de ignorar](https://opencode.ai/docs/pt-br/tools#padr%C3%B5es-de-ignorar) Para incluir arquivos que normalmente seriam ignorados, crie um arquivo `.ignore` na raiz do seu projeto. Este arquivo pode permitir explicitamente certos caminhos. !node_modules/!dist/!build/ Por exemplo, este arquivo `.ignore` permite que o ripgrep busque dentro dos diretórios `node_modules/`, `dist/` e `build/`, mesmo que estejam listados em `.gitignore`. --- # Tools | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/tools#_top) Tools ===== Verwalte, welche Tools ein LLM nutzen darf. Tools erlauben dem LLM Aktionen in deiner Codebasis. OpenCode bringt eingebaute Tools mit und laesst sich ueber [Custom Tools](https://opencode.ai/docs/custom-tools) oder [MCP-Server](https://opencode.ai/docs/mcp-servers) erweitern. Standardmaessig sind alle Tools **aktiviert** und brauchen keine Freigabe. Das Verhalten steuerst du ueber [Berechtigungen](https://opencode.ai/docs/permissions) . * * * [Konfiguration](https://opencode.ai/docs/de/tools#konfiguration) ----------------------------------------------------------------- Nutze das Feld `permission`, um Tool-Verhalten zu steuern. Pro Tool kannst du erlauben, verbieten oder eine Rueckfrage verlangen. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Mit Wildcards kannst du mehrere Tools auf einmal steuern. Zum Beispiel, um fuer alle Tools eines MCP-Servers eine Freigabe zu verlangen: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Mehr dazu](https://opencode.ai/docs/permissions) , wie du Berechtigungen konfigurierst. * * * [Eingebaut](https://opencode.ai/docs/de/tools#eingebaut) --------------------------------------------------------- Hier sind alle in OpenCode verfuegbaren eingebauten Tools. * * * ### [bash](https://opencode.ai/docs/de/tools#bash) Fuehrt Shell-Befehle in deiner Projektumgebung aus. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Damit kann das LLM Terminal-Befehle wie `npm install`, `git status` oder andere Shell-Kommandos ausfuehren. * * * ### [edit](https://opencode.ai/docs/de/tools#edit) Bearbeitet bestehende Dateien ueber exakte String-Ersetzungen. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Dieses Tool fuehrt praezise Aenderungen per exakter Textsuche aus. Es ist der zentrale Weg, wie das LLM Code aendert. * * * ### [write](https://opencode.ai/docs/de/tools#write) Erstellt neue Dateien oder ueberschreibt bestehende Dateien. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Damit erlaubst du dem LLM, neue Dateien anzulegen. Bestehende Dateien werden dabei ueberschrieben. * * * ### [read](https://opencode.ai/docs/de/tools#read) Liest Dateiinhalte aus deiner Codebasis. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Dieses Tool liest Dateien und gibt deren Inhalt zurueck. Es unterstuetzt das Lesen spezifischer Zeilenbereiche bei grossen Dateien. * * * ### [grep](https://opencode.ai/docs/de/tools#grep) Durchsucht Dateiinhalte mit regulaeren Ausdruecken. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Schnelle Inhaltssuche in deiner Codebasis. Unterstuetzt volle Regex-Syntax und Filterung nach Dateimustern. * * * ### [glob](https://opencode.ai/docs/de/tools#glob) Findet Dateien per Musterabgleich. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Sucht nach Dateien mit Glob-Mustern wie `**/*.js` oder `src/**/*.ts`. Gibt passende Dateipfade sortiert nach Aenderungsdatum zurueck. * * * ### [list](https://opencode.ai/docs/de/tools#list) Listet Dateien und Verzeichnisse in einem Pfad auf. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Dieses Tool listet Verzeichnisinhalte auf. Es akzeptiert Glob-Muster zum Filtern der Ergebnisse. * * * ### [lsp (experimentell)](https://opencode.ai/docs/de/tools#lsp-experimentell) Interagiere mit deinen konfigurierten LSP-Servern fuer Code-Intelligence-Features wie Definitionen, Referenzen, Hover-Infos und Call-Hierarchien. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Unterstuetzte Operationen sind `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` und `outgoingCalls`. Um verfuegbare LSP-Server fuer dein Projekt zu konfigurieren, siehe [LSP-Server](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/de/tools#patch) Wendet Patches auf Dateien an. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Dieses Tool wendet Patch-Dateien auf deine Codebasis an. Nuetzlich fuer Diffs und Patches aus verschiedenen Quellen. * * * ### [skill](https://opencode.ai/docs/de/tools#skill) Laedt einen [Skill](https://opencode.ai/docs/skills) (eine `SKILL.md`\-Datei) und gibt dessen Inhalt in der Unterhaltung zurueck. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/de/tools#todowrite) Verwaltet Todo-Listen waehrend Coding-Sessions. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Erstellt und aktualisiert Aufgabenlisten, um den Fortschritt bei komplexen Operationen zu verfolgen. Das LLM nutzt dies, um mehrstufige Aufgaben zu organisieren. * * * ### [todoread](https://opencode.ai/docs/de/tools#todoread) Liest existierende Todo-Listen. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Liest den aktuellen Status der Todo-Liste. Wird vom LLM genutzt, um offene oder erledigte Aufgaben zu verfolgen. * * * ### [webfetch](https://opencode.ai/docs/de/tools#webfetch) Ruft Webinhalte ab. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Erlaubt dem LLM, Webseiten abzurufen und zu lesen. Nuetzlich zum Nachschlagen von Dokumentation oder fuer Online-Recherche. * * * ### [websearch](https://opencode.ai/docs/de/tools#websearch) Durchsucht das Web nach Informationen. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Fuehrt Websuchen mit Exa AI durch, um relevante Informationen online zu finden. Nuetzlich fuer Recherche, aktuelle Ereignisse oder Informationen jenseits des Trainingsdatums. Kein API-Key erforderlich — das Tool verbindet sich direkt mit dem gehosteten MCP-Service von Exa AI ohne Authentifizierung. * * * ### [question](https://opencode.ai/docs/de/tools#question) Stellt dem Benutzer waehrend der Ausfuehrung Fragen. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Dieses Tool erlaubt dem LLM, dem Benutzer waehrend einer Aufgabe Fragen zu stellen. Nuetzlich fuer: * Sammeln von Benutzerpraeferenzen oder Anforderungen * Klaerung mehrdeutiger Anweisungen * Entscheidungen bei Implementierungsoptionen einholen * Auswahlmoeglichkeiten fuer das weitere Vorgehen anbieten Jede Frage enthaelt eine Ueberschrift, den Fragetext und eine Liste von Optionen. Benutzer koennen aus den Optionen waehlen oder eine eigene Antwort eingeben. Bei mehreren Fragen koennen Benutzer zwischen ihnen navigieren, bevor sie alle Antworten absenden. * * * [Benutzerdefinierte Tools](https://opencode.ai/docs/de/tools#benutzerdefinierte-tools) --------------------------------------------------------------------------------------- Mit Custom Tools definierst du eigene Funktionen, die das LLM aufrufen kann. Sie werden in der Konfigurationsdatei definiert und koennen beliebigen Code ausfuehren. [Mehr dazu](https://opencode.ai/docs/custom-tools) , wie du Custom Tools erstellst. * * * [MCP-Server](https://opencode.ai/docs/de/tools#mcp-server) ----------------------------------------------------------- MCP-Server (Model Context Protocol) binden externe Tools und Dienste ein. Dazu gehoeren Datenbanken, API-Integrationen und Drittanbieter-Services. [Mehr dazu](https://opencode.ai/docs/mcp-servers) , wie du MCP-Server konfigurierst. * * * [Interna](https://opencode.ai/docs/de/tools#interna) ----------------------------------------------------- Intern verwenden Tools wie `grep`, `glob` und `list` [ripgrep](https://github.com/BurntSushi/ripgrep) . Standardmaessig beachtet ripgrep `.gitignore`, daher werden dort aufgefuehrte Dateien und Ordner nicht durchsucht. * * * ### [Ignorier-Muster](https://opencode.ai/docs/de/tools#ignorier-muster) Wenn du normalerweise ignorierte Dateien einschliessen willst, lege im Projekt-Root eine `.ignore`\-Datei an. Dort kannst du Pfade explizit erlauben. !node_modules/!dist/!build/ Dieses Beispiel erlaubt ripgrep, in `node_modules/`, `dist/` und `build/` zu suchen, auch wenn sie in `.gitignore` stehen. --- # Поиск неисправностей | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/troubleshooting#_top) Поиск неисправностей ==================== Распространенные проблемы и способы их решения. Чтобы устранить проблемы с opencode, начните с проверки журналов и локальных данных, которые он хранит на диске. * * * [Журналы](https://opencode.ai/docs/ru/troubleshooting#%D0%B6%D1%83%D1%80%D0%BD%D0%B0%D0%BB%D1%8B) -------------------------------------------------------------------------------------------------- Лог-файлы записываются в: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.local\share\opencode\log`. Файлам журналов присваиваются имена с метками времени (например, `2025-01-09T123456.log`), и сохраняются 10 последних файлов журналов. Вы можете установить уровень журнала с помощью CLI-параметра `--log-level`, чтобы получить более подробную информацию об отладке. Например, `opencode --log-level DEBUG`. * * * [Хранилище](https://opencode.ai/docs/ru/troubleshooting#%D1%85%D1%80%D0%B0%D0%BD%D0%B8%D0%BB%D0%B8%D1%89%D0%B5) ---------------------------------------------------------------------------------------------------------------- opencode хранит данные сеанса и другие данные приложения на диске по адресу: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.local\share\opencode`. Этот каталог содержит: * `auth.json` – данные аутентификации, такие как ключи API и токены OAuth. * `log/` – журналы приложений. * `project/` — данные, специфичные для проекта, такие как данные сеанса и сообщения. * Если проект находится в репозитории Git, он хранится в `.//storage/`. * Если это не репозиторий Git, он хранится в `./global/storage/`. * * * [Настольное приложение](https://opencode.ai/docs/ru/troubleshooting#%D0%BD%D0%B0%D1%81%D1%82%D0%BE%D0%BB%D1%8C%D0%BD%D0%BE%D0%B5-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- opencode Desktop запускает локальный сервер opencode (спутник `opencode-cli`) в фоновом режиме. Большинство проблем вызвано неправильно работающим плагином, поврежденным кешем или неверными настройками сервера. ### [Быстрые проверки](https://opencode.ai/docs/ru/troubleshooting#%D0%B1%D1%8B%D1%81%D1%82%D1%80%D1%8B%D0%B5-%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B8) * Полностью закройте и перезапустите приложение. * Если приложение отображает экран с ошибкой, нажмите **Перезапустить** и скопируйте сведения об ошибке. * Только для macOS: меню `OpenCode` -> **Обновить веб-просмотр** (помогает, если пользовательский интерфейс пуст или завис). * * * ### [Отключить плагины](https://opencode.ai/docs/ru/troubleshooting#%D0%BE%D1%82%D0%BA%D0%BB%D1%8E%D1%87%D0%B8%D1%82%D1%8C-%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD%D1%8B) Если настольное приложение дает сбой при запуске, зависает или ведет себя странно, начните с отключения плагинов. #### [Проверьте глобальную конфигурацию](https://opencode.ai/docs/ru/troubleshooting#%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D1%8C%D1%82%D0%B5-%D0%B3%D0%BB%D0%BE%D0%B1%D0%B0%D0%BB%D1%8C%D0%BD%D1%83%D1%8E-%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B3%D1%83%D1%80%D0%B0%D1%86%D0%B8%D1%8E) Откройте файл глобальной конфигурации и найдите ключ `plugin`. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (или `~/.config/opencode/opencode.json`) * **macOS/Linux** (более ранние версии): `~/.local/share/opencode/opencode.jsonc` * **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.config\opencode\opencode.jsonc`. Если у вас настроены плагины, временно отключите их, удалив ключ или установив для него пустой массив: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Проверьте каталоги плагинов](https://opencode.ai/docs/ru/troubleshooting#%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D1%8C%D1%82%D0%B5-%D0%BA%D0%B0%D1%82%D0%B0%D0%BB%D0%BE%D0%B3%D0%B8-%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD%D0%BE%D0%B2) opencode также может загружать локальные плагины с диска. Временно переместите их в сторону (или переименуйте папку) и перезапустите настольное приложение: * **Глобальные плагины** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.config\opencode\plugins`. * **Плагины проекта** (только если вы используете конфигурацию для каждого проекта) * `/.opencode/plugins/` Если приложение снова начнет работать, повторно включите плагины по одному, чтобы определить, какой из них вызывает проблему. * * * ### [Очистить кеш](https://opencode.ai/docs/ru/troubleshooting#%D0%BE%D1%87%D0%B8%D1%81%D1%82%D0%B8%D1%82%D1%8C-%D0%BA%D0%B5%D1%88) Если отключение плагинов не помогает (или установка плагина зависла), очистите кеш, чтобы opencode мог его пересобрать. 1. Полностью закройте opencode Desktop. 2. Удалите каталог кэша: * **macOS**: Finder -> `Cmd+Shift+G` -> вставить `~/.cache/opencode`. * **Linux**: удалите `~/.cache/opencode` (или запустите `rm -rf ~/.cache/opencode`). * **Windows**: нажмите `WIN+R` и вставьте `%USERPROFILE%\.cache\opencode`. 3. Перезапустите рабочий стол opencode. * * * ### [Исправить проблемы с подключением к серверу](https://opencode.ai/docs/ru/troubleshooting#%D0%B8%D1%81%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D1%82%D1%8C-%D0%BF%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D1%8B-%D1%81-%D0%BF%D0%BE%D0%B4%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%D0%BC-%D0%BA-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D1%83) opencode Desktop может либо запустить собственный локальный сервер (по умолчанию), либо подключиться к настроенному вами URL-адресу сервера. Если вы видите диалоговое окно **Ошибка подключения** (или приложение никогда не выходит за пределы заставки), проверьте URL-адрес пользовательского сервера. #### [Очистите URL-адрес сервера по умолчанию для рабочего стола.](https://opencode.ai/docs/ru/troubleshooting#%D0%BE%D1%87%D0%B8%D1%81%D1%82%D0%B8%D1%82%D0%B5-url-%D0%B0%D0%B4%D1%80%D0%B5%D1%81-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D0%B0-%D0%BF%D0%BE-%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E-%D0%B4%D0%BB%D1%8F-%D1%80%D0%B0%D0%B1%D0%BE%D1%87%D0%B5%D0%B3%D0%BE-%D1%81%D1%82%D0%BE%D0%BB%D0%B0) На главном экране щелкните имя сервера (с точкой состояния), чтобы открыть окно выбора сервера. В разделе **Сервер по умолчанию** нажмите **Очистить**. #### [Удалите `server.port`/`server.hostname` из вашей конфигурации.](https://opencode.ai/docs/ru/troubleshooting#%D1%83%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D0%B5-serverportserverhostname-%D0%B8%D0%B7-%D0%B2%D0%B0%D1%88%D0%B5%D0%B9-%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B3%D1%83%D1%80%D0%B0%D1%86%D0%B8%D0%B8) Если ваш `opencode.json(c)` содержит раздел `server`, временно удалите его и перезапустите настольное приложение. #### [Проверьте переменные среды](https://opencode.ai/docs/ru/troubleshooting#%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D1%8C%D1%82%D0%B5-%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5-%D1%81%D1%80%D0%B5%D0%B4%D1%8B) Если в вашей среде установлен `OPENCODE_PORT`, настольное приложение попытается использовать этот порт для локального сервера. * Отмените настройку `OPENCODE_PORT` (или выберите свободный порт) и перезапустите. * * * ### [Linux: проблемы с Wayland/X11](https://opencode.ai/docs/ru/troubleshooting#linux-%D0%BF%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D1%8B-%D1%81-waylandx11) В Linux некоторые настройки Wayland могут вызывать пустые окна или ошибки компоновщика. * Если вы используете Wayland, а приложение не работает или вылетает, попробуйте запустить с помощью `OC_ALLOW_WAYLAND=1`. * Если это усугубляет ситуацию, удалите его и попробуйте вместо этого запустить сеанс X11. * * * ### [Windows: среда выполнения WebView2.](https://opencode.ai/docs/ru/troubleshooting#windows-%D1%81%D1%80%D0%B5%D0%B4%D0%B0-%D0%B2%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B5%D0%BD%D0%B8%D1%8F-webview2) В Windows для opencode Desktop требуется Microsoft Edge **WebView2 Runtime**. Если приложение открывается в пустом окне или не запускается, установите/обновите WebView2 и повторите попытку. * * * ### [Windows: общие проблемы с производительностью](https://opencode.ai/docs/ru/troubleshooting#windows-%D0%BE%D0%B1%D1%89%D0%B8%D0%B5-%D0%BF%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D1%8B-%D1%81-%D0%BF%D1%80%D0%BE%D0%B8%D0%B7%D0%B2%D0%BE%D0%B4%D0%B8%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C%D1%8E) Если вы испытываете низкую производительность, проблемы с доступом к файлам или проблемы с terminal в Windows, попробуйте использовать [WSL (подсистема Windows для Linux)](https://opencode.ai/docs/windows-wsl) . WSL предоставляет среду Linux, которая более эффективно работает с функциями opencode. * * * ### [Уведомления не отображаются](https://opencode.ai/docs/ru/troubleshooting#%D1%83%D0%B2%D0%B5%D0%B4%D0%BE%D0%BC%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F-%D0%BD%D0%B5-%D0%BE%D1%82%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B0%D1%8E%D1%82%D1%81%D1%8F) opencode Desktop отображает системные уведомления только в следующих случаях: * уведомления для opencode включены в настройках вашей ОС, и * окно приложения не в фокусе. * * * ### [Сбросить хранилище настольных приложений (последнее средство)](https://opencode.ai/docs/ru/troubleshooting#%D1%81%D0%B1%D1%80%D0%BE%D1%81%D0%B8%D1%82%D1%8C-%D1%85%D1%80%D0%B0%D0%BD%D0%B8%D0%BB%D0%B8%D1%89%D0%B5-%D0%BD%D0%B0%D1%81%D1%82%D0%BE%D0%BB%D1%8C%D0%BD%D1%8B%D1%85-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BD%D0%B5%D0%B5-%D1%81%D1%80%D0%B5%D0%B4%D1%81%D1%82%D0%B2%D0%BE) Если приложение не запускается и вы не можете очистить настройки из пользовательского интерфейса, сбросьте сохраненное состояние настольного приложения. 1. Закройте рабочий стол opencode. 2. Найдите и удалите эти файлы (они находятся в каталоге данных приложения opencode Desktop): * `opencode.settings.dat` (URL-адрес сервера по умолчанию для рабочего стола) * `opencode.global.dat` и `opencode.workspace.*.dat` (состояние пользовательского интерфейса, например, недавние серверы/проекты) Чтобы быстро найти каталог: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (затем найдите имена файлов, указанные выше) * **Linux**: найдите в `~/.local/share` имена файлов, указанные выше. * **Windows**: нажмите `WIN+R` -> `%APPDATA%` (затем найдите имена файлов, указанные выше). * * * [Получение помощи](https://opencode.ai/docs/ru/troubleshooting#%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BF%D0%BE%D0%BC%D0%BE%D1%89%D0%B8) ------------------------------------------------------------------------------------------------------------------------------------------------------------ Если у вас возникли проблемы с opencode: 1. **Сообщайте о проблемах на GitHub** Лучший способ сообщить об ошибках или запросить новые функции — через наш репозиторий GitHub: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Прежде чем создавать новую проблему, выполните поиск по существующим проблемам, чтобы узнать, не сообщалось ли уже о вашей проблеме. 2. **Присоединяйтесь к нашему Discord** Для получения помощи в режиме реального времени и обсуждения в сообществе присоединяйтесь к нашему серверу Discord: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Общие проблемы](https://opencode.ai/docs/ru/troubleshooting#%D0%BE%D0%B1%D1%89%D0%B8%D0%B5-%D0%BF%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D1%8B) ---------------------------------------------------------------------------------------------------------------------------------------------- Вот некоторые распространенные проблемы и способы их решения. * * * ### [opencode не запускается](https://opencode.ai/docs/ru/troubleshooting#opencode-%D0%BD%D0%B5-%D0%B7%D0%B0%D0%BF%D1%83%D1%81%D0%BA%D0%B0%D0%B5%D1%82%D1%81%D1%8F) 1. Проверьте журналы на наличие сообщений об ошибках 2. Попробуйте запустить `--print-logs`, чтобы увидеть вывод в terminal. 3. Убедитесь, что у вас установлена ​​последняя версия `opencode upgrade`. * * * ### [Проблемы аутентификации](https://opencode.ai/docs/ru/troubleshooting#%D0%BF%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D1%8B-%D0%B0%D1%83%D1%82%D0%B5%D0%BD%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D0%B8) 1. Попробуйте выполнить повторную аутентификацию с помощью команды `/connect` в TUI. 2. Убедитесь, что ваши ключи API действительны 3. Убедитесь, что ваша сеть разрешает подключения к API провайдера. * * * ### [Модель недоступна](https://opencode.ai/docs/ru/troubleshooting#%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D1%8C-%D0%BD%D0%B5%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%D0%BD%D0%B0) 1. Убедитесь, что вы прошли аутентификацию у провайдера 2. Проверьте правильность названия модели в вашей конфигурации. 3. Для некоторых моделей может потребоваться специальный доступ или подписка. Если вы столкнулись с `ProviderModelNotFoundError`, вы, скорее всего, ошибаетесь. ссылка на модель где-то. На модели следует ссылаться следующим образом: `/`. Примеры: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` Чтобы выяснить, к каким моделям у вас есть доступ, запустите `opencode models`. * * * ### [ProviderInitError](https://opencode.ai/docs/ru/troubleshooting#provideriniterror) Если вы столкнулись с ошибкой ProviderInitError, скорее всего, у вас неверная или поврежденная конфигурация. Чтобы решить эту проблему: 1. Сначала убедитесь, что ваш провайдер настроен правильно, следуя [руководству провайдеров](https://opencode.ai/docs/providers) 2. Если проблема не устранена, попробуйте очистить сохраненную конфигурацию: rm -rf ~/.local/share/opencode В Windows нажмите `WIN+R` и удалите: `%USERPROFILE%\.local\share\opencode`. 3. Повторно выполните аутентификацию у своего провайдера, используя команду `/connect` в TUI. * * * ### [AI\_APICallError и проблемы с пакетом провайдера](https://opencode.ai/docs/ru/troubleshooting#ai_apicallerror-%D0%B8-%D0%BF%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D1%8B-%D1%81-%D0%BF%D0%B0%D0%BA%D0%B5%D1%82%D0%BE%D0%BC-%D0%BF%D1%80%D0%BE%D0%B2%D0%B0%D0%B9%D0%B4%D0%B5%D1%80%D0%B0) Если вы столкнулись с ошибками вызова API, это может быть связано с устаревшими пакетами провайдера. opencode динамически устанавливает пакеты провайдеров (OpenAI, Anthropic, Google и т. д.) по мере необходимости и кэширует их локально. Чтобы решить проблемы с пакетом поставщика: 1. Очистите кеш пакетов провайдера: rm -rf ~/.cache/opencode В Windows нажмите `WIN+R` и удалите: `%USERPROFILE%\.cache\opencode`. 2. Перезапустите opencode, чтобы переустановить последние пакеты поставщиков. Это заставит opencode загружать самые последние версии пакетов провайдеров, что часто решает проблемы совместимости с параметрами модели и изменениями API. * * * ### [Копирование/вставка не работает в Linux](https://opencode.ai/docs/ru/troubleshooting#%D0%BA%D0%BE%D0%BF%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5%D0%B2%D1%81%D1%82%D0%B0%D0%B2%D0%BA%D0%B0-%D0%BD%D0%B5-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82-%D0%B2-linux) Для работы функций копирования/вставки пользователям Linux необходимо установить одну из следующих утилит буфера обмена: **Для систем X11:** apt install -y xclip# orapt install -y xsel **Для систем Wayland:** apt install -y wl-clipboard **Для headless-сред:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode определит, используете ли вы Wayland и предпочитаете `wl-clipboard`, в противном случае он попытается найти инструменты буфера обмена в порядке: `xclip` и `xsel`. --- # 도구 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/tools#_top) 도구 == LLM이 사용할 수 있는 도구를 관리합니다. 도구는 LLM을 사용하여 코드베이스에서 작업을 수행 할 수 있습니다. opencode는 내장 도구 세트로 제공되지만, [custom tools](https://opencode.ai/docs/custom-tools) 또는 [MCP 서버](https://opencode.ai/docs/mcp-servers) 로 확장할 수 있습니다. 기본적으로 모든 도구는**enabled**이며, 실행할 권한이 없습니다. [permissions](https://opencode.ai/docs/permissions) 를 통해 공구 동작을 제어할 수 있습니다. * * * [구성](https://opencode.ai/docs/ko/tools#%EA%B5%AC%EC%84%B1) ----------------------------------------------------------- `permission` 필드를 사용하여 도구 동작을 제어합니다. 각 도구에 대한 승인이 필요할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} 한 번에 여러 도구를 제어 할 와일드 카드를 사용할 수 있습니다. 예를 들어, MCP 서버의 모든 도구에 대한 승인을 요구합니다. { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Learn more](https://opencode.ai/docs/permissions) configuring 권한에 대해. * * * [내장](https://opencode.ai/docs/ko/tools#%EB%82%B4%EC%9E%A5) ----------------------------------------------------------- 다음은 opencode에서 사용할 수있는 모든 내장 도구입니다. * * * ###### [bash](https://opencode.ai/docs/ko/tools#bash) 프로젝트 환경에서 shell 명령을 실행합니다. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} 이 도구는 `npm install`, `git status` 또는 다른 shell 명령과 같은 terminal 명령을 실행하는 LLM을 허용합니다. * * * ### [edit](https://opencode.ai/docs/ko/tools#edit) 정확한 문자열 교체를 사용하여 기존 파일을 수정합니다. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 이 도구는 정확한 텍스트 일치를 대체하여 파일에 정확한 편집을 수행합니다. LLM은 코드를 modify하는 주요 방법입니다. * * * ### [write](https://opencode.ai/docs/ko/tools#write) 새로운 파일을 만들거나 기존의 것을 덮어쓰기. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} LLM을 사용하여 새 파일을 만듭니다. 이미 존재하는 경우 기존 파일을 덮어쓰겠습니다. * * * ### [read](https://opencode.ai/docs/ko/tools#read) codebase에서 파일 내용을 읽으십시오. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} 이 도구는 파일을 읽고 내용을 반환합니다. 큰 파일에 대한 특정 라인 범위를 읽을 수 있습니다. * * * #### [grep](https://opencode.ai/docs/ko/tools#grep) 정규 표현식을 사용하여 파일 내용을 검색합니다. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Codebase에서 빠른 콘텐츠 검색. 전체 regex 문법 및 파일 패턴 필터링 지원. * * * #### [glob](https://opencode.ai/docs/ko/tools#glob) 패턴 매칭으로 파일 찾기. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} `**/*.js` 또는 `src/**/*.ts`와 같은 glob 패턴을 사용하여 파일 검색. 수정 시간에 의해 정렬 된 파일 경로 반환. * * * ### [list](https://opencode.ai/docs/ko/tools#list) 주어진 경로의 파일 및 디렉토리 목록. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} 이 도구는 디렉토리 내용을 나열합니다. 그것은 glob 패턴을 필터 결과에 받아들입니다. * * * ### [lsp (실험적)](https://opencode.ai/docs/ko/tools#lsp-%EC%8B%A4%ED%97%98%EC%A0%81) 정의, 참고, hover info 및 호출 hierarchy와 같은 코드 인텔리전스 기능을 얻기 위해 구성 된 LSP 서버와 인터랙트. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} 지원된 가동은 `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` 및 `outgoingCalls`를 포함합니다. LSP 서버가 프로젝트에 사용할 수 있는 구성하려면 [LSP Servers](https://opencode.ai/docs/lsp) 를 참조하십시오. * * * [patch](https://opencode.ai/docs/ko/tools#patch) ------------------------------------------------- 파일에 패치를 적용합니다. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 이 도구는 코드베이스에 패치 파일을 적용합니다. 다양한 소스에서 diffs 및 Patch를 적용하는 데 유용합니다. * * * ### [skill](https://opencode.ai/docs/ko/tools#skill) [skill](https://opencode.ai/docs/skills) (`SKILL.md` 파일)을로드하고 대화의 내용을 반환합니다. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * [todowrite](https://opencode.ai/docs/ko/tools#todowrite) --------------------------------------------------------- 코딩 세션 중에 todo 목록을 관리합니다. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} 복잡한 작업 중에 진행 상황을 추적하기 위해 작업 목록을 만들고 업데이트합니다. LLM은 멀티 단계 작업을 구성하기 위해 이것을 사용합니다. * * * #### [todoread](https://opencode.ai/docs/ko/tools#todoread) 기존의 todo 목록 읽기. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} 현재 todo 목록 상태를 읽습니다. 작업이 종료되거나 완료되는 것을 추적하기 위해 LLM에 의해 사용됩니다. * * * #### [webfetch](https://opencode.ai/docs/ko/tools#webfetch) Fetch 웹 콘텐츠. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} LLM을 fetch 및 웹 페이지를 읽을 수 있습니다. 온라인 리소스를 찾는 데 도움이 되는 문서 또는 연구 * * * #### [websearch](https://opencode.ai/docs/ko/tools#websearch) 웹 검색 { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Exa AI를 사용하여 웹 검색을 수행하여 관련 정보를 온라인으로 찾으십시오. 연구 주제에 유용한, 현재 이벤트를 찾는, 또는 훈련 데이터 차단을 넘어 정보를 수집. API 키가 필요하지 않습니다 - 도구는 인증없이 Exa AI의 호스팅 MCP 서비스에 직접 연결됩니다. * * * ### [question](https://opencode.ai/docs/ko/tools#question) 실행 중에 사용자의 질문 요청. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} 이 도구는 작업 중에 LLM을 요청할 수 있습니다. 그것은 유용합니다: * 사용자 선호도 또는 요구 사항 변경 * 주위 지침 * 구현 선택에 대한 결정 * 어떤 방향에 대한 선택 제공 각 질문에는 헤더, 질문 텍스트 및 옵션 목록이 포함되어 있습니다. 사용자는 제공된 선택권에서 선택하거나 주문 대답을 타자를 수 있습니다. 여러 질문이 있을 때, 사용자는 모든 답변을 제출하기 전에 그들 사이에서 탐색 할 수 있습니다. * * * [사용자 정의 도구](https://opencode.ai/docs/ko/tools#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98-%EB%8F%84%EA%B5%AC) ----------------------------------------------------------------------------------------------------------------- 사용자 정의 도구는 LLM이 호출 할 수있는 자신의 기능을 정의 할 수 있습니다. config 파일에 정의되어 arbitrary 코드를 실행할 수 있습니다. [Learn more](https://opencode.ai/docs/custom-tools) 사용자 정의 도구 만들기. * * * [MCP 서버](https://opencode.ai/docs/ko/tools#mcp-%EC%84%9C%EB%B2%84) ------------------------------------------------------------------- MCP(Model Context Protocol) 서버는 외부 도구와 서비스를 통합할 수 있습니다. 이 데이터베이스 액세스, API 통합 및 타사 서비스가 포함되어 있습니다. MCP 서버 구성에 대한 [Learn more](https://opencode.ai/docs/mcp-servers) . * * * [내부](https://opencode.ai/docs/ko/tools#%EB%82%B4%EB%B6%80) ----------------------------------------------------------- 내부, 도구 `grep`, `glob`, 그리고 `list` 사용 [ripgrep](https://github.com/BurntSushi/ripgrep) 후드 아래에. 기본적으로 ripgrep은 `.gitignore` 패턴을 존중하며 `.gitignore`에 나열된 파일 및 디렉토리를 검색 및 목록에서 제외됩니다. * * * #### [Ignore 패턴](https://opencode.ai/docs/ko/tools#ignore-%ED%8C%A8%ED%84%B4) 일반적으로 무시되는 파일을 포함하려면 프로젝트 루트에 `.ignore` 파일을 만듭니다. 이 파일은 명시적으로 특정 경로를 허용 할 수 있습니다. !node_modules/!dist/!build/ 예를 들어,이 `.ignore` 파일은 `node_modules/`, `dist/` 및 `build/` 디렉토리 내에서 검색 할 수 있습니다. `.gitignore`. --- # Araçlar | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/tools#_top) Araçlar ======= LLM'in kullanabileceği araçları yönetin. Araçlar, LLM’in kod tabanınızda eylem gerçekleştirmesini sağlar. opencode yerleşik bir araç setiyle gelir, ancak bunu [özel araçlarla](https://opencode.ai/docs/custom-tools) veya [MCP sunucularıyla](https://opencode.ai/docs/mcp-servers) genişletebilirsiniz. Varsayılan olarak tüm araçlar **etkindir** ve çalışmak için izin istemez. Araç davranışını [izinler](https://opencode.ai/docs/permissions) üzerinden kontrol edebilirsiniz. * * * [Yapılandırma](https://opencode.ai/docs/tr/tools#yap%C4%B1land%C4%B1rma) ------------------------------------------------------------------------- Araç davranışını kontrol etmek için `permission` alanını kullanın. Her araç için izin verebilir, reddedebilir veya onay isteyebilirsiniz. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Birden fazla aracı aynı anda kontrol etmek için joker karakterler de kullanabilirsiniz. Örneğin, bir MCP sunucusundan gelen tüm araçlar için onay istemek: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} İzin yapılandırması için [daha fazla bilgi alın](https://opencode.ai/docs/permissions) . * * * [Yerleşik](https://opencode.ai/docs/tr/tools#yerle%C5%9Fik) ------------------------------------------------------------ opencode içinde bulunan tüm yerleşik araçlar aşağıdadır. * * * ### [bash](https://opencode.ai/docs/tr/tools#bash) Proje ortamınızda kabuk komutları çalıştırır. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Bu araç LLM’in `npm install`, `git status` gibi terminal komutlarını veya diğer kabuk komutlarını çalıştırmasını sağlar. * * * ### [edit](https://opencode.ai/docs/tr/tools#edit) Birebir metin değiştirme ile mevcut dosyaları düzenler. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Bu araç dosyalarda kesin metin eşleşmelerini değiştirerek hassas düzenleme yapar. LLM’in kodu değiştirmek için kullandığı temel yöntemdir. * * * ### [write](https://opencode.ai/docs/tr/tools#write) Yeni dosyalar oluşturur veya mevcut dosyaları üzerine yazar. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} LLM’in yeni dosya oluşturmasına izin vermek için bunu kullanın. Dosya zaten varsa üzerine yazar. * * * ### [read](https://opencode.ai/docs/tr/tools#read) Kod tabanınızdan dosya içeriği okur. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Bu araç dosyaları okur ve içeriklerini döndürür. Büyük dosyalar için belirli satır aralıklarını okuma desteği vardır. * * * ### [grep](https://opencode.ai/docs/tr/tools#grep) Düzenli ifadelerle dosya içeriğinde arama yapar. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Kod tabanında hızlı içerik araması sunar. Tam regex sözdizimini ve dosya desen filtrelerini destekler. * * * ### [glob](https://opencode.ai/docs/tr/tools#glob) Desen eşleştirme ile dosya bulur. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} `**/*.js` veya `src/**/*.ts` gibi glob desenleriyle dosya arar. Eşleşen dosya yollarını değişim zamanına göre sıralar. * * * ### [list](https://opencode.ai/docs/tr/tools#list) Verilen yoldaki dosya ve dizinleri listeler. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Bu araç dizin içeriğini listeler. Sonuçları filtrelemek için glob desenlerini kabul eder. * * * ### [lsp (deneysel)](https://opencode.ai/docs/tr/tools#lsp-deneysel) Tanım, referans, hover bilgisi ve çağrılar hiyerarşisi gibi kod zekası özellikleri için yapılandırdığınız LSP sunucularıyla etkileşir. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Desteklenen işlemler: `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls`, `outgoingCalls`. Projeniz için kullanılabilir LSP sunucularını ayarlamak için [LSP Sunucuları](https://opencode.ai/docs/lsp) sayfasına bakın. * * * ### [patch](https://opencode.ai/docs/tr/tools#patch) Dosyalara patch uygular. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Bu araç patch dosyalarını kod tabanınıza uygular. Farklı kaynaklardan gelen diff ve patch’leri uygulamak için kullanışlıdır. * * * ### [skill](https://opencode.ai/docs/tr/tools#skill) Bir [skill](https://opencode.ai/docs/skills) (`SKILL.md` dosyası) yükler ve içeriğini konuşmaya döndürür. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/tr/tools#todowrite) Kodlama oturumlarında yapılacaklar listesini yönetir. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Karmaşık işlemlerde ilerlemeyi takip etmek için görev listeleri oluşturur ve günceller. LLM bunu çok adımlı görevleri düzenlemek için kullanır. * * * ### [todoread](https://opencode.ai/docs/tr/tools#todoread) Mevcut yapılacaklar listesini okur. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Güncel todo listesi durumunu okur. LLM bunu hangi görevlerin beklediğini veya tamamlandığını takip etmek için kullanır. * * * ### [webfetch](https://opencode.ai/docs/tr/tools#webfetch) Web içeriği getirir. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} LLM’in web sayfalarını getirip okumasını sağlar. Dokümantasyon aramak veya çevrimiçi kaynakları incelemek için kullanışlıdır. * * * ### [websearch](https://opencode.ai/docs/tr/tools#websearch) Web’de bilgi arar. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Exa AI ile web araması yaparak ilgili bilgileri bulur. Eğitim verisi kesim tarihinin ötesindeki konuları araştırmak, güncel olayları bulmak veya genel araştırma yapmak için kullanışlıdır. API anahtarı gerekmez - araç Exa AI’nin barındırılan MCP hizmetine doğrudan kimlik doğrulaması olmadan bağlanır. * * * ### [question](https://opencode.ai/docs/tr/tools#question) Çalışma sırasında kullanıcıya soru sorar. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Bu araç LLM’in görev sırasında kullanıcıya soru sormasını sağlar. Şunlar için kullanışlıdır: * Kullanıcı tercihleri veya gereksinimleri toplamak * Belirsiz talimatları netleştirmek * Uygulama seçeneklerinde karar almak * Hangi yöne gidileceğine dair seçenek sunmak Her soru bir başlık, soru metni ve seçenek listesi içerir. Kullanıcılar seçeneklerden birini seçebilir veya özel yanıt yazabilir. Birden fazla soru varsa tüm yanıtları göndermeden önce sorular arasında gezebilirler. * * * [Özel araçlar](https://opencode.ai/docs/tr/tools#%C3%B6zel-ara%C3%A7lar) ------------------------------------------------------------------------- Özel araçlar, LLM’in çağırabileceği kendi fonksiyonlarınızı tanımlamanızı sağlar. Bunlar config dosyanızda tanımlanır ve keyfi kod çalıştırabilir. Özel araç oluşturma için [daha fazla bilgi alın](https://opencode.ai/docs/custom-tools) . * * * [MCP sunucuları](https://opencode.ai/docs/tr/tools#mcp-sunucular%C4%B1) ------------------------------------------------------------------------ MCP (Model Context Protocol) sunucuları, harici araçları ve servisleri entegre etmenizi sağlar. Buna veritabanı erişimi, API entegrasyonları ve üçüncü taraf servisler dahildir. MCP sunucularını yapılandırma için [daha fazla bilgi alın](https://opencode.ai/docs/mcp-servers) . * * * [Dahili detaylar](https://opencode.ai/docs/tr/tools#dahili-detaylar) --------------------------------------------------------------------- Dahilde `grep`, `glob` ve `list` gibi araçlar [ripgrep](https://github.com/BurntSushi/ripgrep) kullanır. Varsayılan olarak ripgrep `.gitignore` desenlerine uyar; yani `.gitignore` içindeki dosya ve dizinler arama ve listeleme sonucuna dahil edilmez. * * * ### [Yoksayma desenleri](https://opencode.ai/docs/tr/tools#yoksayma-desenleri) Normalde yok sayılan dosyaları dahil etmek için proje kökünde bir `.ignore` dosyası oluşturun. Bu dosya belirli yolları açıkça izinli yapabilir. !node_modules/!dist/!build/ Örneğin bu `.ignore` dosyası, `node_modules/` içinde olsalar bile ripgrep’in `dist/`, `build/` ve `.gitignore` dizinlerinde arama yapmasına izin verir. --- # Outils | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/tools#_top) Outils ====== Gérez les outils qu'un LLM peut utiliser. Les outils permettent au LLM d’effectuer des actions dans votre base de code. OpenCode est livré avec un ensemble d’outils intégrés, mais vous pouvez l’étendre avec [outils personnalisés](https://opencode.ai/docs/custom-tools) ou [serveurs MCP](https://opencode.ai/docs/mcp-servers) . Par défaut, tous les outils sont **activés** et n’ont pas besoin d’autorisation pour s’exécuter. Vous pouvez contrôler le comportement de l’outil via [permissions](https://opencode.ai/docs/permissions) . * * * [Configurer](https://opencode.ai/docs/fr/tools#configurer) ----------------------------------------------------------- Utilisez le champ `permission` pour contrôler le comportement de l’outil. Vous pouvez autoriser, refuser ou exiger une approbation pour chaque outil. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Vous pouvez également utiliser des caractères génériques pour contrôler plusieurs outils à la fois. Par exemple, pour exiger l’approbation de tous les outils d’un serveur MCP : { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [En savoir plus](https://opencode.ai/docs/permissions) sur la configuration des autorisations. * * * [Intégré](https://opencode.ai/docs/fr/tools#int%C3%A9gr%C3%A9) --------------------------------------------------------------- Voici tous les outils intégrés disponibles dans OpenCode. * * * ### [frapper](https://opencode.ai/docs/fr/tools#frapper) Exécutez des commandes shell dans votre environnement de projet. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Cet outil permet au LLM d’exécuter des commandes de terminal telles que `npm install`, `git status` ou toute autre commande shell. * * * ### [modifier](https://opencode.ai/docs/fr/tools#modifier) Modifiez les fichiers existants en utilisant des remplacements de chaînes exacts. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Cet outil effectue des modifications précises des fichiers en remplaçant les correspondances de texte exactes. C’est la principale façon dont LLM modifie le code. * * * ### [écrire](https://opencode.ai/docs/fr/tools#%C3%A9crire) Créez de nouveaux fichiers ou écrasez ceux existants. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Utilisez-le pour permettre au LLM de créer de nouveaux fichiers. Il écrasera les fichiers existants s’ils existent déjà. * * * ### [lire](https://opencode.ai/docs/fr/tools#lire) Lisez le contenu du fichier à partir de votre base de code. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Cet outil lit les fichiers et renvoie leur contenu. Il prend en charge la lecture de plages de lignes spécifiques pour les fichiers volumineux. * * * ### [grep](https://opencode.ai/docs/fr/tools#grep) Recherchez le contenu du fichier à l’aide d’expressions régulières. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Recherche rapide de contenu dans votre base de code. Prend en charge la syntaxe regex complète et le filtrage des modèles de fichiers. * * * ### [globe](https://opencode.ai/docs/fr/tools#globe) Recherchez des fichiers par correspondance de modèles. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Recherchez des fichiers à l’aide de modèles globaux tels que `**/*.js` ou `src/**/*.ts`. Renvoie les chemins de fichiers correspondants triés par heure de modification. * * * ### [liste](https://opencode.ai/docs/fr/tools#liste) Répertoriez les fichiers et les répertoires dans un chemin donné. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Cet outil répertorie le contenu du répertoire. Il accepte les modèles globaux pour filtrer les résultats. * * * ### [lsp (expérimental)](https://opencode.ai/docs/fr/tools#lsp-exp%C3%A9rimental) Interagissez avec vos serveurs LSP configurés pour obtenir des fonctionnalités d’intelligence du code telles que des définitions, des références, des informations de survol et une hiérarchie d’appels. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Les opérations prises en charge incluent `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` et `outgoingCalls`. Pour configurer les serveurs LSP disponibles pour votre projet, consultez [LSP Servers](https://opencode.ai/docs/lsp) . * * * ### [correctif](https://opencode.ai/docs/fr/tools#correctif) Appliquez des correctifs aux fichiers. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Cet outil applique les fichiers de correctifs à votre base de code. Utile pour appliquer des différences et des correctifs provenant de diverses sources. * * * ### [compétence](https://opencode.ai/docs/fr/tools#comp%C3%A9tence) Chargez une [skill](https://opencode.ai/docs/skills) (un fichier `SKILL.md`) et renvoyez son contenu dans la conversation. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [à écrire](https://opencode.ai/docs/fr/tools#%C3%A0-%C3%A9crire) Gérez les listes de tâches pendant les sessions de codage. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Crée et met à jour des listes de tâches pour suivre la progression lors d’opérations complexes. Le LLM l’utilise pour organiser des tâches en plusieurs étapes. * * * ### [todore](https://opencode.ai/docs/fr/tools#todore) Lisez les listes de tâches existantes. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Lit l’état actuel de la liste de tâches. Utilisé par le LLM pour suivre les tâches en attente ou terminées. * * * ### [récupération sur le Web](https://opencode.ai/docs/fr/tools#r%C3%A9cup%C3%A9ration-sur-le-web) Récupérer du contenu Web. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Permet au LLM de récupérer et de lire des pages Web. Utile pour rechercher de la documentation ou rechercher des ressources en ligne. * * * ### [recherche sur le Web](https://opencode.ai/docs/fr/tools#recherche-sur-le-web) Recherchez des informations sur le Web. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Effectue des recherches sur le Web à l’aide d’Exa AI pour trouver des informations pertinentes en ligne. Utile pour rechercher des sujets, trouver des événements actuels ou collecter des informations au-delà de la limite des données de formation. Aucune clé API n’est requise : l’outil se connecte directement au service MCP hébergé d’Exa AI sans authentification. * * * ### [question](https://opencode.ai/docs/fr/tools#question) Posez des questions à l’utilisateur pendant l’exécution. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Cet outil permet au LLM de poser des questions à l’utilisateur lors d’une tâche. C’est utile pour : * Recueillir les préférences ou les exigences des utilisateurs * Clarifier les instructions ambiguës * Obtenir des décisions sur les choix de mise en œuvre * Offrir des choix sur la direction à prendre Chaque question comprend un en-tête, le texte de la question et une liste d’options. Les utilisateurs peuvent choisir parmi les options proposées ou saisir une réponse personnalisée. Lorsqu’il y a plusieurs questions, les utilisateurs peuvent naviguer entre elles avant de soumettre toutes les réponses. * * * [Outils personnalisés](https://opencode.ai/docs/fr/tools#outils-personnalis%C3%A9s) ------------------------------------------------------------------------------------ Les outils personnalisés vous permettent de définir vos propres fonctions que le LLM peut appeler. Ceux-ci sont définis dans votre fichier de configuration et peuvent exécuter du code arbitraire. [En savoir plus](https://opencode.ai/docs/custom-tools) sur la création d’outils personnalisés. * * * [Serveurs MCP](https://opencode.ai/docs/fr/tools#serveurs-mcp) --------------------------------------------------------------- Les serveurs MCP (Model Context Protocol) vous permettent d’intégrer des outils et services externes. Cela inclut l’accès à la base de données, les intégrations API et les services tiers. [En savoir plus](https://opencode.ai/docs/mcp-servers) sur la configuration des serveurs MCP. * * * [Internes](https://opencode.ai/docs/fr/tools#internes) ------------------------------------------------------- En interne, des outils comme `grep`, `glob` et `list` utilisent [ripgrep](https://github.com/BurntSushi/ripgrep) sous le capot. Par défaut, ripgrep respecte les modèles `.gitignore`, ce qui signifie que les fichiers et répertoires répertoriés dans votre `.gitignore` seront exclus des recherches et des listes. * * * ### [Ignorer les modèles](https://opencode.ai/docs/fr/tools#ignorer-les-mod%C3%A8les) Pour inclure des fichiers qui seraient normalement ignorés, créez un fichier `.ignore` à la racine de votre projet. Ce fichier peut autoriser explicitement certains chemins. !node_modules/!dist/!build/ Par exemple, ce fichier `.ignore` permet à ripgrep de rechercher dans les répertoires `node_modules/`, `dist/` et `build/` même s’ils sont répertoriés dans `.gitignore`. --- # Strumenti | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/tools#_top) Strumenti ========= Gestisci gli strumenti che un LLM puo' usare. Gli strumenti permettono all’LLM di eseguire azioni nel tuo codebase. OpenCode include un set di strumenti integrati, ma puoi estenderlo con [strumenti personalizzati](https://opencode.ai/docs/custom-tools) o con [server MCP](https://opencode.ai/docs/mcp-servers) . Di default, tutti gli strumenti sono **abilitati** e non richiedono permessi per essere eseguiti. Puoi controllare il comportamento degli strumenti tramite i [permessi](https://opencode.ai/docs/permissions) . * * * [Configurazione](https://opencode.ai/docs/it/tools#configurazione) ------------------------------------------------------------------- Usa il campo `permission` per controllare il comportamento degli strumenti. Puoi consentire, negare o richiedere approvazione per ciascuno. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Puoi anche usare wildcard per controllare piu’ strumenti insieme. Per esempio, per richiedere approvazione per tutti gli strumenti di un server MCP: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Scopri di piu’](https://opencode.ai/docs/permissions) su come configurare i permessi. * * * [Integrati](https://opencode.ai/docs/it/tools#integrati) --------------------------------------------------------- Ecco tutti gli strumenti integrati disponibili in OpenCode. * * * ### [bash](https://opencode.ai/docs/it/tools#bash) Esegui comandi di shell nel tuo ambiente di progetto. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Questo strumento permette all’LLM di eseguire comandi da terminale come `npm install`, `git status` o qualunque altro comando di shell. * * * ### [edit](https://opencode.ai/docs/it/tools#edit) Modifica file esistenti usando sostituzioni esatte di stringhe. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Questo strumento esegue modifiche precise ai file sostituendo corrispondenze di testo esatte. E’ il modo principale con cui l’LLM modifica il codice. * * * ### [write](https://opencode.ai/docs/it/tools#write) Crea nuovi file o sovrascrive quelli esistenti. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Usalo per consentire all’LLM di creare nuovi file. Sovrascrivera’ i file esistenti se sono gia’ presenti. * * * ### [read](https://opencode.ai/docs/it/tools#read) Leggi il contenuto dei file dal tuo codebase. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Questo strumento legge i file e ne restituisce il contenuto. Supporta la lettura di intervalli di righe specifici per file grandi. * * * ### [grep](https://opencode.ai/docs/it/tools#grep) Cerca nel contenuto dei file usando espressioni regolari. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Ricerca rapida nel contenuto su tutto il codebase. Supporta la sintassi completa delle regex e il filtro per pattern di file. * * * ### [glob](https://opencode.ai/docs/it/tools#glob) Trova file tramite pattern matching. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Cerca file usando pattern glob come `**/*.js` o `src/**/*.ts`. Restituisce i percorsi corrispondenti ordinati per data di modifica. * * * ### [list](https://opencode.ai/docs/it/tools#list) Elenca file e directory in un percorso specifico. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Questo strumento elenca il contenuto di una directory. Accetta pattern glob per filtrare i risultati. * * * ### [lsp (experimental)](https://opencode.ai/docs/it/tools#lsp-experimental) Interagisci con i server LSP configurati per ottenere funzionalita’ di code intelligence come definizioni, riferimenti, hover info e call hierarchy. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Le operazioni supportate includono `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` e `outgoingCalls`. Per configurare quali server LSP sono disponibili per il tuo progetto, vedi [LSP Servers](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/it/tools#patch) Applica patch ai file. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Questo strumento applica file patch al tuo codebase. Utile per applicare diff e patch da varie fonti. * * * ### [skill](https://opencode.ai/docs/it/tools#skill) Carica una [skill](https://opencode.ai/docs/skills) (un file `SKILL.md`) e ne restituisce il contenuto nella conversazione. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/it/tools#todowrite) Gestisci todo list durante le sessioni di coding. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Crea e aggiorna liste di task per tracciare i progressi durante operazioni complesse. L’LLM lo usa per organizzare attivita’ multi-step. * * * ### [todoread](https://opencode.ai/docs/it/tools#todoread) Leggi le todo list esistenti. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Legge lo stato corrente della todo list. Usato dall’LLM per tenere traccia di quali task sono in sospeso o completati. * * * ### [webfetch](https://opencode.ai/docs/it/tools#webfetch) Recupera contenuti dal web. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Permette all’LLM di recuperare e leggere pagine web. Utile per consultare documentazione o ricercare risorse online. * * * ### [websearch](https://opencode.ai/docs/it/tools#websearch) Cerca informazioni sul web. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Esegue ricerche web usando Exa AI per trovare informazioni rilevanti online. Utile per ricercare argomenti, trovare eventi attuali o raccogliere informazioni oltre il cutoff dei dati di addestramento. Non e’ richiesta alcuna API key: lo strumento si connette direttamente al servizio MCP ospitato da Exa AI senza autenticazione. * * * ### [question](https://opencode.ai/docs/it/tools#question) Fai domande all’utente durante l’esecuzione. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Questo strumento permette all’LLM di porre domande all’utente durante un task. E’ utile per: * Raccogliere preferenze o requisiti dell’utente * Chiarire istruzioni ambigue * Ottenere decisioni sulle scelte di implementazione * Offrire opzioni su che direzione prendere Ogni domanda include un header, il testo della domanda e una lista di opzioni. Gli utenti possono selezionare dalle opzioni fornite o digitare una risposta personalizzata. Quando ci sono piu’ domande, gli utenti possono navigare tra di esse prima di inviare tutte le risposte. * * * [Strumenti personalizzati](https://opencode.ai/docs/it/tools#strumenti-personalizzati) --------------------------------------------------------------------------------------- Gli strumenti personalizzati ti permettono di definire funzioni che l’LLM puo’ chiamare. Sono definiti nel tuo file di configurazione e possono eseguire codice arbitrario. [Scopri di piu’](https://opencode.ai/docs/custom-tools) su come creare strumenti personalizzati. * * * [Server MCP](https://opencode.ai/docs/it/tools#server-mcp) ----------------------------------------------------------- I server MCP (Model Context Protocol) permettono di integrare strumenti e servizi esterni. Questo include accesso a database, integrazioni API e servizi di terze parti. [Scopri di piu’](https://opencode.ai/docs/mcp-servers) su come configurare i server MCP. * * * [Interni](https://opencode.ai/docs/it/tools#interni) ----------------------------------------------------- Internamente, strumenti come `grep`, `glob` e `list` usano [ripgrep](https://github.com/BurntSushi/ripgrep) sotto al cofano. Di default, ripgrep rispetta i pattern di `.gitignore`, quindi i file e le directory elencati in `.gitignore` vengono esclusi da ricerche ed elenchi. * * * ### [Pattern di ignore](https://opencode.ai/docs/it/tools#pattern-di-ignore) Per includere file che normalmente verrebbero ignorati, crea un file `.ignore` nella root del progetto. Questo file puo’ consentire esplicitamente certi path. !node_modules/!dist/!build/ Per esempio, questo file `.ignore` permette a ripgrep di cercare dentro `node_modules/`, `dist/` e `build/` anche se sono elencate in `.gitignore`. --- # 工具 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/tools#_top) 工具 == 管理 LLM 可以使用的工具。 工具允許 LLM 在您的程式碼庫中執行操作。OpenCode 自帶一組內建工具,您也可以透過[自訂工具](https://opencode.ai/docs/custom-tools) 或 [MCP 伺服器](https://opencode.ai/docs/mcp-servers) 來擴充它。 預設情況下,所有工具都是**啟用**的,且無需權限即可執行。您可以透過[權限](https://opencode.ai/docs/permissions) 來控制工具的行為。 * * * [設定](https://opencode.ai/docs/zh-tw/tools#%E8%A8%AD%E5%AE%9A) -------------------------------------------------------------- 使用 `permission` 欄位來控制工具行為。您可以對每個工具設定允許、拒絕或需要審批。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} 您還可以使用萬用字元同時控制多個工具。例如,要求某個 MCP 伺服器的所有工具都需要審批: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [了解更多](https://opencode.ai/docs/permissions) 關於設定權限的內容。 * * * [內建工具](https://opencode.ai/docs/zh-tw/tools#%E5%85%A7%E5%BB%BA%E5%B7%A5%E5%85%B7) ---------------------------------------------------------------------------------- 以下是 OpenCode 中所有可用的內建工具。 * * * ### [bash](https://opencode.ai/docs/zh-tw/tools#bash) 在專案環境中執行 shell 指令。 { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} 該工具允許 LLM 執行終端機指令,例如 `npm install`、`git status` 或其他任何 shell 指令。 * * * ### [edit](https://opencode.ai/docs/zh-tw/tools#edit) 透過精確的字串替換來修改現有檔案。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 該工具透過替換精確匹配的文字來對檔案進行編輯。這是 LLM 修改程式碼的主要方式。 * * * ### [write](https://opencode.ai/docs/zh-tw/tools#write) 建立新檔案或覆蓋現有檔案。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 使用此工具允許 LLM 建立新檔案。如果檔案已存在,則會覆蓋現有檔案。 * * * ### [read](https://opencode.ai/docs/zh-tw/tools#read) 讀取程式碼庫中的檔案內容。 { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} 該工具讀取檔案並回傳其內容。它支援對大檔案讀取指定行範圍。 * * * ### [grep](https://opencode.ai/docs/zh-tw/tools#grep) 使用正規表示式搜尋檔案內容。 { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} 在程式碼庫中快速搜尋內容。支援完整的正規表示式語法和檔案模式過濾。 * * * ### [glob](https://opencode.ai/docs/zh-tw/tools#glob) 透過模式匹配查找檔案。 { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} 使用 `**/*.js` 或 `src/**/*.ts` 等 glob 模式搜尋檔案。回傳按修改時間排序的匹配檔案路徑。 * * * ### [list](https://opencode.ai/docs/zh-tw/tools#list) 列出指定路徑下的檔案和目錄。 { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} 該工具用於列出目錄內容。它接受 glob 模式來過濾結果。 * * * ### [lsp(實驗性)](https://opencode.ai/docs/zh-tw/tools#lsp%E5%AF%A6%E9%A9%97%E6%80%A7) 與已設定的 LSP 伺服器互動,取得程式碼智慧功能,如定義跳轉、參考查找、懸停資訊和呼叫階層結構。 { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} 支援的操作包括 `goToDefinition`、`findReferences`、`hover`、`documentSymbol`、`workspaceSymbol`、`goToImplementation`、`prepareCallHierarchy`、`incomingCalls` 和 `outgoingCalls`。 要設定專案可用的 LSP 伺服器,請參閱 [LSP 伺服器](https://opencode.ai/docs/lsp) 。 * * * ### [patch](https://opencode.ai/docs/zh-tw/tools#patch) 對檔案套用補丁。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} 該工具將補丁檔案套用到您的程式碼庫中。適用於套用來自各種來源的 diff 和補丁。 * * * ### [skill](https://opencode.ai/docs/zh-tw/tools#skill) 載入一個[技能](https://opencode.ai/docs/skills) (即 `SKILL.md` 檔案)並在對話中回傳其內容。 { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/zh-tw/tools#todowrite) 在編碼工作階段中管理待辦事項清單。 { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} 建立和更新任務清單以追蹤複雜操作的進度。LLM 使用此工具來組織多步驟任務。 * * * ### [todoread](https://opencode.ai/docs/zh-tw/tools#todoread) 讀取現有的待辦事項清單。 { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} 讀取當前待辦事項清單的狀態。LLM 使用此工具來追蹤哪些任務待處理、哪些已完成。 * * * ### [webfetch](https://opencode.ai/docs/zh-tw/tools#webfetch) 擷取網頁內容。 { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} 允許 LLM 擷取並讀取網頁內容。適用於查閱文件或研究線上資源。 * * * ### [websearch](https://opencode.ai/docs/zh-tw/tools#websearch) 在網路上搜尋資訊。 { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} 使用 Exa AI 進行網路搜尋以查找相關資訊。適用於研究主題、了解時事動態或取得超出訓練資料截止日期的資訊。 無需 API 金鑰——該工具無需身分驗證即可直接連接到 Exa AI 的託管 MCP 服務。 * * * ### [question](https://opencode.ai/docs/zh-tw/tools#question) 在執行過程中向使用者提問。 { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} 該工具允許 LLM 在執行任務期間向使用者提問。適用於以下場景: * 收集使用者偏好或需求 * 釐清模糊的指令 * 取得實作方案的決策 * 提供方向選擇的選項 每個問題包含標題、問題正文和選項清單。使用者可以從提供的選項中選擇,也可以輸入自訂答案。當有多個問題時,使用者可以在提交所有答案之前在各問題之間切換瀏覽。 * * * [自訂工具](https://opencode.ai/docs/zh-tw/tools#%E8%87%AA%E8%A8%82%E5%B7%A5%E5%85%B7) ---------------------------------------------------------------------------------- 自訂工具允許您定義 LLM 可以呼叫的自訂函式。這些函式在您的設定檔中定義,可以執行任意程式碼。 [了解更多](https://opencode.ai/docs/custom-tools) 關於建立自訂工具的內容。 * * * [MCP 伺服器](https://opencode.ai/docs/zh-tw/tools#mcp-%E4%BC%BA%E6%9C%8D%E5%99%A8) -------------------------------------------------------------------------------- MCP(Model Context Protocol)伺服器允許您整合外部工具和服務,包括資料庫存取、API 整合和第三方服務。 [了解更多](https://opencode.ai/docs/mcp-servers) 關於設定 MCP 伺服器的內容。 * * * [內部機制](https://opencode.ai/docs/zh-tw/tools#%E5%85%A7%E9%83%A8%E6%A9%9F%E5%88%B6) ---------------------------------------------------------------------------------- 在內部,`grep`、`glob` 和 `list` 等工具底層使用 [ripgrep](https://github.com/BurntSushi/ripgrep) 。預設情況下,ripgrep 遵循 `.gitignore` 中的模式,這意味著 `.gitignore` 中列出的檔案和目錄將被排除在搜尋和列表結果之外。 * * * ### [忽略模式](https://opencode.ai/docs/zh-tw/tools#%E5%BF%BD%E7%95%A5%E6%A8%A1%E5%BC%8F) 要包含通常會被忽略的檔案,請在專案根目錄下建立一個 `.ignore` 檔案。該檔案可以明確允許某些路徑。 !node_modules/!dist/!build/ 例如,這個 `.ignore` 檔案允許 ripgrep 在 `node_modules/`、`dist/` 和 `build/` 目錄中進行搜尋,即使它們已在 `.gitignore` 中列出。 --- # ツール | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/tools#_top) ツール === LLM が使用できるツールを管理します。 ツールを使用すると、LLM がコードベースでアクションを実行できるようになります。 OpenCode には一連の組み込みツールが付属していますが、[カスタムツール](https://opencode.ai/docs/custom-tools) または [MCP サーバー](https://opencode.ai/docs/mcp-servers) を使用して拡張できます。 デフォルトでは、すべてのツールは**有効**になっており、実行するための権限は必要ありません。 [権限](https://opencode.ai/docs/permissions) . * * * [設定](https://opencode.ai/docs/ja/tools#%E8%A8%AD%E5%AE%9A) ----------------------------------------------------------- `permission` フィールドを使用してツールの動作を制御します。各ツールを許可、拒否、または承認を要求することができます。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} ワイルドカードを使用して複数のツールを一度に制御することもできます。たとえば、MCP サーバーからのすべてのツールの承認を要求するには、次のようにします。 { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [アクセス許可の構成について詳しくは、](https://opencode.ai/docs/permissions) をご覧ください。 * * * [組み込み](https://opencode.ai/docs/ja/tools#%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF) ------------------------------------------------------------------------------- OpenCode で利用可能なすべての組み込みツールを次に示します。 * * * ### [bash](https://opencode.ai/docs/ja/tools#bash) プロジェクト環境でシェルコマンドを実行します。 { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} このツールを使用すると、LLM は `npm install`、`git status`、またはその他のシェルコマンドなどのターミナルコマンドを実行できます。 * * * ### [edit](https://opencode.ai/docs/ja/tools#edit) 正確な文字列置換を使用して既存のファイルを変更します。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} このツールは、完全に一致するテキストを置き換えることにより、ファイルを正確に編集します。これは、LLM がコードを変更する主な方法です。 * * * ### [write](https://opencode.ai/docs/ja/tools#write) 新しいファイルを作成するか、既存のファイルを上書きします。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} これを使用して、LLM が新しいファイルを作成できるようにします。既存のファイルがすでに存在する場合は上書きされます。 * * * ### [read](https://opencode.ai/docs/ja/tools#read) コードベースからファイルの内容を読み取ります。 { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} このツールはファイルを読み取り、その内容を返します。大きなファイルの特定の行範囲の読み取りをサポートします。 * * * ### [grep](https://opencode.ai/docs/ja/tools#grep) 正規表現を使用してファイルの内容を検索します。 { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} コードベース全体での高速コンテンツ検索。完全な正規表現構文とファイルパターンフィルタリングをサポートします。 * * * ### [glob](https://opencode.ai/docs/ja/tools#glob) パターンマッチングによりファイルを検索します。 { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} `**/*.js` や `src/**/*.ts` などの glob パターンを使用してファイルを検索します。一致するファイルパスを変更時間順に並べて返します。 * * * ### [list](https://opencode.ai/docs/ja/tools#list) 指定されたパス内のファイルとディレクトリを一覧表示します。 { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} このツールはディレクトリの内容を一覧表示します。結果をフィルタリングするための glob パターンを受け入れます。 * * * ### [lsp (実験的)](https://opencode.ai/docs/ja/tools#lsp-%E5%AE%9F%E9%A8%93%E7%9A%84) 構成された LSP サーバーと対話して、定義、参照、ホバー情報、呼び出し階層などのコードインテリジェンス機能を取得します。 { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} サポートされている操作には、`goToDefinition`、`findReferences`、`hover`、`documentSymbol`、`workspaceSymbol`、`goToImplementation`、`prepareCallHierarchy`、`incomingCalls`、および `outgoingCalls` が含まれます。 プロジェクトで使用できる LSP サーバーを構成するには、「LSP Servers\](/docs/lsp). * * * ### [patch](https://opencode.ai/docs/ja/tools#patch) ファイルにパッチを適用します。 { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} このツールは、コードベースにパッチファイルを適用します。さまざまなソースからの差分やパッチを適用するのに役立ちます。 * * * ### [skill](https://opencode.ai/docs/ja/tools#skill) [skill](https://opencode.ai/docs/skills) (`SKILL.md` ファイル) をロードし、会話でその内容を返します。 { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/ja/tools#todowrite) コーディングセッション中に ToDo リストを管理します。 { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} タスクリストを作成および更新して、複雑な操作中の進行状況を追跡します。 LLM はこれを使用して、複数ステップのタスクを整理します。 * * * ### [todoread](https://opencode.ai/docs/ja/tools#todoread) 既存の ToDo リストを読み取ります。 { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} 現在の Todo リストの状態を読み取ります。どのタスクが保留中または完了しているかを追跡するために LLM によって使用されます。 * * * ### [webfetch](https://opencode.ai/docs/ja/tools#webfetch) Web コンテンツを取得します。 { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} LLM が Web ページをフェッチして読み取ることを許可します。ドキュメントの検索やオンラインリソースの調査に役立ちます。 * * * ### [websearch](https://opencode.ai/docs/ja/tools#websearch) ウェブで情報を検索してください。 { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Exa AI を使用して Web 検索を実行し、オンラインで関連情報を見つけます。トピックの調査、最新のイベントの検索、またはトレーニングデータのカットオフを超えた情報の収集に役立ちます。 API キーは必要ありません。ツールは認証なしで Exa AI のホストされた MCP サービスに直接接続します。 * * * ### [question](https://opencode.ai/docs/ja/tools#question) 実行中にユーザーに質問します。 { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} このツールを使用すると、LLM はタスク中にユーザーに質問できるようになります。これは次の場合に役立ちます。 * ユーザーの好みや要件を収集する * 曖昧な指示を明確にする * 実装の選択肢について決定を下す * どの方向に進むべきかについての選択肢を提供する 各質問には、ヘッダー、質問テキスト、およびオプションのリストが含まれます。ユーザーは、提供されたオプションから選択するか、カスタムの回答を入力できます。複数の質問がある場合、ユーザーはすべての回答を送信する前に質問間を移動できます。 * * * [カスタムツール](https://opencode.ai/docs/ja/tools#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%84%E3%83%BC%E3%83%AB) ------------------------------------------------------------------------------------------------------------- カスタムツールを使用すると、LLM が呼び出すことができる独自の関数を定義できます。これらは設定ファイルで定義されており、任意のコードを実行できます。 [カスタムツールの作成について詳しくは、](https://opencode.ai/docs/custom-tools) をご覧ください。 * * * [MCPサーバー](https://opencode.ai/docs/ja/tools#mcp%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC) ------------------------------------------------------------------------------------- MCP (Model Context Protocol) サーバーを使用すると、外部ツールとサービスを統合できます。これには、データベースアクセス、API 統合、サードパーティサービスが含まれます。 [MCP サーバーの設定について詳しくは、](https://opencode.ai/docs/mcp-servers) をご覧ください。 * * * [内部動作](https://opencode.ai/docs/ja/tools#%E5%86%85%E9%83%A8%E5%8B%95%E4%BD%9C) ------------------------------------------------------------------------------- 内部的には、`grep`、`glob`、`list` などのツールは内部で [ripgrep](https://github.com/BurntSushi/ripgrep) を使用します。デフォルトでは、ripgrep は `.gitignore` パターンを尊重します。つまり、`.gitignore` にリストされているファイルとディレクトリは検索とリストから除外されます。 * * * ### [パターンを無視する](https://opencode.ai/docs/ja/tools#%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%E3%82%92%E7%84%A1%E8%A6%96%E3%81%99%E3%82%8B) 通常は無視されるファイルを含めるには、プロジェクトのルートに `.ignore` ファイルを作成します。このファイルでは、特定のパスを明示的に許可できます。 !node_modules/!dist/!build/ たとえば、この `.ignore` ファイルを使用すると、ripgrep は、`node_modules/` にリストされている場合でも、`dist/`、`build/`、および `.gitignore` ディレクトリ内を検索できます。 --- # Risoluzione dei problemi | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/troubleshooting#_top) Risoluzione dei problemi ======================== Problemi comuni e come risolverli. Per diagnosticare problemi con OpenCode, inizia controllando i log e i dati locali che salva su disco. * * * [Log](https://opencode.ai/docs/it/troubleshooting#log) ------------------------------------------------------- I file di log vengono scritti in: * **macOS/Linux**: `~/.local/share/opencode/log/` * **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.local\share\opencode\log` I file di log hanno nomi con timestamp (ad es. `2025-01-09T123456.log`) e vengono conservati i 10 file di log piu recenti. Puoi impostare il livello di log con l’opzione a riga di comando `--log-level` per ottenere informazioni di debug piu dettagliate. Per esempio: `opencode --log-level DEBUG`. * * * [Archiviazione](https://opencode.ai/docs/it/troubleshooting#archiviazione) --------------------------------------------------------------------------- opencode salva i dati delle sessioni e altri dati dell’applicazione su disco in: * **macOS/Linux**: `~/.local/share/opencode/` * **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.local\share\opencode` Questa directory contiene: * `auth.json` - dati di autenticazione come chiavi API, token OAuth * `log/` - log dell’applicazione * `project/` - dati specifici del progetto come dati di sessione e messaggi * Se il progetto e dentro un repository Git, viene salvato in `.//storage/` * Se non e un repository Git, viene salvato in `./global/storage/` * * * [App desktop](https://opencode.ai/docs/it/troubleshooting#app-desktop) ----------------------------------------------------------------------- OpenCode Desktop esegue in background un server locale di OpenCode (il sidecar `opencode-cli`). La maggior parte dei problemi e causata da un plugin che si comporta male, da una cache corrotta o da un’impostazione del server errata. ### [Controlli rapidi](https://opencode.ai/docs/it/troubleshooting#controlli-rapidi) * Chiudi completamente l’app e riaprila. * Se l’app mostra una schermata di errore, fai clic su **Restart** e copia i dettagli dell’errore. * Solo macOS: menu `OpenCode` -> **Reload Webview** (utile se l’interfaccia e vuota o bloccata). * * * ### [Disabilita i plugin](https://opencode.ai/docs/it/troubleshooting#disabilita-i-plugin) Se l’app desktop va in crash all’avvio, si blocca o si comporta in modo strano, inizia disabilitando i plugin. #### [Controlla la configurazione globale](https://opencode.ai/docs/it/troubleshooting#controlla-la-configurazione-globale) Apri il tuo file di configurazione globale e cerca la chiave `plugin`. * **macOS/Linux**: `~/.config/opencode/opencode.jsonc` (o `~/.config/opencode/opencode.json`) * **macOS/Linux** (installazioni vecchie): `~/.local/share/opencode/opencode.jsonc` * **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.config\opencode\opencode.jsonc` Se hai plugin configurati, disabilitali temporaneamente rimuovendo la chiave o impostandola a un array vuoto: { "$schema": "https://opencode.ai/config.json", "plugin": [],} #### [Controlla le directory dei plugin](https://opencode.ai/docs/it/troubleshooting#controlla-le-directory-dei-plugin) OpenCode puo anche caricare plugin locali dal disco. Spostali temporaneamente altrove (o rinomina la cartella) e riavvia l’app desktop: * **Plugin globali** * **macOS/Linux**: `~/.config/opencode/plugins/` * **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.config\opencode\plugins` * **Plugin del progetto** (solo se usi una configurazione per progetto) * `/.opencode/plugins/` Se l’app ricomincia a funzionare, riabilita i plugin uno alla volta per capire quale stia causando il problema. * * * ### [Svuota la cache](https://opencode.ai/docs/it/troubleshooting#svuota-la-cache) Se disabilitare i plugin non aiuta (o l’installazione di un plugin e bloccata), svuota la cache in modo che OpenCode possa ricostruirla. 1. Chiudi completamente OpenCode Desktop. 2. Elimina la directory della cache: * **macOS**: Finder -> `Cmd+Shift+G` -> paste `~/.cache/opencode` * **Linux**: elimina `~/.cache/opencode` (oppure esegui `rm -rf ~/.cache/opencode`) * **Windows**: premi `WIN+R` e incolla `%USERPROFILE%\.cache\opencode` 3. Riavvia OpenCode Desktop. * * * ### [Risolvi problemi di connessione al server](https://opencode.ai/docs/it/troubleshooting#risolvi-problemi-di-connessione-al-server) OpenCode Desktop puo avviare il proprio server locale (predefinito) oppure connettersi a un URL server che hai configurato. Se vedi una finestra **“Connection Failed”** (o l’app non supera mai la schermata di avvio), controlla se hai impostato un URL server personalizzato. #### [Cancella l’URL del server predefinito dell’app desktop](https://opencode.ai/docs/it/troubleshooting#cancella-lurl-del-server-predefinito-dellapp-desktop) Dalla schermata Home, fai clic sul nome del server (con il pallino di stato) per aprire il selettore dei server. Nella sezione **Default server**, fai clic su **Clear**. #### [Rimuovi `server.port` / `server.hostname` dalla tua configurazione](https://opencode.ai/docs/it/troubleshooting#rimuovi-serverport--serverhostname-dalla-tua-configurazione) Se il tuo `opencode.json(c)` contiene una sezione `server`, rimuovila temporaneamente e riavvia l’app desktop. #### [Controlla le variabili d’ambiente](https://opencode.ai/docs/it/troubleshooting#controlla-le-variabili-dambiente) Se hai `OPENCODE_PORT` impostato nell’ambiente, l’app desktop provera a usare quella porta per il server locale. * Rimuovi `OPENCODE_PORT` (o scegli una porta libera) e riavvia. * * * ### [Linux: problemi Wayland / X11](https://opencode.ai/docs/it/troubleshooting#linux-problemi-wayland--x11) Su Linux, alcune configurazioni Wayland possono causare finestre vuote o errori del compositor. * Se sei su Wayland e l’app e vuota o va in crash, prova ad avviarla con `OC_ALLOW_WAYLAND=1`. * Se peggiora la situazione, rimuovilo e prova invece ad avviare sotto una sessione X11. * * * ### [Windows: runtime WebView2](https://opencode.ai/docs/it/troubleshooting#windows-runtime-webview2) Su Windows, OpenCode Desktop richiede **WebView2 Runtime** di Microsoft Edge. Se l’app si apre su una finestra vuota o non parte, installa/aggiorna WebView2 e riprova. * * * ### [Windows: problemi generali di prestazioni](https://opencode.ai/docs/it/troubleshooting#windows-problemi-generali-di-prestazioni) Se riscontri prestazioni lente, problemi di accesso ai file o problemi del terminale su Windows, prova a usare [WSL (Windows Subsystem for Linux)](https://opencode.ai/docs/windows-wsl) . WSL fornisce un ambiente Linux che funziona in modo piu fluido con le funzionalita di OpenCode. * * * ### [Notifiche non visualizzate](https://opencode.ai/docs/it/troubleshooting#notifiche-non-visualizzate) OpenCode Desktop mostra le notifiche di sistema solo quando: * le notifiche sono abilitate per OpenCode nelle impostazioni del sistema operativo, e * la finestra dell’app non e in primo piano. * * * ### [Reimposta lo stato dell’app desktop (ultima risorsa)](https://opencode.ai/docs/it/troubleshooting#reimposta-lo-stato-dellapp-desktop-ultima-risorsa) Se l’app non si avvia e non riesci a ripulire le impostazioni dall’interfaccia, reimposta lo stato salvato dell’app desktop. 1. Chiudi OpenCode Desktop. 2. Trova ed elimina questi file (si trovano nella directory dati dell’app OpenCode Desktop): * `opencode.settings.dat` (desktop default server URL) * `opencode.global.dat` e `opencode.workspace.*.dat` (stato dell’interfaccia come server/progetti recenti) Per trovare rapidamente la directory: * **macOS**: Finder -> `Cmd+Shift+G` -> `~/Library/Application Support` (poi cerca i nomi file qui sopra) * **Linux**: cerca sotto `~/.local/share` i nomi file qui sopra * **Windows**: premi `WIN+R` -> `%APPDATA%` (poi cerca i nomi file qui sopra) * * * [Ottenere aiuto](https://opencode.ai/docs/it/troubleshooting#ottenere-aiuto) ----------------------------------------------------------------------------- Se riscontri problemi con OpenCode: 1. **Segnala i problemi su GitHub** Il modo migliore per segnalare bug o richiedere funzionalita e tramite il nostro repository GitHub: [**github.com/anomalyco/opencode/issues**](https://github.com/anomalyco/opencode/issues) Prima di creare una nuova issue, cerca tra quelle esistenti per vedere se il problema e gia stato segnalato. 2. **Unisciti al nostro Discord** Per supporto in tempo reale e discussioni con la community, unisciti al nostro server Discord: [**opencode.ai/discord**](https://opencode.ai/discord) * * * [Problemi comuni](https://opencode.ai/docs/it/troubleshooting#problemi-comuni) ------------------------------------------------------------------------------- Ecco alcuni problemi comuni e come risolverli. * * * ### [OpenCode non si avvia](https://opencode.ai/docs/it/troubleshooting#opencode-non-si-avvia) 1. Controlla i log per eventuali messaggi di errore 2. Prova a eseguire con `--print-logs` per vedere l’output nel terminale 3. Assicurati di avere l’ultima versione con `opencode upgrade` * * * ### [Problemi di autenticazione](https://opencode.ai/docs/it/troubleshooting#problemi-di-autenticazione) 1. Prova a riautenticarti con il comando `/connect` nella TUI 2. Controlla che le chiavi API siano valide 3. Assicurati che la rete permetta connessioni all’API del provider * * * ### [Modello non disponibile](https://opencode.ai/docs/it/troubleshooting#modello-non-disponibile) 1. Controlla di esserti autenticato con il provider 2. Verifica che il nome del modello nella configurazione sia corretto 3. Alcuni modelli potrebbero richiedere accessi o abbonamenti specifici Se incontri `ProviderModelNotFoundError`, probabilmente stai facendo riferimento a un modello in modo errato da qualche parte. I modelli vanno indicati in questo formato: `/` Esempi: * `openai/gpt-4.1` * `openrouter/google/gemini-2.5-flash` * `opencode/kimi-k2` Per capire a quali modelli hai accesso, esegui `opencode models` * * * ### [ProviderInitError](https://opencode.ai/docs/it/troubleshooting#provideriniterror) Se incontri un ProviderInitError, probabilmente la tua configurazione e invalida o corrotta. Per risolvere: 1. Per prima cosa, verifica che il provider sia configurato correttamente seguendo la [guida ai provider](https://opencode.ai/docs/providers) 2. Se il problema persiste, prova a cancellare la configurazione salvata: rm -rf ~/.local/share/opencode Su Windows, premi `WIN+R` ed elimina: `%USERPROFILE%\.local\share\opencode` 3. Riautenticati con il provider usando il comando `/connect` nella TUI. * * * ### [AI\_APICallError e problemi dei pacchetti provider](https://opencode.ai/docs/it/troubleshooting#ai_apicallerror-e-problemi-dei-pacchetti-provider) Se incontri errori nelle chiamate API, potrebbe dipendere da pacchetti provider non aggiornati. opencode installa dinamicamente i pacchetti provider (OpenAI, Anthropic, Google, ecc.) quando servono e li mette in cache localmente. Per risolvere problemi coi pacchetti provider: 1. Svuota la cache dei pacchetti provider: rm -rf ~/.cache/opencode Su Windows, premi `WIN+R` ed elimina: `%USERPROFILE%\.cache\opencode` 2. Riavvia opencode per reinstallare i pacchetti provider piu recenti Questo forzera opencode a scaricare le versioni piu recenti dei pacchetti provider, cosa che spesso risolve problemi di compatibilita con parametri dei modelli e cambiamenti delle API. * * * ### [Copia/incolla non funziona su Linux](https://opencode.ai/docs/it/troubleshooting#copiaincolla-non-funziona-su-linux) Su Linux e necessario avere installata una delle seguenti utility per gli appunti affinche copia/incolla funzioni: **Per sistemi X11:** apt install -y xclip# orapt install -y xsel **Per sistemi Wayland:** apt install -y wl-clipboard **Per ambienti headless:** apt install -y xvfb# and run:Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &export DISPLAY=:99.0 opencode rilevera se stai usando Wayland e preferira `wl-clipboard`; altrimenti provera a trovare gli strumenti per gli appunti nell’ordine: `xclip` e `xsel`. --- # Инструменты | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/tools#_top) Инструменты =========== Управляйте инструментами, которые может использовать LLM. Инструменты позволяют LLM выполнять действия в вашей кодовой базе. opencode поставляется с набором встроенных инструментов, но вы можете расширить его с помощью [пользовательских инструментов](https://opencode.ai/docs/custom-tools) или [MCP-серверов](https://opencode.ai/docs/mcp-servers) . По умолчанию все инструменты **включены** и не требуют разрешения для запуска. Вы можете контролировать поведение инструмента через [permissions](https://opencode.ai/docs/permissions) . * * * [Настройка](https://opencode.ai/docs/ru/tools#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0) ------------------------------------------------------------------------------------------------------ Используйте поле `permission` для управления поведением инструмента. Вы можете разрешить, запретить или потребовать одобрения для каждого инструмента. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Вы также можете использовать подстановочные знаки для одновременного управления несколькими инструментами. Например, чтобы потребовать одобрения всех инструментов с сервера MCP: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Подробнее](https://opencode.ai/docs/permissions) о настройке разрешений. * * * [Встроенный](https://opencode.ai/docs/ru/tools#%D0%B2%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9) ------------------------------------------------------------------------------------------------------------- Вот все встроенные инструменты, доступные в opencode. * * * ### [bash](https://opencode.ai/docs/ru/tools#bash) Выполняйте shell-команды в среде вашего проекта. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Этот инструмент позволяет LLM запускать команды терминала, такие как `npm install`, `git status` или любую другую shell-команду. * * * ### [edit](https://opencode.ai/docs/ru/tools#edit) Измените существующие файлы, используя точную замену строк. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Этот инструмент выполняет точное редактирование файлов, заменяя точные совпадения текста. Это основной способ изменения кода в LLM. * * * ### [write](https://opencode.ai/docs/ru/tools#write) Создавайте новые файлы или перезаписывайте существующие. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Используйте это, чтобы позволить LLM создавать новые файлы. Он перезапишет существующие файлы, если они уже существуют. * * * ### [read](https://opencode.ai/docs/ru/tools#read) Прочитайте содержимое файла из вашей кодовой базы. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Этот инструмент читает файлы и возвращает их содержимое. Он поддерживает чтение определенных диапазонов строк для больших файлов. * * * ### [grep](https://opencode.ai/docs/ru/tools#grep) Поиск содержимого файла с помощью регулярных выражений. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Быстрый поиск контента по вашей кодовой базе. Поддерживает полный синтаксис регулярных выражений и фильтрацию шаблонов файлов. * * * ### [glob](https://opencode.ai/docs/ru/tools#glob) Найдите файлы по шаблону. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Ищите файлы, используя шаблоны glob, например `**/*.js` или `src/**/*.ts`. Возвращает соответствующие пути к файлам, отсортированные по времени изменения. * * * ### [list](https://opencode.ai/docs/ru/tools#list) Список файлов и каталогов по заданному пути. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Этот инструмент отображает содержимое каталога. Он принимает шаблоны glob для фильтрации результатов. * * * ### [lsp (экспериментальный)](https://opencode.ai/docs/ru/tools#lsp-%D1%8D%D0%BA%D1%81%D0%BF%D0%B5%D1%80%D0%B8%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9) Взаимодействуйте с настроенными серверами LSP, чтобы получить функции анализа кода, такие как определения, ссылки, информация о наведении и иерархия вызовов. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Поддерживаемые операции включают `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` и `outgoingCalls`. Чтобы настроить серверы LSP, доступные для вашего проекта, см. [LSP Servers](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/ru/tools#patch) Применяйте патчи к файлам. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Этот инструмент применяет файлы исправлений к вашей кодовой базе. Полезно для применения различий и патчей из различных источников. * * * ### [skill](https://opencode.ai/docs/ru/tools#skill) Загрузите [skill](https://opencode.ai/docs/skills) (файл `SKILL.md`) и верните его содержимое в диалог. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/ru/tools#todowrite) Управляйте списками дел во время сеансов кодирования. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Создает и обновляет списки задач для отслеживания прогресса во время сложных операций. LLM использует это для организации многоэтапных задач. * * * ### [todoread](https://opencode.ai/docs/ru/tools#todoread) Прочтите существующие списки дел. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Считывает текущее состояние списка дел. Используется LLM для отслеживания задач, ожидающих или завершенных. * * * ### [webfetch](https://opencode.ai/docs/ru/tools#webfetch) Получить веб-контент. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Позволяет LLM получать и читать веб-страницы. Полезно для поиска документации или исследования онлайн-ресурсов. * * * ### [websearch](https://opencode.ai/docs/ru/tools#websearch) Найдите информацию в Интернете. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Выполняет поиск в Интернете с помощью Exa AI для поиска соответствующей информации в Интернете. Полезно для исследования тем, поиска текущих событий или сбора информации, выходящей за рамки данных обучения. Ключ API не требуется — инструмент подключается напрямую к сервису MCP, размещенному на Exa AI, без аутентификации. * * * ### [question](https://opencode.ai/docs/ru/tools#question) Задавайте вопросы пользователю во время выполнения. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Этот инструмент позволяет LLM задавать вопросы пользователю во время выполнения задачи. Это полезно для: * Сбор предпочтений или требований пользователей * Уточнение двусмысленных инструкций * Получение решений по вариантам реализации * Предлагая выбор, в каком направлении двигаться Каждый вопрос включает заголовок, текст вопроса и список вариантов. Пользователи могут выбрать один из предложенных вариантов или ввести собственный ответ. Если вопросов несколько, пользователи могут перемещаться между ними, прежде чем отправлять все ответы. * * * [Пользовательские инструменты](https://opencode.ai/docs/ru/tools#%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B5-%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Пользовательские инструменты позволяют вам определять собственные функции, которые может вызывать LLM. Они определены в вашем файле конфигурации и могут выполнять произвольный код. [Подробнее](https://opencode.ai/docs/custom-tools) о создании собственных инструментов. * * * [MCP-серверы](https://opencode.ai/docs/ru/tools#mcp-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D1%8B) ------------------------------------------------------------------------------------------------ Серверы MCP (Model Context Protocol) позволяют интегрировать внешние инструменты и сервисы. Сюда входит доступ к базе данных, интеграция API и сторонние сервисы. [Подробнее](https://opencode.ai/docs/mcp-servers) о настройке серверов MCP. * * * [Внутреннее устройство](https://opencode.ai/docs/ru/tools#%D0%B2%D0%BD%D1%83%D1%82%D1%80%D0%B5%D0%BD%D0%BD%D0%B5%D0%B5-%D1%83%D1%81%D1%82%D1%80%D0%BE%D0%B9%D1%81%D1%82%D0%B2%D0%BE) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Внутренне такие инструменты, как `grep`, `glob` и `list`, используют [ripgrep](https://github.com/BurntSushi/ripgrep) . По умолчанию ripgrep учитывает шаблоны `.gitignore`, что означает, что файлы и каталоги, перечисленные в вашем `.gitignore`, будут исключены из поиска и списков. * * * ### [Игнорировать шаблоны](https://opencode.ai/docs/ru/tools#%D0%B8%D0%B3%D0%BD%D0%BE%D1%80%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C-%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD%D1%8B) Чтобы включить файлы, которые обычно игнорируются, создайте файл `.ignore` в корне вашего проекта. Этот файл может явно разрешать определенные пути. !node_modules/!dist/!build/ Например, этот файл `.ignore` позволяет ripgrep выполнять поиск в каталогах `node_modules/`, `dist/` и `build/`, даже если они указаны в `.gitignore`. --- # Herramientas | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/tools#_top) Herramientas ============ Administre las herramientas que puede usar un LLM. Las herramientas permiten que LLM realice acciones en su código base. OpenCode viene con un conjunto de herramientas integradas, pero puede ampliarlo con [herramientas personalizadas](https://opencode.ai/docs/custom-tools) o [servidores MCP](https://opencode.ai/docs/mcp-servers) . De forma predeterminada, todas las herramientas están **habilitadas** y no necesitan permiso para ejecutarse. Puede controlar el comportamiento de la herramienta a través de [permisos](https://opencode.ai/docs/permissions) . * * * [Configuración](https://opencode.ai/docs/es/tools#configuraci%C3%B3n) ---------------------------------------------------------------------- Utilice el campo `permission` para controlar el comportamiento de la herramienta. Puede permitir, denegar o exigir aprobación para cada herramienta. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} También puedes utilizar comodines para controlar varias herramientas a la vez. Por ejemplo, para solicitar aprobación para todas las herramientas de un servidor MCP: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Más información](https://opencode.ai/docs/permissions) sobre la configuración de permisos. * * * [Integradas](https://opencode.ai/docs/es/tools#integradas) ----------------------------------------------------------- Aquí están todas las herramientas integradas disponibles en OpenCode. * * * ### [bash](https://opencode.ai/docs/es/tools#bash) Ejecute comandos de shell en el entorno de su proyecto. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} Esta herramienta permite que LLM ejecute comandos de terminal como `npm install`, `git status` o cualquier otro comando de shell. * * * ### [edit](https://opencode.ai/docs/es/tools#edit) Modifique archivos existentes utilizando reemplazos de cadenas exactas. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Esta herramienta realiza ediciones precisas de archivos reemplazando coincidencias de texto exactas. Es la forma principal en que LLM modifica el código. * * * ### [write](https://opencode.ai/docs/es/tools#write) Cree nuevos archivos o sobrescriba los existentes. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Utilice esto para permitir que LLM cree nuevos archivos. Sobrescribirá los archivos existentes si ya existen. * * * ### [read](https://opencode.ai/docs/es/tools#read) Lea el contenido del archivo desde su base de código. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Esta herramienta lee archivos y devuelve su contenido. Admite la lectura de rangos de líneas específicos para archivos grandes. * * * ### [grep](https://opencode.ai/docs/es/tools#grep) Busque contenidos de archivos utilizando expresiones regulares. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Búsqueda rápida de contenido en su base de código. Admite sintaxis de expresiones regulares completa y filtrado de patrones de archivos. * * * ### [glob](https://opencode.ai/docs/es/tools#glob) Encuentre archivos por coincidencia de patrones. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Busque archivos usando patrones globales como `**/*.js` o `src/**/*.ts`. Devuelve rutas de archivos coincidentes ordenadas por hora de modificación. * * * ### [list](https://opencode.ai/docs/es/tools#list) Enumere archivos y directorios en una ruta determinada. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} Esta herramienta enumera el contenido del directorio. Acepta patrones globales para filtrar resultados. * * * ### [lsp (experimental)](https://opencode.ai/docs/es/tools#lsp-experimental) Interactúe con sus servidores LSP configurados para obtener funciones de inteligencia de código como definiciones, referencias, información de desplazamiento y jerarquía de llamadas. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Las operaciones admitidas incluyen `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` y `outgoingCalls`. Para configurar qué servidores LSP están disponibles para su proyecto, consulte [Servidores LSP](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/es/tools#patch) Aplicar parches a los archivos. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Esta herramienta aplica archivos de parche a su código base. Útil para aplicar diferencias y parches de diversas fuentes. * * * ### [skill](https://opencode.ai/docs/es/tools#skill) Cargue una [habilidad](https://opencode.ai/docs/skills) (un archivo `SKILL.md`) y devuelva su contenido en la conversación. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/es/tools#todowrite) Administre listas de tareas pendientes durante las sesiones de codificación. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Crea y actualiza listas de tareas para realizar un seguimiento del progreso durante operaciones complejas. El LLM usa esto para organizar tareas de varios pasos. * * * ### [todoread](https://opencode.ai/docs/es/tools#todoread) Leer listas de tareas pendientes existentes. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Lee el estado actual de la lista de tareas pendientes. Utilizado por LLM para rastrear qué tareas están pendientes o completadas. * * * ### [webfetch](https://opencode.ai/docs/es/tools#webfetch) Obtener contenido web. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Permite que LLM busque y lea páginas web. Útil para buscar documentación o investigar recursos en línea. * * * ### [websearch](https://opencode.ai/docs/es/tools#websearch) Busque información en la web. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Realiza búsquedas web utilizando Exa AI para encontrar información relevante en línea. Útil para investigar temas, encontrar eventos actuales o recopilar información más allá del límite de datos de entrenamiento. No se requiere ninguna clave API: la herramienta se conecta directamente al servicio MCP alojado de Exa AI sin autenticación. * * * ### [question](https://opencode.ai/docs/es/tools#question) Haga preguntas al usuario durante la ejecución. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} Esta herramienta permite que LLM haga preguntas al usuario durante una tarea. Es útil para: * Recopilar preferencias o requisitos del usuario. * Aclarar instrucciones ambiguas * Tomar decisiones sobre las opciones de implementación. * Ofrecer opciones sobre qué dirección tomar. Cada pregunta incluye un encabezado, el texto de la pregunta y una lista de opciones. Los usuarios pueden seleccionar entre las opciones proporcionadas o escribir una respuesta personalizada. Cuando hay varias preguntas, los usuarios pueden navegar entre ellas antes de enviar todas las respuestas. * * * [Herramientas personalizadas](https://opencode.ai/docs/es/tools#herramientas-personalizadas) --------------------------------------------------------------------------------------------- Las herramientas personalizadas le permiten definir sus propias funciones a las que LLM puede llamar. Estos están definidos en su archivo de configuración y pueden ejecutar código arbitrario. [Más información](https://opencode.ai/docs/custom-tools) sobre la creación de herramientas personalizadas. * * * [Servidores MCP](https://opencode.ai/docs/es/tools#servidores-mcp) ------------------------------------------------------------------- Los servidores MCP (Model Context Protocol) le permiten integrar herramientas y servicios externos. Esto incluye acceso a bases de datos, integraciones API y servicios de terceros. [Más información](https://opencode.ai/docs/mcp-servers) sobre la configuración de servidores MCP. * * * [Internos](https://opencode.ai/docs/es/tools#internos) ------------------------------------------------------- Internamente, herramientas como `grep`, `glob` y `list` usan [ripgrep](https://github.com/BurntSushi/ripgrep) bajo el capó. De forma predeterminada, ripgrep respeta los patrones `.gitignore`, lo que significa que los archivos y directorios enumerados en su `.gitignore` se excluirán de las búsquedas y listados. * * * ### [Ignorar patrones](https://opencode.ai/docs/es/tools#ignorar-patrones) Para incluir archivos que normalmente se ignorarían, cree un archivo `.ignore` en la raíz de su proyecto. Este archivo puede permitir explícitamente ciertas rutas. !node_modules/!dist/!build/ Por ejemplo, este archivo `.ignore` permite que ripgrep busque dentro de los directorios `node_modules/`, `dist/` y `build/` incluso si figuran en `.gitignore`. --- # Narzędzia | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/tools#_top) Narzędzia ========= Zarządzaj narzędziami, z których może korzystać LLM. Narzędzia umożliwiają LLM wykonywanie działań w bazie kodu. OpenCode posiada zestaw wbudowanych narzędzi, ale możesz go rozszerzyć o [narzędzia niestandardowe](https://opencode.ai/docs/custom-tools) lub [serwery MCP](https://opencode.ai/docs/mcp-servers) . Domyślnie wszystkie narzędzia są **włączone** i nie wymagają zatwierdzenia przed uruchomieniem. Możesz kontrolować zachowanie narzędzi poprzez [uprawnienia](https://opencode.ai/docs/permissions) . * * * [Konfiguracja](https://opencode.ai/docs/pl/tools#konfiguracja) --------------------------------------------------------------- Użyj pola `permission` do kontrolowania zachowania narzędzia. Dla każdego narzędzia możesz zezwolić (`allow`), odmówić (`deny`) lub wymagać zatwierdzenia (`ask`). { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} Możesz także używać symboli wieloznacznych do kontrolowania wielu narzędzi jednocześnie. Na przykład, aby wymagać zatwierdzenia dla wszystkich narzędzi z serwera MCP: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [Dowiedz się więcej](https://opencode.ai/docs/permissions) o konfigurowaniu uprawnień. * * * [Wbudowane narzędzia](https://opencode.ai/docs/pl/tools#wbudowane-narz%C4%99dzia) ---------------------------------------------------------------------------------- Oto wszystkie wbudowane narzędzia dostępne w OpenCode. * * * ### [bash](https://opencode.ai/docs/pl/tools#bash) Wykonuj polecenia powłoki (shell) w środowisku projektu. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} To narzędzie umożliwia LLM uruchamianie poleceń terminalowych, takich jak `npm install`, `git status` lub dowolne inne polecenie powłoki. * * * ### [edit](https://opencode.ai/docs/pl/tools#edit) Modyfikuj istniejące pliki poprzez precyzyjne zastępowanie tekstu. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} To narzędzie umożliwia precyzyjną edycję plików poprzez zastąpienie dokładnych dopasowań tekstu. Jest to główny sposób, w jaki LLM modyfikuje kod. * * * ### [write](https://opencode.ai/docs/pl/tools#write) Twórz nowe pliki lub nadpisuj istniejące. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} Użyj tego, aby umożliwić LLM tworzenie nowych plików. Zastąpi istniejące pliki, jeśli już istnieją. * * * ### [read](https://opencode.ai/docs/pl/tools#read) Odczytaj zawartość pliku z bazy kodu. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} Narzędzie to odczytuje pliki i zwraca ich zawartość. Obsługuje czytanie określonych zakresów linii w przypadku dużych plików. * * * ### [grep](https://opencode.ai/docs/pl/tools#grep) Przeszukuj zawartość plików za pomocą wyrażeń regularnych. { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} Szybkie wyszukiwanie treści w całej bazie kodu. Obsługuje pełną składnię wyrażeń regularnych i filtrowanie wzorców plików. * * * ### [glob](https://opencode.ai/docs/pl/tools#glob) Znajduj pliki na podstawie wzorców. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} Szukaj plików przy użyciu wzorców glob, takich jak `**/*.js` lub `src/**/*.ts`. Zwraca pasujące ścieżki plików posortowane według czasu modyfikacji. * * * ### [list](https://opencode.ai/docs/pl/tools#list) Wyświetla listę plików i katalogów w podanej ścieżce. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} To narzędzie wyświetla zawartość katalogu. Akceptuje wzorce glob do filtrowania wyników. * * * ### [LSP (eksperymentalne)](https://opencode.ai/docs/pl/tools#lsp-eksperymentalne) Interakcja ze skonfigurowanymi serwerami LSP w celu uzyskania funkcji analizy kodu, takich jak definicje, referencje, podpowiedzi (hover) i hierarchia wywołań. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} Obsługiwane operacje obejmują `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` i `outgoingCalls`. Aby skonfigurować, które serwery LSP są dostępne dla Twojego projektu, zobacz [Serwery LSP](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/pl/tools#patch) Stosuj łatki (patches) do plików. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} To narzędzie stosuje pliki różnicowe (diffs) do bazy kodu. Przydatne do stosowania zmian z różnych źródeł. * * * ### [skill](https://opencode.ai/docs/pl/tools#skill) Załaduj [umiejętność](https://opencode.ai/docs/skills) (plik `SKILL.md`) i zwróć jej treść w rozmowie. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/pl/tools#todowrite) Zarządzaj listami zadań (todo) podczas sesji kodowania. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} Tworzy i aktualizuje listy zadań w celu śledzenia postępu podczas złożonych operacji. LLM wykorzystuje to do organizowania zadań wieloetapowych. * * * ### [todoread](https://opencode.ai/docs/pl/tools#todoread) Odczytuj istniejące listy zadań (todo). { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} Odczytuje bieżący stan listy rzeczy do zrobienia. Używany przez LLM do śledzenia zadań oczekujących lub ukończonych. * * * ### [webfetch](https://opencode.ai/docs/pl/tools#webfetch) Pobieraj treści z sieci. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} Umożliwia LLM pobieranie i odczytywanie stron internetowych. Przydatne do wyszukiwania dokumentacji lub zasobów online. * * * ### [websearch](https://opencode.ai/docs/pl/tools#websearch) Wyszukaj informacje w Internecie. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} Przeszukuje Internet za pomocą Exa AI, aby znaleźć odpowiednie informacje. Przydatne do badania tematów, znajdowania bieżących wydarzeń lub zbierania informacji wykraczających poza zbiór danych treningowych. Nie jest wymagany żaden klucz API — narzędzie łączy się bezpośrednio z usługą MCP hostowaną przez Exa AI bez uwierzytelniania. * * * ### [question](https://opencode.ai/docs/pl/tools#question) Zadawaj pytania użytkownikowi podczas wykonywania. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} To narzędzie umożliwia LLM zadawanie pytań użytkownikowi podczas wykonywania zadania. Jest to przydatne do: * Zbierania preferencji i wymagań użytkownika * Doprecyzowania niejednoznacznych instrukcji * Podejmowania decyzji dotyczących implementacji * Proponowania możliwych kierunków działania Każde pytanie zawiera nagłówek, tekst pytania i listę opcji. Użytkownicy mogą wybierać spośród dostępnych opcji lub wpisać niestandardową odpowiedź. Jeśli pytań jest wiele, użytkownicy mogą nawigować między nimi przed przesłaniem wszystkich odpowiedzi. * * * [Narzędzia niestandardowe](https://opencode.ai/docs/pl/tools#narz%C4%99dzia-niestandardowe) -------------------------------------------------------------------------------------------- Niestandardowe narzędzia pozwalają zdefiniować własne funkcje, które LLM może wywołać. Są one zdefiniowane w pliku konfiguracyjnym i mogą wykonywać dowolny kod. [Więcej informacji](https://opencode.ai/docs/custom-tools) o tworzeniu narzędzi niestandardowych. * * * [Serwery MCP](https://opencode.ai/docs/pl/tools#serwery-mcp) ------------------------------------------------------------- Serwery MCP (Model Context Protocol) umożliwiają integrację zewnętrznych narzędzi i usług. Obejmuje to dostęp do baz danych, integracje API i usługi stron trzecich. [Dowiedz się więcej](https://opencode.ai/docs/mcp-servers) o konfigurowaniu serwerów MCP. * * * [Szczegóły techniczne](https://opencode.ai/docs/pl/tools#szczeg%C3%B3%C5%82y-techniczne) ----------------------------------------------------------------------------------------- Wewnętrznie narzędzia takie jak `grep`, `glob` i `list` używają [ripgrep](https://github.com/BurntSushi/ripgrep) . Domyślnie ripgrep respektuje wzorce `.gitignore`, co oznacza, że pliki i katalogi wymienione w Twoim `.gitignore` zostaną wykluczone z wyszukiwań i list. * * * ### [Ignorowanie plików](https://opencode.ai/docs/pl/tools#ignorowanie-plik%C3%B3w) Aby uwzględnić pliki, które normalnie byłyby ignorowane, utwórz plik `.ignore` w katalogu głównym projektu. Ten plik może jawnie zezwalać na określone ścieżki. !node_modules/!dist/!build/ Na przykład ten plik `.ignore` pozwala ripgrepowi przeszukiwać katalogi `node_modules/`, `dist/` i `build/`, nawet jeśli są one wymienione w `.gitignore`. --- # الأدوات | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/tools#_top) الأدوات ======= إدارة الأدوات التي يمكن لـ LLM استخدامها. تتيح الأدوات لـ LLM تنفيذ إجراءات داخل قاعدة الشفرة الخاصة بك. يأتي OpenCode مع مجموعة من الأدوات المدمجة، لكن يمكنك توسيعه عبر [أدوات مخصصة](https://opencode.ai/docs/custom-tools) أو [خوادم MCP](https://opencode.ai/docs/mcp-servers) . افتراضيا، تكون جميع الأدوات **مفعلة** ولا تحتاج إلى إذن للتشغيل. يمكنك التحكم في سلوك الأدوات عبر [الأذونات](https://opencode.ai/docs/permissions) . * * * [التهيئة](https://opencode.ai/docs/ar/tools#%D8%A7%D9%84%D8%AA%D9%87%D9%8A%D8%A6%D8%A9) ---------------------------------------------------------------------------------------- استخدم الحقل `permission` للتحكم في سلوك الأدوات. يمكنك السماح أو الرفض أو طلب الموافقة لكل أداة. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} يمكنك أيضا استخدام أحرف البدل للتحكم في عدة أدوات دفعة واحدة. على سبيل المثال، لطلب الموافقة على جميع الأدوات القادمة من خادم MCP: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [اعرف المزيد](https://opencode.ai/docs/permissions) حول تهيئة الأذونات. * * * [المدمجة](https://opencode.ai/docs/ar/tools#%D8%A7%D9%84%D9%85%D8%AF%D9%85%D8%AC%D8%A9) ---------------------------------------------------------------------------------------- فيما يلي جميع الأدوات المدمجة المتاحة في OpenCode. * * * ### [bash](https://opencode.ai/docs/ar/tools#bash) نفذ أوامر shell في بيئة مشروعك. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} تتيح هذه الأداة لـ LLM تشغيل أوامر terminal مثل `npm install` و`git status` أو أي أمر shell آخر. * * * ### [edit](https://opencode.ai/docs/ar/tools#edit) عدّل الملفات الموجودة باستخدام استبدال نصي مطابق تماما. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} تجري هذه الأداة تعديلات دقيقة على الملفات عبر استبدال مقاطع نصية متطابقة. وهي الطريقة الأساسية التي يعدّل بها LLM الشفرة. * * * ### [write](https://opencode.ai/docs/ar/tools#write) أنشئ ملفات جديدة أو اكتب فوق الملفات الموجودة. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} استخدم هذا للسماح لـ LLM بإنشاء ملفات جديدة. سيكتب فوق الملفات الموجودة إذا كانت موجودة بالفعل. * * * ### [read](https://opencode.ai/docs/ar/tools#read) اقرأ محتويات الملفات من قاعدة الشفرة الخاصة بك. { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} تقرأ هذه الأداة الملفات وتعيد محتوياتها. وتدعم قراءة نطاقات محددة من الأسطر للملفات الكبيرة. * * * ### [grep](https://opencode.ai/docs/ar/tools#grep) ابحث في محتوى الملفات باستخدام التعابير النمطية (Regex). { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} بحث سريع في المحتوى عبر قاعدة الشفرة الخاصة بك. يدعم صياغة Regex الكاملة وتصفية الملفات عبر أنماط المسارات. * * * ### [glob](https://opencode.ai/docs/ar/tools#glob) اعثر على الملفات عبر مطابقة الأنماط. { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} ابحث عن الملفات باستخدام أنماط glob مثل `**/*.js` أو `src/**/*.ts`. يعيد مسارات الملفات المطابقة مرتبة حسب وقت التعديل. * * * ### [list](https://opencode.ai/docs/ar/tools#list) اعرض قائمة بالملفات والمجلدات في مسار محدد. { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} تعرض هذه الأداة محتويات المجلد. وتقبل أنماط glob لتصفية النتائج. * * * ### [lsp (experimental)](https://opencode.ai/docs/ar/tools#lsp-experimental) تفاعل مع خوادم LSP التي قمت بتهيئتها للحصول على ميزات ذكاء الشفرة مثل التعاريف والمراجع ومعلومات التحويم وتسلسل الاستدعاءات. { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} تتضمن العمليات المدعومة: `goToDefinition` و`findReferences` و`hover` و`documentSymbol` و`workspaceSymbol` و`goToImplementation` و`prepareCallHierarchy` و`incomingCalls` و`outgoingCalls`. لتهيئة خوادم LSP المتاحة لمشروعك، راجع [خوادم LSP](https://opencode.ai/docs/lsp) . * * * ### [patch](https://opencode.ai/docs/ar/tools#patch) طبّق الرقع (Patches) على الملفات. { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} تطبق هذه الأداة ملفات الرقع على قاعدة الشفرة الخاصة بك. وهي مفيدة لتطبيق الفروقات (Diffs) والرقع من مصادر متعددة. * * * ### [skill](https://opencode.ai/docs/ar/tools#skill) حمّل [مهارة](https://opencode.ai/docs/skills) (ملف `SKILL.md`) وأعد محتواها ضمن المحادثة. { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/ar/tools#todowrite) أدِر قوائم المهام أثناء جلسات البرمجة. { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} تنشئ هذه الأداة قوائم المهام وتحدّثها لتتبع التقدم أثناء العمليات المعقدة. يستخدمها LLM لتنظيم المهام متعددة الخطوات. * * * ### [todoread](https://opencode.ai/docs/ar/tools#todoread) اقرأ قوائم المهام الموجودة. { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} تقرأ هذه الأداة الحالة الحالية لقائمة المهام. يستخدمها LLM لتتبع المهام المعلقة أو المكتملة. * * * ### [webfetch](https://opencode.ai/docs/ar/tools#webfetch) اجلب محتوى الويب. { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} تتيح هذه الأداة لـ LLM جلب صفحات الويب وقراءتها. وهي مفيدة للبحث عن التوثيق أو لاستكشاف موارد عبر الإنترنت. * * * ### [websearch](https://opencode.ai/docs/ar/tools#websearch) ابحث في الويب عن معلومات. { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} تجري عمليات بحث على الويب باستخدام Exa AI للعثور على معلومات ذات صلة عبر الإنترنت. وهي مفيدة للبحث في المواضيع، والعثور على أحداث جارية، أو جمع معلومات تتجاوز حد بيانات التدريب. لا يلزم مفتاح API - إذ تتصل الأداة مباشرة بخدمة MCP المستضافة لدى Exa AI دون مصادقة. * * * ### [question](https://opencode.ai/docs/ar/tools#question) اطرح على المستخدم أسئلة أثناء التنفيذ. { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} تتيح هذه الأداة لـ LLM طرح أسئلة على المستخدم أثناء المهمة. وهي مفيدة من أجل: * جمع تفضيلات المستخدم أو متطلباته * توضيح التعليمات غير الواضحة * الحصول على قرارات حول خيارات التنفيذ * تقديم خيارات حول الاتجاه الذي يجب اتباعه يتضمن كل سؤال عنوانا ونص السؤال وقائمة بالخيارات. يمكن للمستخدمين الاختيار من الخيارات المتاحة أو كتابة إجابة مخصصة. وعند وجود عدة أسئلة، يمكن للمستخدمين التنقل بينها قبل إرسال جميع الإجابات. * * * [أدوات مخصصة](https://opencode.ai/docs/ar/tools#%D8%A3%D8%AF%D9%88%D8%A7%D8%AA-%D9%85%D8%AE%D8%B5%D8%B5%D8%A9) --------------------------------------------------------------------------------------------------------------- تتيح لك الأدوات المخصصة تعريف دوالك الخاصة التي يمكن لـ LLM استدعاؤها. تُعرّف هذه الأدوات في ملف التهيئة ويمكنها تنفيذ شفرة عشوائية. [اعرف المزيد](https://opencode.ai/docs/custom-tools) حول إنشاء أدوات مخصصة. * * * [خوادم MCP](https://opencode.ai/docs/ar/tools#%D8%AE%D9%88%D8%A7%D8%AF%D9%85-mcp) ---------------------------------------------------------------------------------- تتيح لك خوادم MCP (Model Context Protocol) دمج أدوات وخدمات خارجية. يشمل ذلك الوصول إلى قواعد البيانات وتكاملات API وخدمات الجهات الخارجية. [اعرف المزيد](https://opencode.ai/docs/mcp-servers) حول تهيئة خوادم MCP. * * * [التفاصيل الداخلية](https://opencode.ai/docs/ar/tools#%D8%A7%D9%84%D8%AA%D9%81%D8%A7%D8%B5%D9%8A%D9%84-%D8%A7%D9%84%D8%AF%D8%A7%D8%AE%D9%84%D9%8A%D8%A9) --------------------------------------------------------------------------------------------------------------------------------------------------------- داخليا، تستخدم أدوات مثل `grep` و`glob` و`list` أداة [ripgrep](https://github.com/BurntSushi/ripgrep) في الخلفية. افتراضيا، يحترم ripgrep أنماط `.gitignore`، ما يعني أن الملفات والمجلدات المدرجة في `.gitignore` ستُستبعد من عمليات البحث وعرض القوائم. * * * ### [أنماط التجاهل](https://opencode.ai/docs/ar/tools#%D8%A3%D9%86%D9%85%D8%A7%D8%B7-%D8%A7%D9%84%D8%AA%D8%AC%D8%A7%D9%87%D9%84) لتضمين ملفات يتم تجاهلها عادة، أنشئ ملف `.ignore` في جذر المشروع. يمكن لهذا الملف السماح صراحة بمسارات محددة. !node_modules/!dist/!build/ على سبيل المثال، يسمح ملف `.ignore` هذا لـ ripgrep بالبحث داخل مجلدات `node_modules/` و`dist/` و`build/` حتى لو كانت مدرجة في `.gitignore`. --- # เครื่องมือ | OpenCode [Skip to content](https://opencode.ai/docs/th/tools#_top) เครื่องมือ ========== จัดการเครื่องมือที่ LLM สามารถใช้ได้ เครื่องมืออนุญาตให้ LLM ดำเนินการในโค้ดเบสของคุณ OpenCode มาพร้อมกับชุดเครื่องมือในตัว แต่คุณสามารถขยายได้ด้วย [เครื่องมือที่กำหนดเอง](https://opencode.ai/docs/custom-tools) หรือ [MCP เซิร์ฟเวอร์](https://opencode.ai/docs/mcp-servers) ตามค่าเริ่มต้น เครื่องมือทั้งหมด **เปิดใช้งาน** และไม่จำเป็นต้องมีสิทธิ์ในการทำงาน คุณสามารถควบคุมการทำงานของเครื่องมือผ่าน [สิทธิ์](https://opencode.ai/docs/permissions) * * * [กำหนดค่า](https://opencode.ai/docs/th/tools#%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2) ----------------------------------------------------------------------------------------------------------------------- ใช้ฟิลด์ `permission` เพื่อควบคุมการทำงานของเครื่องมือ คุณสามารถอนุญาต ปฏิเสธ หรือต้องการการอนุมัติสำหรับเครื่องมือแต่ละรายการได้ { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "deny", "bash": "ask", "webfetch": "allow" }} คุณยังสามารถใช้ไวด์การ์ดเพื่อควบคุมเครื่องมือหลายรายการพร้อมกันได้ ตัวอย่างเช่น หากต้องการขออนุมัติเครื่องมือทั้งหมดจากเซิร์ฟเวอร์ MCP: { "$schema": "https://opencode.ai/config.json", "permission": { "mymcp_*": "ask" }} [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/permissions) เกี่ยวกับการกำหนดค่าสิทธิ์ * * * [บิวท์อิน](https://opencode.ai/docs/th/tools#%E0%B8%9A%E0%B8%B4%E0%B8%A7%E0%B8%97%E0%B9%8C%E0%B8%AD%E0%B8%B4%E0%B8%99) ----------------------------------------------------------------------------------------------------------------------- นี่คือเครื่องมือในตัวทั้งหมดที่มีอยู่ใน OpenCode * * * ### [bash](https://opencode.ai/docs/th/tools#bash) ดำเนินการคำสั่ง shell ในสภาพแวดล้อมโปรเจ็กต์ของคุณ { "$schema": "https://opencode.ai/config.json", "permission": { "bash": "allow" }} เครื่องมือนี้อนุญาตให้ LLM รันคำสั่ง terminal เช่น `npm install`, `git status` หรือคำสั่ง shell อื่น ๆ * * * ### [edit](https://opencode.ai/docs/th/tools#edit) แก้ไขไฟล์ที่มีอยู่โดยใช้การแทนที่สตริงที่แน่นอน { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} เครื่องมือนี้ทำการแก้ไขไฟล์อย่างแม่นยำโดยแทนที่ข้อความที่ตรงกันทุกประการ มันเป็นวิธีหลักที่ LLM แก้ไขโค้ด * * * ### [write](https://opencode.ai/docs/th/tools#write) สร้างไฟล์ใหม่หรือเขียนทับไฟล์ที่มีอยู่ { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} ใช้สิ่งนี้เพื่ออนุญาตให้ LLM สร้างไฟล์ใหม่ มันจะเขียนทับไฟล์ที่มีอยู่หากมีอยู่แล้ว * * * ### [read](https://opencode.ai/docs/th/tools#read) อ่านเนื้อหาไฟล์จากโค้ดเบสของคุณ { "$schema": "https://opencode.ai/config.json", "permission": { "read": "allow" }} เครื่องมือนี้จะอ่านไฟล์และส่งกลับเนื้อหา รองรับการอ่านช่วงบรรทัดเฉพาะสำหรับไฟล์ขนาดใหญ่ * * * ### [grep](https://opencode.ai/docs/th/tools#grep) ค้นหาเนื้อหาไฟล์โดยใช้นิพจน์ทั่วไป { "$schema": "https://opencode.ai/config.json", "permission": { "grep": "allow" }} ค้นหาเนื้อหาอย่างรวดเร็วทั่วทั้งโค้ดเบสของคุณ รองรับไวยากรณ์ regex เต็มรูปแบบและการกรองรูปแบบไฟล์ * * * ### [glob](https://opencode.ai/docs/th/tools#glob) ค้นหาไฟล์ตามรูปแบบการจับคู่ { "$schema": "https://opencode.ai/config.json", "permission": { "glob": "allow" }} ค้นหาไฟล์โดยใช้รูปแบบ glob เช่น `**/*.js` หรือ `src/**/*.ts` ส่งคืนเส้นทางไฟล์ที่ตรงกันโดยจัดเรียงตามเวลาแก้ไข * * * ### [list](https://opencode.ai/docs/th/tools#list) แสดงรายการไฟล์และไดเร็กทอรีในพาธที่กำหนด { "$schema": "https://opencode.ai/config.json", "permission": { "list": "allow" }} เครื่องมือนี้แสดงรายการเนื้อหาไดเร็กทอรี ยอมรับรูปแบบ glob เพื่อกรองผลลัพธ์ * * * ### [lsp (ขั้นทดลอง)](https://opencode.ai/docs/th/tools#lsp-%E0%B8%82%E0%B8%B1%E0%B9%89%E0%B8%99%E0%B8%97%E0%B8%94%E0%B8%A5%E0%B8%AD%E0%B8%87) โต้ตอบกับเซิร์ฟเวอร์ LSP ที่กำหนดค่าของคุณเพื่อรับฟีเจอร์อัจฉริยะด้านโค้ด เช่น คำจำกัดความ การอ้างอิง ข้อมูลโฮเวอร์ และลำดับชั้นการโทร { "$schema": "https://opencode.ai/config.json", "permission": { "lsp": "allow" }} การดำเนินการที่รองรับ ได้แก่ `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls` และ `outgoingCalls` หากต้องการกำหนดค่าเซิร์ฟเวอร์ LSP ที่พร้อมใช้งานสำหรับโครงการของคุณ โปรดดู [LSP เซิร์ฟเวอร์](https://opencode.ai/docs/lsp) * * * ### [patch](https://opencode.ai/docs/th/tools#patch) ใช้แพทช์กับไฟล์ { "$schema": "https://opencode.ai/config.json", "permission": { "edit": "allow" }} เครื่องมือนี้ใช้ไฟล์แพทช์กับโค้ดเบสของคุณ มีประโยชน์สำหรับการใช้ความแตกต่างและแพตช์จากแหล่งต่างๆ * * * ### [skill](https://opencode.ai/docs/th/tools#skill) โหลด [ทักษะ](https://opencode.ai/docs/skills) (ไฟล์ `SKILL.md`) และส่งคืนเนื้อหาในการสนทนา { "$schema": "https://opencode.ai/config.json", "permission": { "skill": "allow" }} * * * ### [todowrite](https://opencode.ai/docs/th/tools#todowrite) จัดการรายการสิ่งที่ต้องทำระหว่างเซสชันการเขียนโค้ด { "$schema": "https://opencode.ai/config.json", "permission": { "todowrite": "allow" }} สร้างและอัปเดตรายการงานเพื่อติดตามความคืบหน้าระหว่างการดำเนินการที่ซับซ้อน LLM ใช้สิ่งนี้เพื่อจัดระเบียบงานที่มีหลายขั้นตอน * * * ### [todoread](https://opencode.ai/docs/th/tools#todoread) อ่านรายการสิ่งที่ต้องทำที่มีอยู่ { "$schema": "https://opencode.ai/config.json", "permission": { "todoread": "allow" }} อ่านสถานะรายการสิ่งที่ต้องทำปัจจุบัน ใช้โดย LLM เพื่อติดตามงานที่กำลังรอดำเนินการหรือเสร็จสิ้น * * * ### [webfetch](https://opencode.ai/docs/th/tools#webfetch) ดึงเนื้อหาเว็บ { "$schema": "https://opencode.ai/config.json", "permission": { "webfetch": "allow" }} อนุญาตให้ LLM ดึงข้อมูลและอ่านหน้าเว็บ มีประโยชน์สำหรับการค้นหาเอกสารหรือค้นคว้าแหล่งข้อมูลออนไลน์ * * * ### [websearch](https://opencode.ai/docs/th/tools#websearch) ค้นหาข้อมูลในเว็บ { "$schema": "https://opencode.ai/config.json", "permission": { "websearch": "allow" }} ทำการค้นหาเว็บโดยใช้ Exa AI เพื่อค้นหาข้อมูลที่เกี่ยวข้องทางออนไลน์ มีประโยชน์สำหรับการค้นคว้าหัวข้อ ค้นหาเหตุการณ์ปัจจุบัน หรือการรวบรวมข้อมูลนอกเหนือจากการตัดข้อมูลการฝึกอบรม ไม่จำเป็นต้องใช้คีย์ API เครื่องมือนี้เชื่อมต่อโดยตรงกับบริการ MCP ที่โฮสต์ของ Exa AI โดยไม่มีการตรวจสอบสิทธิ์ * * * ### [question](https://opencode.ai/docs/th/tools#question) ถามคำถามผู้ใช้ระหว่างการดำเนินการ { "$schema": "https://opencode.ai/config.json", "permission": { "question": "allow" }} เครื่องมือนี้อนุญาตให้ LLM ถามคำถามผู้ใช้ระหว่างทำงาน มันมีประโยชน์สำหรับ: * การรวบรวมความชอบหรือความต้องการของผู้ใช้ * ชี้แจงคำแนะนำที่ไม่ชัดเจน * การตัดสินใจเกี่ยวกับทางเลือกในการดำเนินการ * เสนอทางเลือกว่าจะไปในทิศทางใด คำถามแต่ละข้อประกอบด้วยส่วนหัว ข้อความคำถาม และรายการตัวเลือก ผู้ใช้สามารถเลือกจากตัวเลือกที่มีให้หรือพิมพ์คำตอบที่กำหนดเองได้ เมื่อมีคำถามหลายข้อ ผู้ใช้สามารถสลับไปมาระหว่างคำถามเหล่านั้นก่อนที่จะส่งคำตอบทั้งหมด * * * [เครื่องมือที่กำหนดเอง](https://opencode.ai/docs/th/tools#%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เครื่องมือแบบกำหนดเองช่วยให้คุณสามารถกำหนดฟังก์ชันของคุณเองที่ LLM สามารถเรียกได้ สิ่งเหล่านี้ถูกกำหนดไว้ในไฟล์ปรับแต่งของคุณและสามารถรันโค้ดได้ตามใจชอบ [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/custom-tools) เกี่ยวกับการสร้างเครื่องมือที่กำหนดเอง * * * [MCP เซิร์ฟเวอร์](https://opencode.ai/docs/th/tools#mcp-%E0%B9%80%E0%B8%8B%E0%B8%B4%E0%B8%A3%E0%B9%8C%E0%B8%9F%E0%B9%80%E0%B8%A7%E0%B8%AD%E0%B8%A3%E0%B9%8C) ------------------------------------------------------------------------------------------------------------------------------------------------------------- เซิร์ฟเวอร์ MCP (Model Context Protocol) ช่วยให้คุณสามารถรวมเครื่องมือและบริการภายนอกได้ ซึ่งรวมถึงการเข้าถึงฐานข้อมูล การบูรณาการ API และบริการของบุคคลที่สาม [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/mcp-servers) เกี่ยวกับการกำหนดค่าเซิร์ฟเวอร์ MCP * * * [ภายใน](https://opencode.ai/docs/th/tools#%E0%B8%A0%E0%B8%B2%E0%B8%A2%E0%B9%83%E0%B8%99) ----------------------------------------------------------------------------------------- ภายใน เครื่องมือต่างๆ เช่น `grep`, `glob` และ `list` ใช้ [ripgrep](https://github.com/BurntSushi/ripgrep) ภายใต้ประทุน ตามค่าเริ่มต้น ripgrep เคารพรูปแบบ `.gitignore` ซึ่งหมายความว่าไฟล์และไดเร็กทอรีที่อยู่ใน `.gitignore` ของคุณจะถูกแยกออกจากการค้นหาและรายการ * * * ### [ละเว้นรูปแบบ](https://opencode.ai/docs/th/tools#%E0%B8%A5%E0%B8%B0%E0%B9%80%E0%B8%A7%E0%B9%89%E0%B8%99%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B9%81%E0%B8%9A%E0%B8%9A) หากต้องการรวมไฟล์ที่ปกติจะถูกละเว้น ให้สร้างไฟล์ `.ignore` ในรูทโปรเจ็กต์ของคุณ ไฟล์นี้สามารถอนุญาตเส้นทางบางอย่างได้อย่างชัดเจน !node_modules/!dist/!build/ ตัวอย่างเช่น ไฟล์ `.ignore` นี้อนุญาตให้ ripgrep ค้นหาภายในไดเร็กทอรี `node_modules/`, `dist/` และ `build/` แม้ว่าไดเร็กทอรีเหล่านั้นจะแสดงอยู่ใน `.gitignore` ก็ตาม ---