# Table of Contents - [Intro | AI coding agent built for the terminal](#intro-ai-coding-agent-built-for-the-terminal) - [Ecosystem | OpenCode](#ecosystem-opencode) - [Agent Skills | OpenCode](#agent-skills-opencode) - [References | OpenCode](#references-opencode) - [LSP Servers | OpenCode](#lsp-servers-opencode) - [ACP Support | OpenCode](#acp-support-opencode) - [Ökosystem | OpenCode](#-kosystem-opencode) - [Ecosistema | OpenCode](#ecosistema-opencode) - [生態系統 | OpenCode](#-opencode) - [النظام البيئي | OpenCode](#-opencode) - [Competenze dell'agente | OpenCode](#competenze-dell-agente-opencode) - [Agenten-Skills | OpenCode](#agenten-skills-opencode) - [Supporto ACP | OpenCode](#supporto-acp-opencode) - [ACP-Unterstützung | OpenCode](#acp-unterst-tzung-opencode) - [References | OpenCode](#references-opencode) - [การรองรับ ACP | OpenCode](#-acp-opencode) - [ACP 支援 | OpenCode](#acp-opencode) - [Поддержка ACP | OpenCode](#-acp-opencode) - [LSP Server | OpenCode](#lsp-server-opencode) - [Server LSP | OpenCode](#server-lsp-opencode) - [Support ACP | OpenCode](#support-acp-opencode) - [Serveurs LSP | OpenCode](#serveurs-lsp-opencode) - [LSP-servere | OpenCode](#lsp-servere-opencode) - [LSP Sunucuları | OpenCode](#lsp-sunucular-opencode) - [İzinler | OpenCode](#i-zinler-opencode) - [LSP-серверы | OpenCode](#lsp-opencode) - [LSP เซิร์ฟเวอร์ | OpenCode](#lsp-opencode) - [الأدوات المخصصة | OpenCode](#-opencode) - [الإضافات | OpenCode](#-opencode) - [สิทธิ์ | OpenCode](#-opencode) - [Темы | OpenCode](#-opencode) - [Themes | OpenCode](#themes-opencode) - [Temi | OpenCode](#temi-opencode) - [ธีมส์ | OpenCode](#-opencode) - [外掛 | OpenCode](#-opencode) - [Plugins | OpenCode](#plugins-opencode) - [Eklentiler | OpenCode](#eklentiler-opencode) - [ปลั๊กอิน | OpenCode](#-opencode) - [Complementos | OpenCode](#complementos-opencode) - [Wtyczki | OpenCode](#wtyczki-opencode) - [Плагины | OpenCode](#-opencode) - [السمات | OpenCode](#-opencode) - [Ecossistema | OpenCode](#ecossistema-opencode) - [Themes | OpenCode](#themes-opencode) - [テーマ | OpenCode](#-opencode) - [Écosystème | OpenCode](#-cosyst-me-opencode) - [Ekosistem | OpenCode](#ekosistem-opencode) - [Server MCP | OpenCode](#server-mcp-opencode) - [GitHub | OpenCode](#github-opencode) - [GitHub | OpenCode](#github-opencode) - [GitHub | OpenCode](#github-opencode) - [GitHub | OpenCode](#github-opencode) - [GitHub | OpenCode](#github-opencode) - [MCP-servere | OpenCode](#mcp-servere-opencode) - [Serwery MCP | OpenCode](#serwery-mcp-opencode) - [Ekosystem | OpenCode](#ekosystem-opencode) - [MCP 伺服器 | OpenCode](#mcp-opencode) - [GitHub | OpenCode](#github-opencode) - [主題 | OpenCode](#-opencode) - [Thèmes | OpenCode](#th-mes-opencode) - [Temalar | OpenCode](#temalar-opencode) - [Temas | OpenCode](#temas-opencode) - [Soporte ACP | OpenCode](#soporte-acp-opencode) - [Serveurs MCP | OpenCode](#serveurs-mcp-opencode) - [MCP เซิร์ฟเวอร์ | OpenCode](#mcp-opencode) - [Regler | OpenCode](#regler-opencode) - [Regeln | OpenCode](#regeln-opencode) - [Zasady | OpenCode](#zasady-opencode) - [규칙 | OpenCode](#-opencode) - [Reglas | OpenCode](#reglas-opencode) - [Temaer | OpenCode](#temaer-opencode) - [LSP-servere | OpenCode](#lsp-servere-opencode) - [ACP サポート | OpenCode](#acp-opencode) - [ACP Support | OpenCode](#acp-support-opencode) - [Serwery LSP | OpenCode](#serwery-lsp-opencode) - [LSP 服务器 | OpenCode](#lsp-opencode) - [MCP-серверы | OpenCode](#mcp-opencode) - [Правила | OpenCode](#-opencode) - [Servidores LSP | OpenCode](#servidores-lsp-opencode) - [القواعد | OpenCode](#-opencode) - [Regole | OpenCode](#regole-opencode) - [ルール | OpenCode](#-opencode) - [กฎ | OpenCode](#-opencode) - [Brugerdefinerede værktøjer | OpenCode](#brugerdefinerede-v-rkt-jer-opencode) - [테마 | OpenCode](#-opencode) - [Temaer | OpenCode](#temaer-opencode) - [Modeller | OpenCode](#modeller-opencode) - [Modelle | OpenCode](#modelle-opencode) - [모델 | OpenCode](#-opencode) - [Modelli | OpenCode](#modelli-opencode) - [Modelos | OpenCode](#modelos-opencode) - [Modeller | OpenCode](#modeller-opencode) - [Modelos | OpenCode](#modelos-opencode) - [Modeller | OpenCode](#modeller-opencode) - [モデル | OpenCode](#-opencode) - [โมเดล | OpenCode](#-opencode) - [Модели | OpenCode](#-opencode) - [主题 | OpenCode](#-opencode) - [Modele | OpenCode](#modele-opencode) - [模型 | OpenCode](#-opencode) - [النماذج | OpenCode](#-opencode) - [プラグイン | OpenCode](#-opencode) - [GitHub | OpenCode](#github-opencode) - [MCP 服务器 | OpenCode](#mcp-opencode) - [规则 | OpenCode](#-opencode) - [Umiejętności Agenta | OpenCode](#umiej-tno-ci-agenta-opencode) - [Agentfærdigheder | OpenCode](#agentf-rdigheder-opencode) - [Habilidades del agente | OpenCode](#habilidades-del-agente-opencode) - [에이전트 스킬 | OpenCode](#-opencode) - [ACP | OpenCode](#acp-opencode) - [ACP 支持 | OpenCode](#acp-opencode) - [ACP-understøttelse | OpenCode](#acp-underst-ttelse-opencode) - [エージェントスキル | OpenCode](#-opencode) - [References | OpenCode](#references-opencode) - [References | OpenCode](#references-opencode) - [代理技能 | OpenCode](#-opencode) - [References | OpenCode](#references-opencode) - [References | OpenCode](#references-opencode) - [自訂工具 | OpenCode](#-opencode) - [Özel Araçlar | OpenCode](#-zel-ara-lar-opencode) - [References | OpenCode](#references-opencode) - [Plugins | OpenCode](#plugins-opencode) - [Ferramentas Personalizadas | OpenCode](#ferramentas-personalizadas-opencode) - [Custom Tools | OpenCode](#custom-tools-opencode) - [自定义工具 | OpenCode](#-opencode) - [Outils personnalisés | OpenCode](#outils-personnalis-s-opencode) --- # Intro | AI coding agent built for the terminal [Skip to content](https://opencode.ai/docs/#_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/#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/#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/#tab-panel-0) * [Bun](https://opencode.ai/docs/#tab-panel-1) * [pnpm](https://opencode.ai/docs/#tab-panel-2) * [Yarn](https://opencode.ai/docs/#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/#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/#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/#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/#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/#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/#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/#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/#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/#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) . --- # Ecosystem | OpenCode [Skip to content](https://opencode.ai/docs/ecosystem/#_top) Ecosystem ========= Projects and integrations built with OpenCode. A collection of community projects built on OpenCode. You can also check out [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) and [opencode.cafe](https://opencode.cafe/) , a community that aggregates the ecosystem and community. * * * [Plugins](https://opencode.ai/docs/ecosystem/#plugins) ------------------------------------------------------- | Name | Description | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | Automatically run OpenCode sessions in isolated Daytona sandboxes with git sync and live previews | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Automatically inject Helicone session headers for request grouping | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Auto-inject TypeScript/Svelte types into file reads with lookup tools | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Use your ChatGPT Plus/Pro subscription instead of API credits | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Use your existing Gemini plan instead of API billing | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Use Antigravity’s free models instead of API billing | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Multi-branch devcontainer isolation with shallow clones and auto-assigned ports | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth Plugin, with support for Google Search, and more robust API handling | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimize token usage by pruning obsolete tool outputs | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | Redact secrets/PII into VibeGuard-style placeholders before LLM calls; restore locally | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Add native websearch support for supported providers with Google grounded style | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Enables AI agents to run background processes in a PTY, send interactive input to them. | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Instructions for non-interactive shell commands - prevents hangs from TTY-dependent operations | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Track OpenCode usage with Wakatime | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Clean up markdown tables produced by LLMs | | [opencode-morph-fast-apply](https://github.com/JRedeker/opencode-morph-fast-apply) | 10x faster code editing with Morph Fast Apply API and lazy edit markers | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | Fast Apply editing, WarpGrep codebase search, and context compaction via Morph | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Background agents, pre-built LSP/AST/MCP tools, curated agents, Claude Code compatible | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | Desktop notifications and sound alerts for OpenCode sessions | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Desktop notifications and sound alerts for permission, completion, and error events | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | AI-powered automatic Zellij session naming based on OpenCode context | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Allow OpenCode agents to lazy load prompts on demand with skill discovery and injection | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Persistent memory across sessions using Supermemory | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interactive plan review with visual annotation and private/offline sharing | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Extend opencode /commands into a powerful orchestration system with granular flow control | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Schedule recurring jobs using launchd (Mac) or systemd (Linux) with cron syntax | | [opencode-conductor](https://github.com/derekbar90/opencode-conductor) | Protocol-Driven Workflow: Automation of the Context -> Spec -> Plan -> Implement lifecycle. | | [micode](https://github.com/vtemian/micode) | Structured Brainstorm → Plan → Implement workflow with session continuity | | [octto](https://github.com/vtemian/octto) | Interactive browser UI for AI brainstorming with multi-question forms | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Claude Code-style background agents with async delegation and context persistence | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Native OS notifications for OpenCode – know when tasks complete | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Bundled multi-agent orchestration harness – 16 components, one install | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Zero-friction git worktrees for OpenCode | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | Trace and debug your AI agents with Sentry AI Monitoring | | [opencode-firecrawl](https://github.com/firecrawl/opencode-firecrawl) | Web scraping, crawling, and search via the Firecrawl CLI | | [opencode-jfrog-plugin](https://github.com/jfrog/opencode-jfrog-plugin) | JFrog Plugin for seamless integration of Opencode users to JFrog platform | | [opencode-goal-plugin](https://github.com/willytop8/OpenCode-goal-plugin) | Session-scoped `/goal` workflow that keeps objectives in context and auto-continues until complete | * * * [Projects](https://opencode.ai/docs/ecosystem/#projects) --------------------------------------------------------- | Name | Description | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | Discord bot to control OpenCode sessions, built on the SDK | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim plugin for editor-aware prompts, built on the API | | [portal](https://github.com/hosenur/portal) | Mobile-first web UI for OpenCode over Tailscale/VPN | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Template for building OpenCode plugins | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim frontend for opencode - a terminal-based AI coding agent | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK provider for using OpenCode via @opencode-ai/sdk | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | Web / Desktop App and VS Code Extension for OpenCode | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian plugin that embeds OpenCode in Obsidian’s UI | | [OpenWork](https://github.com/different-ai/openwork) | An open-source alternative to Claude Cowork, powered by OpenCode | | [ocx](https://github.com/kdcokenny/ocx) | OpenCode extension manager with portable, isolated profiles. | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Desktop, Web, Mobile and Remote Client App for OpenCode | * * * [Agents](https://opencode.ai/docs/ecosystem/#agents) ----------------------------------------------------- | Name | Description | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | Modular AI agents and commands for structured development | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Configs, prompts, agents, and plugins for enhanced workflows | --- # Agent Skills | OpenCode [Skip to content](https://opencode.ai/docs/skills/#_top) Agent Skills ============ Define reusable behavior via SKILL.md definitions Agent skills let OpenCode discover reusable instructions from your repo or home directory. Skills are loaded on-demand via the native `skill` tool—agents see available skills and can load the full content when needed. * * * [Place files](https://opencode.ai/docs/skills/#place-files) ------------------------------------------------------------ Create one folder per skill name and put a `SKILL.md` inside it. OpenCode searches these locations: * Project config: `.opencode/skills//SKILL.md` * Global config: `~/.config/opencode/skills//SKILL.md` * Project Claude-compatible: `.claude/skills//SKILL.md` * Global Claude-compatible: `~/.claude/skills//SKILL.md` * Project agent-compatible: `.agents/skills//SKILL.md` * Global agent-compatible: `~/.agents/skills//SKILL.md` * * * [Understand discovery](https://opencode.ai/docs/skills/#understand-discovery) ------------------------------------------------------------------------------ For project-local paths, OpenCode walks up from your current working directory until it reaches the git worktree. It loads any matching `skills/*/SKILL.md` in `.opencode/` and any matching `.claude/skills/*/SKILL.md` or `.agents/skills/*/SKILL.md` along the way. Global definitions are also loaded from `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md`, and `~/.agents/skills/*/SKILL.md`. * * * [Write frontmatter](https://opencode.ai/docs/skills/#write-frontmatter) ------------------------------------------------------------------------ Each `SKILL.md` must start with YAML frontmatter. Only these fields are recognized: * `name` (required) * `description` (required) * `license` (optional) * `compatibility` (optional) * `metadata` (optional, string-to-string map) Unknown frontmatter fields are ignored. * * * [Validate names](https://opencode.ai/docs/skills/#validate-names) ------------------------------------------------------------------ `name` must: * Be 1–64 characters * Be lowercase alphanumeric with single hyphen separators * Not start or end with `-` * Not contain consecutive `--` * Match the directory name that contains `SKILL.md` Equivalent regex: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [Follow length rules](https://opencode.ai/docs/skills/#follow-length-rules) ---------------------------------------------------------------------------- `description` must be 1-1024 characters. Keep it specific enough for the agent to choose correctly. * * * [Use an example](https://opencode.ai/docs/skills/#use-an-example) ------------------------------------------------------------------ Create `.opencode/skills/git-release/SKILL.md` like this: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [Recognize tool description](https://opencode.ai/docs/skills/#recognize-tool-description) ------------------------------------------------------------------------------------------ OpenCode lists available skills in the `skill` tool description. Each entry includes the skill name and description: git-release Create consistent releases and changelogs The agent loads a skill by calling the tool: skill({ name: "git-release" }) * * * [Configure permissions](https://opencode.ai/docs/skills/#configure-permissions) -------------------------------------------------------------------------------- Control which skills agents can access using pattern-based permissions in `opencode.json`: { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | Permission | Behavior | | --- | --- | | `allow` | Skill loads immediately | | `deny` | Skill hidden from agent, access rejected | | `ask` | User prompted for approval before loading | Patterns support wildcards: `internal-*` matches `internal-docs`, `internal-tools`, etc. * * * [Override per agent](https://opencode.ai/docs/skills/#override-per-agent) -------------------------------------------------------------------------- Give specific agents different permissions than the global defaults. **For custom agents** (in agent frontmatter): ---permission: skill: "documents-*": "allow"--- **For built-in agents** (in `opencode.json`): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [Disable the skill tool](https://opencode.ai/docs/skills/#disable-the-skill-tool) ---------------------------------------------------------------------------------- Completely disable skills for agents that shouldn’t use them: **For custom agents**: ---tools: skill: false--- **For built-in agents**: { "agent": { "plan": { "tools": { "skill": false } } }} When disabled, the `` section is omitted entirely. * * * [Troubleshoot loading](https://opencode.ai/docs/skills/#troubleshoot-loading) ------------------------------------------------------------------------------ If a skill does not show up: 1. Verify `SKILL.md` is spelled in all caps 2. Check that frontmatter includes `name` and `description` 3. Ensure skill names are unique across all locations 4. Check permissions—skills with `deny` are hidden from agents --- # References | OpenCode [Skip to content](https://opencode.ai/docs/references/#_top) References ========== Add local directories and Git repositories as project references. References give OpenCode access to directories outside the current project. Use them to make documentation, shared libraries, examples, or another repository available while you work. References are configured by alias in `opencode.json` or `opencode.jsonc`. { "$schema": "https://opencode.ai/config.json", "references": { "docs": { "path": "../product-docs", "description": "Use for product behavior and documentation conventions", }, "sdk": { "repository": "anomalyco/opencode-sdk-js", "branch": "main", "description": "Use for JavaScript SDK implementation details", }, },} * * * [Local directories](https://opencode.ai/docs/references/#local-directories) ---------------------------------------------------------------------------- Use `path` to reference a local directory. { "references": { "docs": { "path": "../docs", }, },} Paths can be: * Relative to the config file that defines the reference * Absolute, such as `/home/user/docs` * Relative to your home directory, such as `~/docs` You can also use a string shorthand: { "references": { "docs": "../docs", },} * * * [Git repositories](https://opencode.ai/docs/references/#git-repositories) -------------------------------------------------------------------------- Use `repository` to reference a Git repository. OpenCode materializes the repository in its local repository cache and makes the checked-out source available as a reference directory. { "references": { "effect": { "repository": "Effect-TS/effect", "branch": "main", }, },} `repository` accepts Git URLs, host/path references, and GitHub `owner/repo` shorthand. The optional `branch` field selects a branch or ref. Without `branch`, OpenCode uses the repository’s default branch. You can use string shorthand when you do not need a branch, description, or other options: { "references": { "effect": "Effect-TS/effect", },} * * * [Describe usage](https://opencode.ai/docs/references/#describe-usage) ---------------------------------------------------------------------- Add `description` to explain when an agent should use a reference. { "references": { "design-system": { "path": "../design-system", "description": "Use when implementing UI components or design tokens", }, },} OpenCode includes references with descriptions in agent context. Descriptions should be short and specific enough to distinguish references with similar content. References without descriptions remain available through autocomplete and direct use, but are not advertised to agents. * * * [Hide autocomplete entries](https://opencode.ai/docs/references/#hide-autocomplete-entries) -------------------------------------------------------------------------------------------- Set `hidden` to `true` to omit a reference from `@` autocomplete in the TUI. { "references": { "internal": { "path": "../internal", "description": "Use for internal implementation details", "hidden": true, }, },} `hidden` only affects autocomplete. A hidden reference with a description remains included in agent context. * * * [Use references](https://opencode.ai/docs/references/#use-references) ---------------------------------------------------------------------- Configured references appear in TUI `@` autocomplete. Type `@alias` to attach the reference root, or `@alias/` to search for files inside it. Compare this implementation with @sdk/src/client.ts Agents also receive the resolved paths and descriptions of configured references that have descriptions in their system context, so they can inspect a reference when it is relevant without you attaching it manually. OpenCode automatically allows reference directories through its external-directory permission boundary. Normal tool permissions still apply; for example, an agent that cannot edit files does not gain edit access because a directory is configured as a reference. * * * [Configure fields](https://opencode.ai/docs/references/#configure-fields) -------------------------------------------------------------------------- | Field | Local | Git | Description | | --- | --- | --- | --- | | `path` | Yes | No | Local reference directory | | `repository` | No | Yes | Git URL, host/path, or GitHub `owner/repo` value | | `branch` | No | Yes | Optional Git branch or ref | | `description` | Yes | Yes | Guidance describing when to use the reference | | `hidden` | Yes | Yes | Hide the reference from TUI `@` autocomplete | Reference aliases cannot be empty or contain `/`, whitespace, backticks, or commas. --- # LSP Servers | OpenCode [Skip to content](https://opencode.ai/docs/lsp/#_top) LSP Servers =========== OpenCode integrates with your LSP servers. OpenCode can integrate with Language Server Protocol (LSP) servers to use diagnostics as feedback for the agent. * * * [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, .csx | `.NET SDK` installed | | clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` command available | | dart | .dart | `dart` command available | | deno | .ts, .tsx, .js, .jsx, .mjs | `deno` command available (auto-detects deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | `elixir` command available | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` dependency in project | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installed | | gleam | .gleam | `gleam` command available | | gopls | .go | `go` command available | | hls | .hs, .lhs | `haskell-language-server-wrapper` command available | | jdtls | .java | `Java SDK (version 21+)` installed | | julials | .jl | `julia` and `LanguageServer.jl` installed | | kotlin-ls | .kt, .kts | Auto-installs for Kotlin projects | | lua-ls | .lua | Auto-installs for Lua projects | | nixd | .nix | `nixd` command available | | ocaml-lsp | .ml, .mli | `ocamllsp` command available | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` dependency in project | | php intelephense | .php | Auto-installs for PHP projects | | prisma | .prisma | `prisma` command available | | pyright | .py, .pyi | `pyright` dependency installed | | razor | .razor, .cshtml | `.NET SDK` and VS Code C# extension installed | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | `ruby` and `gem` commands available | | rust | .rs | `rust-analyzer` command available | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` installed (`xcode` on macOS) | | svelte | .svelte | Auto-installs for Svelte projects | | terraform | .tf, .tfvars | Auto-installs from GitHub releases | | tinymist | .typ, .typc | Auto-installs from GitHub releases | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project | | vue | .vue | Auto-installs for Vue projects | | yaml-ls | .yaml, .yml | Auto-installs Red Hat yaml-language-server | | zls | .zig, .zon | `zig` command available | LSP is disabled by default. When enabled, servers start when one of the above file extensions is detected and the requirements are met. * * * [How It Works](https://opencode.ai/docs/lsp/#how-it-works) ----------------------------------------------------------- When LSP is enabled and opencode opens a file, it: 1. Checks the file extension against all enabled LSP servers. 2. Starts the appropriate LSP server if not already running. * * * [Best Practices](https://opencode.ai/docs/lsp/#best-practices) --------------------------------------------------------------- LSP can help the agent find and fix issues by providing diagnostics from language servers. This is useful in some projects, but it is not always a net positive. Language servers can get out of sync, use significant memory, vary by version or project, and slow down agent workflows. In many projects it is better to have the agent run lint, typecheck, or other diagnostic CLI tools directly, so errors are fed back into the agent loop without those tradeoffs. Document those commands in instruction files such as `AGENTS.md` or skills so the agent knows what to run. Enable LSP when your project benefits from additional language-server feedback. * * * [Configure](https://opencode.ai/docs/lsp/#configure) ----------------------------------------------------- You can enable and customize LSP servers through the `lsp` section in your opencode config. To enable all built-in LSP servers, set `lsp` to `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Use an object to keep built-ins enabled while configuring overrides or custom servers. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Each configured LSP server entry supports the following: Server entries need `command` unless they only disable a server. | Property | Type | Description | | --- | --- | --- | | `disabled` | boolean | Set this to `true` to disable the LSP server | | `command` | string\[\] | The command to start the LSP server | | `extensions` | string\[\] | File extensions this LSP server should handle | | `env` | object | Environment variables to set when starting server | | `initialization` | object | Initialization options to send to the LSP server | Let’s look at some examples. * * * ### [Environment variables](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": { "command": ["rust-analyzer"], "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": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"], "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Disabling LSP servers](https://opencode.ai/docs/lsp/#disabling-lsp-servers) If `lsp` is omitted, all LSP servers are disabled. To disable all LSP servers after another config enabled them, set `lsp` to `false`: { "$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. --- # ACP Support | OpenCode [Skip to content](https://opencode.ai/docs/acp/#_top) ACP Support =========== Use OpenCode in any ACP-compatible editor. OpenCode supports the [Agent Client Protocol](https://agentclientprotocol.com/) or (ACP), allowing you to use it directly in compatible editors and IDEs. ACP is an open protocol that standardizes communication between code editors and AI coding agents. * * * [Configure](https://opencode.ai/docs/acp/#configure) ----------------------------------------------------- To use OpenCode via ACP, configure your editor to run the `opencode acp` command. The command starts OpenCode as an ACP-compatible subprocess that communicates with your editor over JSON-RPC via stdio. Below are examples for popular editors that support ACP. * * * ### [Zed](https://opencode.ai/docs/acp/#zed) Add to your [Zed](https://zed.dev/) configuration (`~/.config/zed/settings.json`): { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} To open it, use the `agent: new thread` action in the **Command Palette**. You can also bind a keyboard shortcut by editing your `keymap.json`: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/acp/#jetbrains-ides) Add to your [JetBrains IDE](https://www.jetbrains.com/) acp.json according to the [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} To open it, use the new ‘OpenCode’ agent in the AI Chat agent selector. * * * ### [Avante.nvim](https://opencode.ai/docs/acp/#avantenvim) Add to your [Avante.nvim](https://github.com/yetone/avante.nvim) configuration: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} If you need to pass environment variables: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/acp/#codecompanionnvim) To use OpenCode as an ACP agent in [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) , add the following to your Neovim config: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) This config sets up CodeCompanion to use OpenCode as the ACP agent for chat. If you need to pass environment variables (like `OPENCODE_API_KEY`), refer to [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) in the CodeCompanion.nvim documentation for full details. [Support](https://opencode.ai/docs/acp/#support) ------------------------------------------------- OpenCode works the same via ACP as it does in the terminal. All features are supported: * Built-in tools (file operations, terminal commands, etc.) * Custom tools and slash commands * MCP servers configured in your OpenCode config * Project-specific rules from `AGENTS.md` * Custom formatters and linters * Agents and permissions system --- # Ökosystem | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/ecosystem/#_top) Ökosystem ========= Mit OpenCode erstellte Projekte und Integrationen. Eine Sammlung von Community-Projekten, die auf OpenCode basieren. Sie können sich auch [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) und [opencode.cafe](https://opencode.cafe/) ansehen, eine Community, die das Ökosystem und die Community zusammenfasst. * * * [Plugins](https://opencode.ai/docs/de/ecosystem/#plugins) ---------------------------------------------------------- | Name | Beschreibung | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | Führen Sie OpenCode-Sitzungen automatisch in isolierten Daytona-Sandboxes mit Git-Synchronisierung und Live-Vorschauen aus | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Helicone-Sitzungsheader für die Anforderungsgruppierung automatisch einfügen | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | TypeScript/Svelte-Typen mit Suchtools automatisch in Dateilesevorgänge einfügen | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Verwenden Sie Ihr ChatGPT Plus/Pro-Abonnement anstelle von API Credits | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Verwenden Sie Ihren bestehenden Gemini-Plan anstelle der API-Abrechnung | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Nutzen Sie die kostenlosen Modelle von Antigravity anstelle der API-Abrechnung | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Multi-Branch-Devcontainer-Isolierung mit flachen Klonen und automatisch zugewiesenen Ports | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth-Plugin mit Unterstützung für die Google-Suche und robustere API-Verarbeitung | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimieren Sie die Token-Nutzung, indem Sie veraltete Tool-Ausgaben bereinigen | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | Schwärzen Sie Geheimnisse/PII in VibeGuard-ähnliche Platzhalter vor LLM-Aufrufen; lokal wiederherstellen | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Fügen Sie native Websuchunterstützung für unterstützte Anbieter mit Google Grounded Style hinzu | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Ermöglicht AI-Agenten, Hintergrundprozesse in einem PTY auszuführen und ihnen interaktive Eingaben zu senden. | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Anweisungen für nicht interaktive Shell-Befehle – verhindert Abstürze bei TTY-abhängigen Vorgängen | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Verfolgen Sie die Nutzung von OpenCode mit Wakatime | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Von LLMs erstellte Abschriftentabellen bereinigen | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | Fast Apply-Bearbeitung, WarpGrep-Codesuche und Kontextkomprimierung über Morph | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Hintergrundagenten, vorgefertigte LSP/AST/MCP-Tools, kuratierte Agenten, Claude Code-kompatibel | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | Desktop-Benachrichtigungen und akustische Warnungen für OpenCode-Sitzungen | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Desktop-Benachrichtigungen und akustische Warnungen für Berechtigungs-, Abschluss- und Fehlerereignisse | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | AI-gestützte automatische Benennung von Zellij-Sitzungen basierend auf dem OpenCode-Kontext | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Ermöglichen Sie OpenCode-Agenten das verzögerte Laden von Eingabeaufforderungen bei Bedarf mit Skill-Erkennung und -Injektion | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Persistenter Speicher über Sitzungen hinweg mit Supermemory | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interaktive Planüberprüfung mit visueller Anmerkung und private/offline-Freigabe | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Erweitern Sie OpenCode /commands zu einem leistungsstarken Orchestrierungssystem mit granularer Flusskontrolle | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Planen Sie wiederkehrende Jobs mit launchd (Mac) oder systemd (Linux) mit Cron-Syntax | | [micode](https://github.com/vtemian/micode) | Strukturiertes Brainstorming → Planen → Workflow mit Sitzungskontinuität Implementierung | | [octto](https://github.com/vtemian/octto) | Interaktiver Browser UI für AI Brainstorming mit Formularen mit mehreren Fragen | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Hintergrundagenten im Claude Code-Stil mit asynchroner Delegation und Kontextpersistenz | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Native OS-Benachrichtigungen für OpenCode – wissen, wann Aufgaben erledigt sind | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Gebündelter Multi-Agent-Orchestrierungs-Harness – 16 Komponenten, eine Installation | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Reibungslose Git-Arbeitsbäume für OpenCode | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | Tracen und debuggen Sie Ihre AI-Agenten mit Sentry AI Monitoring | * * * [Projekte](https://opencode.ai/docs/de/ecosystem/#projekte) ------------------------------------------------------------ | Name | Beschreibung | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | Discord-Bot zur Steuerung von OpenCode-Sitzungen, basierend auf SDK | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim-Plugin für editorfähige Eingabeaufforderungen, basierend auf API | | [portal](https://github.com/hosenur/portal) | Mobile-First-Web UI für OpenCode über Tailscale/VPN | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Vorlage zum Erstellen von OpenCode-Plugins | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Neovim-Frontend für OpenCode – ein terminalbasierter AI-Coding-Agent | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK Anbieter für die Verwendung von OpenCode über @opencode-ai/sdk | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | Web-/Desktop-App und VS Code-Erweiterung für OpenCode | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Obsidian-Plugin, das OpenCode in Obsidians UI einbettet | | [OpenWork](https://github.com/different-ai/openwork) | Eine Open-Source-Alternative zu Claude Cowork, unterstützt von OpenCode | | [ocx](https://github.com/kdcokenny/ocx) | OpenCode Erweiterungsmanager mit portablen, isolierten Profilen. | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Desktop-, Web-, Mobil- und Remote-Client-App für OpenCode | * * * [Agenten](https://opencode.ai/docs/de/ecosystem/#agenten) ---------------------------------------------------------- | Name | Beschreibung | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | Modulare AI-Agenten und -Befehle für strukturierte Entwicklung | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Konfigurationen, Eingabeaufforderungen, Agenten und Plugins für verbesserte Arbeitsabläufe | --- # Ecosistema | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/ecosystem/#_top) Ecosistema ========== Progetti e integrazioni costruiti con OpenCode. Una raccolta di progetti della comunità costruiti su OpenCode. Puoi anche dare un’occhiata a [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) e [opencode.cafe](https://opencode.cafe/) , una comunità che aggrega ecosistema e community. * * * [Plugin](https://opencode.ai/docs/it/ecosystem/#plugin) -------------------------------------------------------- | Nome | Descrizione | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | Esegue automaticamente sessioni OpenCode in sandbox Daytona isolate con sync git e anteprime live | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Inietta automaticamente gli header di sessione Helicone per raggruppare le richieste | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Inietta automaticamente tipi TypeScript/Svelte nelle letture dei file con tool di lookup | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Usa il tuo abbonamento ChatGPT Plus/Pro invece dei crediti API | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Usa il tuo piano Gemini esistente invece della fatturazione API | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Usa i modelli gratuiti di Antigravity invece della fatturazione API | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Isolamento devcontainer multi-branch con shallow clone e porte assegnate automaticamente | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Plugin OAuth Google Antigravity, con supporto a Google Search e gestione API più robusta | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Ottimizza l’uso dei token eliminando output obsoleti degli strumenti | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | Oscura segreti/PII in placeholder stile VibeGuard prima delle chiamate LLM; ripristina localmente | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Aggiunge supporto websearch nativo per provider supportati con stile grounded di Google | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Permette agli agenti AI di eseguire processi in background in una PTY e inviare input interattivo | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Istruzioni per comandi shell non interattivi: evita blocchi dovuti a operazioni dipendenti da TTY | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Traccia l’uso di OpenCode con Wakatime | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Ripulisce le tabelle markdown prodotte dai LLM | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | Editing Fast Apply, ricerca codebase WarpGrep e compattazione del contesto tramite Morph | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agenti in background, tool LSP/AST/MCP predefiniti, agenti curati, compatibile con Claude Code | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | Notifiche desktop e avvisi sonori per le sessioni OpenCode | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Notifiche desktop e avvisi sonori per eventi di permesso, completamento ed errore | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Naming automatico delle sessioni Zellij basato sul contesto OpenCode | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Permette agli agenti OpenCode di caricare prompt al bisogno con discovery e injection di skill | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Memoria persistente tra sessioni usando Supermemory | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Revisione interattiva dei piani con annotazione visiva e condivisione privata/offline | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Estende opencode /commands in un sistema di orchestrazione con controllo di flusso granulare | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Pianifica job ricorrenti con launchd (Mac) o systemd (Linux) usando sintassi cron | | [micode](https://github.com/vtemian/micode) | Workflow strutturato Brainstorm → Plan → Implement con continuità di sessione | | [octto](https://github.com/vtemian/octto) | UI browser interattiva per brainstorming AI con moduli multi-domanda | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Agenti in background stile Claude Code con delega async e persistenza del contesto | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Notifiche native del sistema per OpenCode: sai quando i task finiscono | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Harness di orchestrazione multi-agente bundle: 16 componenti, una installazione | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Git worktree senza attriti per OpenCode | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | Traccia e debugga i tuoi agenti AI con Sentry AI Monitoring | * * * [Progetti](https://opencode.ai/docs/it/ecosystem/#progetti) ------------------------------------------------------------ | Nome | Descrizione | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | Bot Discord per controllare sessioni OpenCode, costruito sull’SDK | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Plugin Neovim per prompt consapevoli dell’editor, costruito sull’API | | [portal](https://github.com/hosenur/portal) | Web UI mobile-first per OpenCode su Tailscale/VPN | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Template per costruire plugin OpenCode | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim per opencode: un agente di coding AI per terminale | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Provider Vercel AI SDK per usare OpenCode tramite @opencode-ai/sdk | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | App Web/Desktop ed estensione VS Code per OpenCode | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Plugin Obsidian che integra OpenCode nella UI di Obsidian | | [OpenWork](https://github.com/different-ai/openwork) | Alternativa open source a Claude Cowork, alimentata da OpenCode | | [ocx](https://github.com/kdcokenny/ocx) | Gestore di estensioni OpenCode con profili portabili e isolati | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | App client Desktop, Web, Mobile e remota per OpenCode | * * * [Agenti](https://opencode.ai/docs/it/ecosystem/#agenti) -------------------------------------------------------- | Nome | Descrizione | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | Agenti AI modulari e comandi per uno sviluppo strutturato | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Config, prompt, agenti e plugin per workflow migliorati | --- # 生態系統 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/ecosystem/#_top) 生態系統 ==== 基於 OpenCode 建置的專案與整合。 基於 OpenCode 建置的社群專案合集。 您還可以查看 [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) 和 [opencode.cafe](https://opencode.cafe/) ,這是一個聚合生態系統與社群資源的社群。 * * * [外掛程式](https://opencode.ai/docs/zh-tw/ecosystem/#%E5%A4%96%E6%8E%9B%E7%A8%8B%E5%BC%8F) --------------------------------------------------------------------------------------- | 名稱 | 說明 | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | 在隔離的 Daytona 沙箱中自動執行 OpenCode 工作階段,支援 git 同步和即時預覽 | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | 自動注入 Helicone 工作階段標頭資訊,用於請求分組 | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | 透過搜尋工具自動將 TypeScript/Svelte 型別注入到檔案讀取中 | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | 使用您的 ChatGPT Plus/Pro 訂閱替代 API 額度 | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | 使用您現有的 Gemini 方案替代 API 計費 | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | 使用 Antigravity 的免費模型替代 API 計費 | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | 多分支開發容器隔離,支援淺層複製和自動分配連接埠 | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Antigravity OAuth 外掛程式,支援 Google 搜尋及更強健的 API 處理 | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | 透過修剪過時的工具輸出來最佳化 Token 使用 | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | 在呼叫 LLM 之前將秘密/PII 編輯為 VibeGuard 風格的預留位置;並在本地還原 | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | 為受支援的供應商新增原生網頁搜尋支援,採用 Google grounded 風格 | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | 使 AI 代理能夠在 PTY 中執行背景處理程序,並向其傳送互動式輸入 | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | 非互動式 shell 指令說明——防止依賴 TTY 的操作導致卡住 | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | 使用 Wakatime 追蹤 OpenCode 的使用情況 | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | 清理 LLM 生成的 Markdown 表格 | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | 透過 Morph 提供 Fast Apply 編輯、WarpGrep 程式碼搜尋和上下文壓縮 | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | 背景代理、預建置的 LSP/AST/MCP 工具、精選代理,相容 Claude Code | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | OpenCode 工作階段的桌面通知和聲音提醒 | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | 針對權限請求、任務完成和錯誤事件的桌面通知與聲音提醒 | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | 基於 OpenCode 上下文的 AI 驅動自動 Zellij 工作階段命名 | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | 允許 OpenCode 代理透過技能發現和注入按需延遲載入提示詞 | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | 使用 Supermemory 實現跨工作階段的持久記憶 | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | 支援視覺化標註和私有/離線分享的互動式計畫審查 | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | 將 OpenCode /commands 擴展為具有精細流程控制的強大編排系統 | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | 使用 cron 語法透過 launchd (Mac) 或 systemd (Linux) 排程週期性任務 | | [micode](https://github.com/vtemian/micode) | 結構化的腦力激盪 → 計畫 → 實作工作流程,支援工作階段連續性 | | [octto](https://github.com/vtemian/octto) | 用於 AI 腦力激盪的互動式瀏覽器 UI,支援多問題表單 | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Claude Code 風格的背景代理,支援非同步委派和上下文持久化 | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | OpenCode 的原生作業系統通知——隨時了解任務完成情況 | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | 捆綁式多代理編排套件——16 個元件,一次安裝 | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | OpenCode 的零摩擦 git worktree 管理 | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | 使用 Sentry AI Monitoring 追蹤與除錯您的 AI 代理 | * * * [專案](https://opencode.ai/docs/zh-tw/ecosystem/#%E5%B0%88%E6%A1%88) ------------------------------------------------------------------- | 名稱 | 說明 | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | 用於控制 OpenCode 工作階段的 Discord 機器人,基於 SDK 建置 | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Neovim 外掛程式,提供編輯器感知的提示詞,基於 API 建置 | | [portal](https://github.com/hosenur/portal) | 透過 Tailscale/VPN 使用的行動優先 OpenCode Web UI | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | 用於建置 OpenCode 外掛程式的範本 | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | OpenCode 的 Neovim 前端——基於終端機的 AI 編碼代理 | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Vercel AI SDK 供應商,用於透過 @opencode-ai/sdk 使用 OpenCode | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | OpenCode 的 Web / 桌面應用程式和 VS Code 擴充功能 | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | 將 OpenCode 嵌入 Obsidian UI 的 Obsidian 外掛程式 | | [OpenWork](https://github.com/different-ai/openwork) | Claude Cowork 的開源替代方案,由 OpenCode 驅動 | | [ocx](https://github.com/kdcokenny/ocx) | OpenCode 擴充功能管理器,支援可攜式的隔離設定 | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | OpenCode 的桌面、Web、行動和遠端用戶端應用程式 | * * * [代理](https://opencode.ai/docs/zh-tw/ecosystem/#%E4%BB%A3%E7%90%86) ------------------------------------------------------------------- | 名稱 | 說明 | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | 用於結構化開發的模組化 AI 代理和指令 | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | 用於增強工作流程的設定、提示詞、代理和外掛程式 | --- # النظام البيئي | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/ecosystem/#_top) النظام البيئي ============= مشاريع وتكاملات مبنية باستخدام OpenCode. مجموعة من مشاريع المجتمع المبنية على OpenCode. يمكنك أيضًا الاطلاع على [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) و [opencode.cafe](https://opencode.cafe/) ، وهو مجتمع يجمع النظام البيئي والمجتمع. * * * [الإضافات](https://opencode.ai/docs/ar/ecosystem/#%D8%A7%D9%84%D8%A5%D8%B6%D8%A7%D9%81%D8%A7%D8%AA) ---------------------------------------------------------------------------------------------------- | الاسم | الوصف | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | تشغيل جلسات OpenCode تلقائيًا في صناديق حماية Daytona معزولة مع مزامنة git ومعاينات حية | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | حقن ترويسات جلسة Helicone تلقائيًا لتجميع الطلبات | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | حقن أنواع TypeScript/Svelte تلقائيًا في عمليات قراءة الملفات باستخدام أدوات البحث | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | استخدام اشتراك ChatGPT Plus/Pro الخاص بك بدلاً من أرصدة API | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | استخدام خطة Gemini الحالية الخاصة بك بدلاً من فوترة API | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | استخدام نماذج Antigravity المجانية بدلاً من فوترة API | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | عزل devcontainer متعدد الفروع مع نسخ shallow ومنافذ معينة تلقائيًا | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | إضافة Google Antigravity OAuth، مع دعم بحث Google، ومعالجة API أكثر قوة | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | تحسين استخدام التوكنات عن طريق تقليم مخرجات الأدوات القديمة | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | تنقيح الأسرار/بيانات التعريف الشخصي (PII) إلى نصوص بديلة بأسلوب VibeGuard قبل استدعاءات LLM؛ واستعادتها محليًا | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | إضافة دعم بحث الويب الأصلي للموفرين المدعومين بأسلوب Google grounded | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | تمكين وكلاء الذكاء الاصطناعي من تشغيل عمليات الخلفية في PTY، وإرسال مدخلات تفاعلية إليها. | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | تعليمات لأوامر shell غير التفاعلية - تمنع التعليق الناتج عن العمليات المعتمدة على TTY | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | تتبع استخدام OpenCode باستخدام Wakatime | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | تنظيف جداول markdown التي تنتجها LLMs | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | تحرير Fast Apply وبحث WarpGrep في قاعدة الكود وضغط السياق عبر Morph | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | وكلاء الخلفية، وأدوات LSP/AST/MCP المعدة مسبقًا، ووكلاء مختارون، متوافق مع Claude Code | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | إشعارات سطح المكتب وتنبيهات صوتية لجلسات OpenCode | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | إشعارات سطح المكتب وتنبيهات صوتية لأحداث الإذن والاكتمال والخطأ | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | تسمية جلسات Zellij تلقائيًا بدعم الذكاء الاصطناعي بناءً على سياق OpenCode | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | السماح لوكلاء OpenCode بتحميل المطالبات (prompts) بشكل كسول عند الطلب مع اكتشاف المهارات وحقنها | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | ذاكرة مستمرة عبر الجلسات باستخدام Supermemory | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | مراجعة تفاعلية للخطة مع تعليقات توضيحية مرئية ومشاركة خاصة/بدون اتصال | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | توسيع opencode /commands إلى نظام تنسيق قوي مع تحكم دقيق في التدفق | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | جدولة الوظائف المتكررة باستخدام launchd (Mac) أو systemd (Linux) بصيغة cron | | [micode](https://github.com/vtemian/micode) | سير عمل منظم: عصف ذهني ← تخطيط ← تنفيذ مع استمرارية الجلسة | | [octto](https://github.com/vtemian/octto) | واجهة مستخدم تفاعلية للمتصفح للعصف الذهني بالذكاء الاصطناعي مع نماذج متعددة الأسئلة | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | وكلاء خلفية بأسلوب Claude Code مع تفويض غير متزامن واستمرارية السياق | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | إشعارات نظام التشغيل الأصلية لـ OpenCode – اعرف متى تكتمل المهام | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | حزمة تنسيق متعددة الوكلاء – 16 مكونًا، تثبيت واحد | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | أشجار عمل git (worktrees) خالية من الاحتكاك لـ OpenCode | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | تتبع وتصحيح أخطاء وكلاء الذكاء الاصطناعي باستخدام Sentry AI Monitoring | * * * [المشاريع](https://opencode.ai/docs/ar/ecosystem/#%D8%A7%D9%84%D9%85%D8%B4%D8%A7%D8%B1%D9%8A%D8%B9) ---------------------------------------------------------------------------------------------------- | الاسم | الوصف | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | بوت Discord للتحكم في جلسات OpenCode، مبني على SDK | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | إضافة Neovim للمطالبات المدركة للمحرر، مبنية على API | | [portal](https://github.com/hosenur/portal) | واجهة ويب مخصصة للجوال لـ OpenCode عبر Tailscale/VPN | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | قالب لبناء إضافات OpenCode | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | واجهة Neovim لـ opencode - وكيل برمجة بالذكاء الاصطناعي يعتمد على الطرفية | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | موفر Vercel AI SDK لاستخدام OpenCode عبر @opencode-ai/sdk | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | تطبيق ويب / سطح مكتب وامتداد VS Code لـ OpenCode | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | إضافة Obsidian تدمج OpenCode في واجهة مستخدم Obsidian | | [OpenWork](https://github.com/different-ai/openwork) | بديل مفتوح المصدر لـ Claude Cowork، مدعوم بواسطة OpenCode | | [ocx](https://github.com/kdcokenny/ocx) | مدير امتدادات OpenCode مع ملفات تعريف محمولة ومعزولة. | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | تطبيق عميل لسطح المكتب والويب والجوال وعن بعد لـ OpenCode | * * * [الوكلاء](https://opencode.ai/docs/ar/ecosystem/#%D8%A7%D9%84%D9%88%D9%83%D9%84%D8%A7%D8%A1) --------------------------------------------------------------------------------------------- | الاسم | الوصف | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | وكلاء ذكاء اصطناعي وأوامر معيارية للتطوير المنظم | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | تكوينات، ومطالبات، ووكلاء، وإضافات لسير عمل محسن | --- # Competenze dell'agente | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/skills/#_top) Competenze dell'agente ====================== Definisci comportamenti riutilizzabili tramite definizioni in SKILL.md Le skill degli agenti permettono a OpenCode di individuare istruzioni riutilizzabili dal tuo repo o dalla home directory. Le skill vengono caricate on-demand tramite lo strumento nativo `skill`: gli agenti vedono le skill disponibili e possono caricarne il contenuto completo quando serve. * * * [Posizione dei file](https://opencode.ai/docs/it/skills/#posizione-dei-file) ----------------------------------------------------------------------------- Crea una cartella per ogni nome di skill e metti un `SKILL.md` al suo interno. OpenCode cerca in queste posizioni: * Config di progetto: `.opencode/skills//SKILL.md` * Config globale: `~/.config/opencode/skills//SKILL.md` * Progetto compatibile con Claude: `.claude/skills//SKILL.md` * Globale compatibile con Claude: `~/.claude/skills//SKILL.md` * Progetto compatibile con agent: `.agents/skills//SKILL.md` * Globale compatibile con agent: `~/.agents/skills//SKILL.md` * * * [Discovery](https://opencode.ai/docs/it/skills/#discovery) ----------------------------------------------------------- Per i percorsi locali al progetto, OpenCode risale dalla directory di lavoro corrente finche’ non raggiunge il worktree git. Carica qualsiasi `skills/*/SKILL.md` corrispondente in `.opencode/` e qualsiasi `.claude/skills/*/SKILL.md` o `.agents/skills/*/SKILL.md` corrispondente lungo il percorso. Le definizioni globali vengono caricate anche da `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` e `~/.agents/skills/*/SKILL.md`. * * * [Frontmatter](https://opencode.ai/docs/it/skills/#frontmatter) --------------------------------------------------------------- Ogni `SKILL.md` deve iniziare con frontmatter YAML. Sono riconosciuti solo questi campi: * `name` (obbligatorio) * `description` (obbligatorio) * `license` (opzionale) * `compatibility` (opzionale) * `metadata` (opzionale, mappa stringa-a-stringa) I campi di frontmatter sconosciuti vengono ignorati. * * * [Validazione nomi](https://opencode.ai/docs/it/skills/#validazione-nomi) ------------------------------------------------------------------------- `name` deve: * Essere lungo 1-64 caratteri * Essere alfanumerico minuscolo con separatori `-` singoli * Non iniziare o finire con `-` * Non contenere `--` consecutivi * Corrispondere al nome della directory che contiene `SKILL.md` Regex equivalente: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [Regole di lunghezza](https://opencode.ai/docs/it/skills/#regole-di-lunghezza) ------------------------------------------------------------------------------- `description` deve essere lunga 1-1024 caratteri. Tieni la descrizione abbastanza specifica da permettere all’agente di scegliere correttamente. * * * [Esempio](https://opencode.ai/docs/it/skills/#esempio) ------------------------------------------------------- Crea `.opencode/skills/git-release/SKILL.md` cosi’: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [Descrizione strumento](https://opencode.ai/docs/it/skills/#descrizione-strumento) ----------------------------------------------------------------------------------- OpenCode elenca le skill disponibili nella descrizione dello strumento `skill`. Ogni voce include il nome della skill e la descrizione: git-release Create consistent releases and changelogs L’agente carica una skill chiamando lo strumento: skill({ name: "git-release" }) * * * [Permessi](https://opencode.ai/docs/it/skills/#permessi) --------------------------------------------------------- Controlla a quali skill gli agenti possono accedere usando permessi basati su pattern in `opencode.json`: { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | Permesso | Comportamento | | --- | --- | | `allow` | La skill viene caricata immediatamente | | `deny` | Skill nascosta all’agente, accesso negato | | `ask` | L’utente viene invitato ad approvare il load | I pattern supportano wildcard: `internal-*` corrisponde a `internal-docs`, `internal-tools`, ecc. * * * [Sovrascrittura per agente](https://opencode.ai/docs/it/skills/#sovrascrittura-per-agente) ------------------------------------------------------------------------------------------- Dai ad agenti specifici permessi diversi dai default globali. **Per agenti personalizzati** (nel frontmatter dell’agente): ---permission: skill: "documents-*": "allow"--- **Per agenti integrati** (in `opencode.json`): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [Disabilitare skill](https://opencode.ai/docs/it/skills/#disabilitare-skill) ----------------------------------------------------------------------------- Disabilita completamente le skill per agenti che non dovrebbero usarle: **Per agenti personalizzati**: ---tools: skill: false--- **Per agenti integrati**: { "agent": { "plan": { "tools": { "skill": false } } }} Quando e’ disabilitato, la sezione `` viene omessa completamente. * * * [Risoluzione problemi](https://opencode.ai/docs/it/skills/#risoluzione-problemi) --------------------------------------------------------------------------------- Se una skill non compare: 1. Verifica che `SKILL.md` sia scritto in maiuscolo 2. Controlla che il frontmatter includa `name` e `description` 3. Assicurati che i nomi delle skill siano unici in tutte le posizioni 4. Controlla i permessi: le skill con `deny` vengono nascoste agli agenti --- # Agenten-Skills | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/skills/#_top) Agenten-Skills ============== Definiere wiederverwendbares Verhalten ueber SKILL.md Agent Skills erlauben OpenCode, wiederverwendbare Anweisungen aus deinem Repo oder Home-Verzeichnis zu finden. Sie werden bei Bedarf ueber das native `skill`\-Tool geladen, wenn ein Agent sie wirklich braucht. * * * [Dateien platzieren](https://opencode.ai/docs/de/skills/#dateien-platzieren) ----------------------------------------------------------------------------- Erstelle pro Skill-Namen einen Ordner und lege dort eine `SKILL.md` ab. OpenCode sucht in folgenden Pfaden: * Project config: `.opencode/skills//SKILL.md` * Global config: `~/.config/opencode/skills//SKILL.md` * Project Claude-compatible: `.claude/skills//SKILL.md` * Global Claude-compatible: `~/.claude/skills//SKILL.md` * Project agent-compatible: `.agents/skills//SKILL.md` * Global agent-compatible: `~/.agents/skills//SKILL.md` * * * [Discovery verstehen](https://opencode.ai/docs/de/skills/#discovery-verstehen) ------------------------------------------------------------------------------- Bei projektlokalen Pfaden laeuft OpenCode vom aktuellen Verzeichnis nach oben bis zum Git-Worktree. Dabei werden passende `skills/*/SKILL.md` in `.opencode/` sowie passende Dateien unter `.claude/skills/*/SKILL.md` und `.agents/skills/*/SKILL.md` geladen. Globale Definitionen kommen zusaetzlich aus `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` und `~/.agents/skills/*/SKILL.md`. * * * [Frontmatter schreiben](https://opencode.ai/docs/de/skills/#frontmatter-schreiben) ----------------------------------------------------------------------------------- Jede `SKILL.md` muss mit YAML-Frontmatter beginnen. Nur diese Felder werden ausgewertet: * `name` (erforderlich) * `description` (erforderlich) * `license` (optional) * `compatibility` (optional) * `metadata` (optional, String-zu-String-Map) Unbekannte Frontmatter-Felder werden ignoriert. * * * [Namen validieren](https://opencode.ai/docs/de/skills/#namen-validieren) ------------------------------------------------------------------------- `name` muss: * 1-64 Zeichen lang sein * nur Kleinbuchstaben und Ziffern mit einzelnen Bindestrichen enthalten * nicht mit `-` beginnen oder enden * kein `--` enthalten * zum Verzeichnisnamen passen, in dem `SKILL.md` liegt Entsprechender Regex: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [Längenregeln beachten](https://opencode.ai/docs/de/skills/#l%C3%A4ngenregeln-beachten) ---------------------------------------------------------------------------------------- `description` muss 1-1024 Zeichen lang sein. Formuliere sie so konkret, dass Agenten den Skill eindeutig auswaehlen koennen. * * * [Beispiel verwenden](https://opencode.ai/docs/de/skills/#beispiel-verwenden) ----------------------------------------------------------------------------- Erstelle `.opencode/skills/git-release/SKILL.md` zum Beispiel so: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [Tool-Beschreibung erkennen](https://opencode.ai/docs/de/skills/#tool-beschreibung-erkennen) --------------------------------------------------------------------------------------------- OpenCode listet verfuegbare Skills in der Beschreibung des `skill`\-Tools. Jeder Eintrag enthaelt Namen und Beschreibung: git-release Create consistent releases and changelogs Der Agent laedt einen Skill per Tool-Aufruf: skill({ name: "git-release" }) * * * [Berechtigungen konfigurieren](https://opencode.ai/docs/de/skills/#berechtigungen-konfigurieren) ------------------------------------------------------------------------------------------------- Steuere in `opencode.json` per Muster, auf welche Skills Agenten zugreifen duerfen: { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | Berechtigung | Verhalten | | --- | --- | | `allow` | Skill wird sofort geladen | | `deny` | Skill ist fuer Agenten versteckt | | `ask` | Vor dem Laden wird nach Freigabe gefragt | Muster unterstuetzen Wildcards: `internal-*` passt z. B. auf `internal-docs` oder `internal-tools`. * * * [Pro Agent überschreiben](https://opencode.ai/docs/de/skills/#pro-agent-%C3%BCberschreiben) -------------------------------------------------------------------------------------------- Du kannst einzelnen Agenten andere Berechtigungen als die globalen Defaults geben. **Fuer benutzerdefinierte Agenten** (im Frontmatter): ---permission: skill: "documents-*": "allow"--- **Fuer eingebaute Agenten** (in `opencode.json`): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [Skill-Tool deaktivieren](https://opencode.ai/docs/de/skills/#skill-tool-deaktivieren) --------------------------------------------------------------------------------------- Deaktiviere Skills komplett fuer Agenten, die sie nicht nutzen sollen: **Fuer benutzerdefinierte Agenten**: ---tools: skill: false--- **Fuer eingebaute Agenten**: { "agent": { "plan": { "tools": { "skill": false } } }} Wenn deaktiviert, wird der Abschnitt `` komplett weggelassen. * * * [Fehlerbehebung beim Laden](https://opencode.ai/docs/de/skills/#fehlerbehebung-beim-laden) ------------------------------------------------------------------------------------------- Wenn ein Skill nicht auftaucht: 1. Pruefe, ob `SKILL.md` exakt in Grossbuchstaben geschrieben ist 2. Pruefe, ob Frontmatter `name` und `description` enthaelt 3. Stelle sicher, dass Skill-Namen ueber alle Orte hinweg eindeutig sind 4. Pruefe Berechtigungen - Skills mit `deny` sind fuer Agenten unsichtbar --- # Supporto ACP | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/acp/#_top) Supporto ACP ============ Usa OpenCode in qualunque editor compatibile con ACP. OpenCode supporta [Agent Client Protocol](https://agentclientprotocol.com/) (ACP), permettendoti di usarlo direttamente in editor e IDE compatibili. ACP e è un protocollo aperto che standardizza la comunicazione tra editor di codice e agenti di coding AI. * * * [Configurazione](https://opencode.ai/docs/it/acp/#configurazione) ------------------------------------------------------------------ Per usare OpenCode via ACP, configura l’editor in modo che esegua il comando `opencode acp`. Il comando avvia OpenCode come sottoprocesso compatibile con ACP che comunica con l’editor via JSON-RPC su stdio. Qui sotto trovi esempi per editor popolari che supportano ACP. * * * ### [Zed](https://opencode.ai/docs/it/acp/#zed) Aggiungi alla configurazione di [Zed](https://zed.dev/) (`~/.config/zed/settings.json`): { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} Per aprirlo, usa l’azione `agent: new thread` nella **Command Palette**. Puoi anche assegnare una scorciatoia da tastiera modificando `keymap.json`: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/it/acp/#jetbrains-ides) Aggiungi al tuo acp.json per [JetBrains IDE](https://www.jetbrains.com/) secondo la [documentazione](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} Per aprirlo, seleziona il nuovo agente ‘OpenCode’ nel selettore agenti di AI Chat. * * * ### [Avante.nvim](https://opencode.ai/docs/it/acp/#avantenvim) Aggiungi alla configurazione di [Avante.nvim](https://github.com/yetone/avante.nvim) : { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} Se devi passare variabili d’ambiente: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/it/acp/#codecompanionnvim) Per usare OpenCode come agente ACP in [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) , aggiungi quanto segue alla config di Neovim: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) Questa config imposta CodeCompanion per usare OpenCode come agente ACP per la chat. Se devi passare variabili d’ambiente (come `OPENCODE_API_KEY`), vedi [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) nella documentazione di CodeCompanion.nvim. [Supporto](https://opencode.ai/docs/it/acp/#supporto) ------------------------------------------------------ OpenCode funziona via ACP come nel terminale. Tutte le funzionalita sono supportate: * Strumenti integrati (operazioni sui file, comandi da terminale, ecc.) * Strumenti personalizzati e comandi slash * Server MCP configurati nella tua configurazione OpenCode * Regole specifiche del progetto da `AGENTS.md` * Formatter e linter personalizzati * Sistema di agenti e permessi --- # ACP-Unterstützung | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/acp/#_top) ACP-Unterstützung ================= Verwenden Sie OpenCode in jedem ACP-kompatiblen Editor. OpenCode unterstützt [Agent Client Protocol](https://agentclientprotocol.com/) oder (ACP), sodass Sie es direkt in kompatiblen Editoren und IDEs verwenden können. ACP ist ein offenes Protokoll, das die Kommunikation zwischen Code-Editoren und AI-Coding-Agenten standardisiert. * * * [Konfiguration](https://opencode.ai/docs/de/acp/#konfiguration) ---------------------------------------------------------------- Um OpenCode über ACP zu verwenden, konfigurieren Sie Ihren Editor für die Ausführung des Befehls `opencode acp`. Der Befehl startet OpenCode als ACP-kompatiblen Unterprozess, der über stdio über JSON-RPC mit Ihrem Editor kommuniziert. Nachfolgend finden Sie Beispiele für beliebte Editoren, die ACP unterstützen. * * * ### [Zed](https://opencode.ai/docs/de/acp/#zed) Fügen Sie Ihrer [Zed](https://zed.dev/) \-Konfiguration (`~/.config/zed/settings.json`) Folgendes hinzu: { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} Um es zu öffnen, verwenden Sie die Aktion `agent: new thread` in der **Befehlspalette**. Sie können auch eine Tastenkombination binden, indem Sie Ihren `keymap.json` bearbeiten: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/de/acp/#jetbrains-ides) Fügen Sie zu Ihrem [JetBrains IDE](https://www.jetbrains.com/) acp.json gemäß [Dokumentation](https://www.jetbrains.com/help/ai-assistant/acp.html) hinzu: { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} Um es zu öffnen, verwenden Sie den neuen Agenten „OpenCode“ in der AI Chat Agent Selector. * * * ### [Avante.nvim](https://opencode.ai/docs/de/acp/#avantenvim) Fügen Sie Ihrer [Avante.nvim](https://github.com/yetone/avante.nvim) \-Konfiguration Folgendes hinzu: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} Wenn Sie Umgebungsvariablen übergeben müssen: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/de/acp/#codecompanionnvim) Um OpenCode als ACP-Agent in [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) zu verwenden, fügen Sie Folgendes zu Ihrer Neovim-Konfiguration hinzu: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) Diese Konfiguration richtet CodeCompanion so ein, dass OpenCode als ACP-Agent für den Chat verwendet wird. Wenn Sie Umgebungsvariablen (wie `OPENCODE_API_KEY`) übergeben müssen, finden Sie ausführliche Informationen zu [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) in der Dokumentation zu CodeCompanion.nvim. [Unterstützung](https://opencode.ai/docs/de/acp/#unterst%C3%BCtzung) --------------------------------------------------------------------- OpenCode funktioniert über ACP genauso wie im Terminal. Alle Funktionen werden unterstützt: * Integrierte Tools (Dateioperationen, Terminalbefehle usw.) * Benutzerdefinierte Tools und Slash-Befehle * MCP-Server, die in Ihrer OpenCode-Konfiguration konfiguriert sind * Projektspezifische Regeln von `AGENTS.md` * Benutzerdefinierte Formatierer und Linters * Agenten- und Berechtigungssystem --- # References | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/references/#_top) References ========== Add local directories and Git repositories as project references. هذا المحتوى غير متوفر بلغتك بعد. References give OpenCode access to directories outside the current project. Use them to make documentation, shared libraries, examples, or another repository available while you work. References are configured by alias in `opencode.json` or `opencode.jsonc`. { "$schema": "https://opencode.ai/config.json", "references": { "docs": { "path": "../product-docs", "description": "Use for product behavior and documentation conventions", }, "sdk": { "repository": "anomalyco/opencode-sdk-js", "branch": "main", "description": "Use for JavaScript SDK implementation details", }, },} * * * [Local directories](https://opencode.ai/docs/ar/references/#local-directories) ------------------------------------------------------------------------------- Use `path` to reference a local directory. { "references": { "docs": { "path": "../docs", }, },} Paths can be: * Relative to the config file that defines the reference * Absolute, such as `/home/user/docs` * Relative to your home directory, such as `~/docs` You can also use a string shorthand: { "references": { "docs": "../docs", },} * * * [Git repositories](https://opencode.ai/docs/ar/references/#git-repositories) ----------------------------------------------------------------------------- Use `repository` to reference a Git repository. OpenCode materializes the repository in its local repository cache and makes the checked-out source available as a reference directory. { "references": { "effect": { "repository": "Effect-TS/effect", "branch": "main", }, },} `repository` accepts Git URLs, host/path references, and GitHub `owner/repo` shorthand. The optional `branch` field selects a branch or ref. Without `branch`, OpenCode uses the repository’s default branch. You can use string shorthand when you do not need a branch, description, or other options: { "references": { "effect": "Effect-TS/effect", },} * * * [Describe usage](https://opencode.ai/docs/ar/references/#describe-usage) ------------------------------------------------------------------------- Add `description` to explain when an agent should use a reference. { "references": { "design-system": { "path": "../design-system", "description": "Use when implementing UI components or design tokens", }, },} OpenCode includes references with descriptions in agent context. Descriptions should be short and specific enough to distinguish references with similar content. References without descriptions remain available through autocomplete and direct use, but are not advertised to agents. * * * [Hide autocomplete entries](https://opencode.ai/docs/ar/references/#hide-autocomplete-entries) ----------------------------------------------------------------------------------------------- Set `hidden` to `true` to omit a reference from `@` autocomplete in the TUI. { "references": { "internal": { "path": "../internal", "description": "Use for internal implementation details", "hidden": true, }, },} `hidden` only affects autocomplete. A hidden reference with a description remains included in agent context. * * * [Use references](https://opencode.ai/docs/ar/references/#use-references) ------------------------------------------------------------------------- Configured references appear in TUI `@` autocomplete. Type `@alias` to attach the reference root, or `@alias/` to search for files inside it. Compare this implementation with @sdk/src/client.ts Agents also receive the resolved paths and descriptions of configured references that have descriptions in their system context, so they can inspect a reference when it is relevant without you attaching it manually. OpenCode automatically allows reference directories through its external-directory permission boundary. Normal tool permissions still apply; for example, an agent that cannot edit files does not gain edit access because a directory is configured as a reference. * * * [Configure fields](https://opencode.ai/docs/ar/references/#configure-fields) ----------------------------------------------------------------------------- | Field | Local | Git | Description | | --- | --- | --- | --- | | `path` | Yes | No | Local reference directory | | `repository` | No | Yes | Git URL, host/path, or GitHub `owner/repo` value | | `branch` | No | Yes | Optional Git branch or ref | | `description` | Yes | Yes | Guidance describing when to use the reference | | `hidden` | Yes | Yes | Hide the reference from TUI `@` autocomplete | Reference aliases cannot be empty or contain `/`, whitespace, backticks, or commas. --- # การรองรับ ACP | OpenCode [Skip to content](https://opencode.ai/docs/th/acp/#_top) การรองรับ ACP ============= ใช้ OpenCode ในโปรแกรมแก้ไขที่รองรับ ACP OpenCode รองรับ [Agent Client Protocol](https://agentclientprotocol.com/) (ACP) ซึ่งช่วยให้สามารถทำงานร่วมกับ editor และ IDE ต่างๆ ได้โดยตรง ACP เป็นมาตรฐานเปิดสำหรับการสื่อสารระหว่างโปรแกรมแก้ไขโค้ดและ AI agent * * * [การกำหนดค่า](https://opencode.ai/docs/th/acp/#%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) ---------------------------------------------------------------------------------------------------------------------------------------------------- ในการใช้ OpenCode ผ่าน ACP ให้กำหนดค่าโปรแกรมแก้ไขของคุณให้รันคำสั่ง `opencode acp` คำสั่งนี้จะเริ่ม OpenCode เป็น process ย่อยที่รองรับ ACP ซึ่งสื่อสารกับโปรแกรมแก้ไขของคุณผ่าน JSON-RPC ทาง stdio นี่คือตัวอย่างสำหรับโปรแกรมแก้ไขยอดนิยมที่รองรับ ACP * * * ### [Zed](https://opencode.ai/docs/th/acp/#zed) สำหรับ [Zed](https://zed.dev/) (`~/.config/zed/settings.json`): { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} สิ่งนี้จะเปิดใช้ `agent: new thread` ใน **Command Palette** คุณต้องตั้งค่า keybinding ใน `keymap.json` ของคุณ: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/th/acp/#jetbrains-ides) เพิ่มลงใน acp.json ของ [JetBrains IDE](https://www.jetbrains.com/) ของคุณตาม [เอกสาร](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} นี่เป็นการเปิดให้ตัวแทน ‘OpenCode’ ในเนื้อหาของตัวแทน AI Chat * * * ### [Avante.nvim](https://opencode.ai/docs/th/acp/#avantenvim) ยังคงมี [Avante.nvim](https://github.com/yetone/avante.nvim) ของคุณ: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} หากคุณต้องการส่งผ่าน environment variables (เช่น `OPENCODE_API_KEY`) คุณต้องระบุใน `env`: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/th/acp/#codecompanionnvim) ลองใช้ OpenCode ACP ใน [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) ให้เพิ่มสิ่งต่อไปนี้ใน Neovim ของคุณ: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) คุณสามารถใช้ CodeCompanion เพื่อใช้ opencode เป็น ACP agent สำหรับแชท หากคุณต้องส่ง environment variables (เช่น `OPENCODE_API_KEY`) โปรดดู [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) ในเอกสารของ CodeCompanion.nvim สำหรับรายละเอียดทั้งหมด [การรองรับ](https://opencode.ai/docs/th/acp/#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A) -------------------------------------------------------------------------------------------------------------------------------- opencode ทำงานผ่าน ACP เหมือนกับใน terminal และรองรับฟีเจอร์ทั้งหมด: * เครื่องมือใน (ไฟล์ไฟล์คำสั่งอื่นๆ) * คำอธิบายและคำสั่งสแลช * MCP แขกที่นี่คือข้อมูลเพิ่มเติมของ OpenCode ของคุณ * กฎเฉพาะโครงการจาก `AGENTS.md` * คนจัดรูปแบบและ linters เวียนนา * ระบบตัวแทนและระบบ --- # ACP 支援 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/acp/#_top) ACP 支援 ====== 在任何相容 ACP 的編輯器中使用 OpenCode。 OpenCode 支援 [Agent Client Protocol](https://agentclientprotocol.com/) (ACP),允許你直接在相容的編輯器和 IDE 中使用它。 ACP 是一個開放協議,用於標準化程式碼編輯器與 AI 編碼代理之間的通訊。 * * * [設定](https://opencode.ai/docs/zh-tw/acp/#%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------- 要透過 ACP 使用 OpenCode,請在編輯器中設定執行 `opencode acp` 命令。 該命令會將 OpenCode 作為相容 ACP 的子程序啟動,透過 stdio 上的 JSON-RPC 與編輯器進行通訊。 以下是支援 ACP 的常用編輯器的設定範例。 * * * ### [Zed](https://opencode.ai/docs/zh-tw/acp/#zed) 新增到你的 [Zed](https://zed.dev/) 設定檔(`~/.config/zed/settings.json`)中: { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} 開啟方式:在**命令面板**中執行 `agent: new thread` 操作。 你也可以透過編輯 `keymap.json` 來繫結鍵盤快速鍵: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/zh-tw/acp/#jetbrains-ides) 根據[文件](https://www.jetbrains.com/help/ai-assistant/acp.html) ,將以下內容新增到你的 [JetBrains IDE](https://www.jetbrains.com/) 的 acp.json 中: { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} 開啟方式:在 AI Chat 代理選擇器中選擇新的 ‘OpenCode’ 代理。 * * * ### [Avante.nvim](https://opencode.ai/docs/zh-tw/acp/#avantenvim) 新增到你的 [Avante.nvim](https://github.com/yetone/avante.nvim) 設定中: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} 如果需要傳遞環境變數: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/zh-tw/acp/#codecompanionnvim) 要在 [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) 中將 OpenCode 用作 ACP 代理,請將以下內容新增到你的 Neovim 設定中: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) 此設定將 CodeCompanion 設為使用 OpenCode 作為聊天的 ACP 代理。 如果需要傳遞環境變數(如 `OPENCODE_API_KEY`),請參閱 CodeCompanion.nvim 文件中的[設定適配器:環境變數](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) 了解詳細資訊。 [支援](https://opencode.ai/docs/zh-tw/acp/#%E6%94%AF%E6%8F%B4) ------------------------------------------------------------- OpenCode 透過 ACP 使用時與在終端機中使用的效果完全一致。所有功能均受支援: * 內建工具(檔案操作、終端機命令等) * 自訂工具和斜線命令 * 在 OpenCode 設定中設定的 MCP 伺服器 * 來自 `AGENTS.md` 的專案級規則 * 自訂格式化工具和程式碼檢查工具 * 代理和權限系統 --- # Поддержка ACP | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/acp/#_top) Поддержка ACP ============= Используйте opencode в любом ACP-совместимом редакторе. opencode поддерживает [Agent Client Protocol](https://agentclientprotocol.com/) (ACP), что позволяет использовать его непосредственно в совместимых редакторах и IDE. ACP — это открытый протокол, который стандартизирует взаимодействие между редакторами кода и ИИ-агентами. * * * [Настройка](https://opencode.ai/docs/ru/acp/#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0) ----------------------------------------------------------------------------------------------------- Чтобы использовать opencode через ACP, настройте свой редактор для запуска команды `opencode acp`. Команда запускает opencode как ACP-совместимый подпроцесс, который взаимодействует с вашим редактором через JSON-RPC через stdio. Ниже приведены примеры популярных редакторов, поддерживающих ACP. * * * ### [Zed](https://opencode.ai/docs/ru/acp/#zed) Добавьте в конфигурацию [Zed](https://zed.dev/) (`~/.config/zed/settings.json`): { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} Чтобы открыть его, используйте действие `agent: new thread` в **Палитре команд**. Вы также можете привязать сочетание клавиш, отредактировав свой `keymap.json`: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [IDE JetBrains](https://opencode.ai/docs/ru/acp/#ide-jetbrains) Добавьте в свою [JetBrains IDE](https://www.jetbrains.com/) acp.json в соответствии с [документацией](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} Чтобы открыть его, используйте новый агент opencode в селекторе агентов AI Chat. * * * ### [Avante.nvim](https://opencode.ai/docs/ru/acp/#avantenvim) Добавьте в свою конфигурацию [Avante.nvim](https://github.com/yetone/avante.nvim) : { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} Если вам нужно передать переменные среды: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/ru/acp/#codecompanionnvim) Чтобы использовать opencode в качестве агента ACP в [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) , добавьте в конфигурацию Neovim следующее: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) Эта конфигурация настраивает CodeCompanion для использования opencode в качестве агента ACP для чата. Если вам нужно передать переменные среды (например, `OPENCODE_API_KEY`), обратитесь к разделу [Настройка адаптеров: переменные среды](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) в документации CodeCompanion.nvim для получения полной информации. [Поддержка](https://opencode.ai/docs/ru/acp/#%D0%BF%D0%BE%D0%B4%D0%B4%D0%B5%D1%80%D0%B6%D0%BA%D0%B0) ----------------------------------------------------------------------------------------------------- opencode через ACP работает так же, как и в терминале. Поддерживаются все функции: * Встроенные инструменты (файловые операции, команды терминала и т. д.) * Пользовательские инструменты и команды слэша * Серверы MCP, настроенные в вашей конфигурации opencode * Правила для конкретного проекта из `AGENTS.md` * Пользовательские форматтеры и линтеры * Агенты и система разрешений --- # 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 kann sich in Language Server Protocol (LSP)-Server integrieren, um Diagnosen als Feedback für den Agenten zu verwenden. * * * [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 ist standardmäßig deaktiviert. Wenn es aktiviert ist, starten Server, sobald eine der oben genannten Dateierweiterungen erkannt wird und die Anforderungen erfüllt sind. * * * [Funktionsweise](https://opencode.ai/docs/de/lsp/#funktionsweise) ------------------------------------------------------------------ Wenn LSP aktiviert ist und 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. * * * [Bewährte Praktiken](https://opencode.ai/docs/de/lsp/#bew%C3%A4hrte-praktiken) ------------------------------------------------------------------------------- LSP kann dem Agenten helfen, Probleme zu finden und zu beheben, indem es Diagnosen von Sprachservern bereitstellt. Das ist in einigen Projekten nützlich, aber nicht immer ein klarer Vorteil. Sprachserver können aus dem Sync geraten, viel Speicher verwenden, je nach Version oder Projekt unterschiedlich arbeiten und Agent-Workflows verlangsamen. In vielen Projekten ist es besser, wenn der Agent lint, typecheck oder andere diagnostische CLI-Tools direkt ausführt, damit Fehler in die Agent-Schleife zurückfließen, ohne diese Kompromisse einzugehen. Dokumentieren Sie diese Befehle in Instruktionsdateien wie `AGENTS.md` oder Skills, damit der Agent weiß, was er ausführen soll. Aktivieren Sie LSP, wenn Ihr Projekt von zusätzlichem Sprachserver-Feedback profitiert. * * * [Konfiguration](https://opencode.ai/docs/de/lsp/#konfiguration) ---------------------------------------------------------------- Sie können LSP-Server über den Abschnitt `lsp` in Ihrer OpenCode-Konfiguration aktivieren und anpassen. Um alle integrierten LSP-Server zu aktivieren, setzen Sie `lsp` auf `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Verwenden Sie ein Objekt, um integrierte Server aktiviert zu lassen und gleichzeitig Überschreibungen oder benutzerdefinierte Server zu konfigurieren. { "$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) Wenn `lsp` ausgelassen wird, sind alle LSP-Server deaktiviert. Um alle LSP-Server zu deaktivieren, nachdem sie durch eine andere Konfiguration aktiviert wurden, 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. --- # Server LSP | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/lsp/#_top) Server LSP ========== OpenCode si integra con i tuoi server LSP. OpenCode può integrarsi con server Language Server Protocol (LSP) per usare la diagnostica come feedback per l’agente. * * * [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 | LSP è disabilitato per impostazione predefinita. Quando è abilitato, i server si avviano quando viene rilevata una delle estensioni qui sopra e i requisiti sono soddisfatti. * * * [Come funziona](https://opencode.ai/docs/it/lsp/#come-funziona) ---------------------------------------------------------------- Quando LSP è abilitato e 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. * * * [Buone pratiche](https://opencode.ai/docs/it/lsp/#buone-pratiche) ------------------------------------------------------------------ LSP può aiutare l’agente a trovare e correggere problemi fornendo diagnostica dai server di linguaggio. Questo è utile in alcuni progetti, ma non è sempre un vantaggio netto. I server di linguaggio possono andare fuori sincronizzazione, usare molta memoria, variare in base alla versione o al progetto e rallentare i workflow dell’agente. In molti progetti è meglio far eseguire direttamente all’agente lint, typecheck o altri strumenti CLI diagnostici, così gli errori rientrano nel ciclo dell’agente senza questi compromessi. Documenta questi comandi nei file di istruzioni come `AGENTS.md` o nelle skills, così l’agente sa cosa eseguire. Abilita LSP quando il tuo progetto trae beneficio da feedback aggiuntivo del server di linguaggio. * * * [Configura](https://opencode.ai/docs/it/lsp/#configura) -------------------------------------------------------- Puoi abilitare e personalizzare i server LSP tramite la sezione `lsp` nella configurazione di opencode. Per abilitare tutti i server LSP integrati, imposta `lsp` a `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Usa un oggetto per mantenere abilitati i server integrati mentre configuri override o server personalizzati. { "$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) Se `lsp` è omesso, tutti i server LSP sono disabilitati. Per disabilitare tutti i server LSP dopo che un’altra configurazione li ha abilitati, 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. --- # Support ACP | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/acp/#_top) Support ACP =========== Utilisez OpenCode dans n’importe quel éditeur compatible ACP. OpenCode prend en charge le [Agent Client Protocol](https://agentclientprotocol.com/) (ACP), vous permettant de l’utiliser directement dans les éditeurs et IDE compatibles. ACP est un protocole ouvert qui standardise la communication entre les éditeurs de code et les agents de codage AI. * * * [Configuration](https://opencode.ai/docs/fr/acp/#configuration) ---------------------------------------------------------------- Pour utiliser OpenCode via ACP, configurez votre éditeur pour exécuter la commande `opencode acp`. La commande démarre OpenCode en tant que sous-processus compatible ACP qui communique avec votre éditeur via JSON-RPC sur stdio. Vous trouverez ci-dessous des exemples d’éditeurs populaires prenant en charge ACP. * * * ### [Zed](https://opencode.ai/docs/fr/acp/#zed) Ajoutez à votre configuration [Zed](https://zed.dev/) (`~/.config/zed/settings.json`) : { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} Pour l’ouvrir, utilisez l’action `agent: new thread` dans la **Palette de commandes**. Vous pouvez également associer un raccourci clavier en modifiant votre `keymap.json` : [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [IDE JetBrains](https://opencode.ai/docs/fr/acp/#ide-jetbrains) Ajoutez `acp.json` à votre [IDE JetBrains](https://www.jetbrains.com/) conformément à la [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} Pour l’ouvrir, utilisez le nouvel agent « OpenCode » dans le sélecteur d’agent AI Chat. * * * ### [Avante.nvim](https://opencode.ai/docs/fr/acp/#avantenvim) Ajoutez à votre configuration [Avante.nvim](https://github.com/yetone/avante.nvim) : { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} Si vous devez transmettre des variables d’environnement : { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/fr/acp/#codecompanionnvim) Pour utiliser OpenCode comme agent ACP dans [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) , ajoutez ce qui suit à votre configuration Neovim : require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) Cette configuration configure CodeCompanion pour utiliser OpenCode comme agent ACP pour le chat. Si vous devez transmettre des variables d’environnement (comme `OPENCODE_API_KEY`), reportez-vous à [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) dans la documentation CodeCompanion.nvim pour plus de détails. [Prise en charge](https://opencode.ai/docs/fr/acp/#prise-en-charge) -------------------------------------------------------------------- OpenCode fonctionne de la même manière via ACP que dans le terminal. Toutes les fonctionnalités sont prises en charge : * Outils intégrés (opérations sur les fichiers, commandes de terminal, etc.) * Outils personnalisés et commandes slash * Serveurs MCP configurés dans votre configuration OpenCode * Règles spécifiques au projet à partir de `AGENTS.md` * Formateurs et linters personnalisés * Système d’agents et d’autorisations --- # Serveurs LSP | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/lsp/#_top) Serveurs LSP ============ OpenCode s'intègre à vos serveurs LSP. OpenCode peut s’intégrer aux serveurs Language Server Protocol (LSP) pour utiliser les diagnostics comme retour pour l’agent. * * * [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 | LSP est désactivé par défaut. Lorsqu’il est activé, les serveurs démarrent lorsqu’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 LSP est activé et qu’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. * * * [Bonnes pratiques](https://opencode.ai/docs/fr/lsp/#bonnes-pratiques) ---------------------------------------------------------------------- LSP peut aider l’agent à trouver et corriger des problèmes en fournissant les diagnostics des serveurs de langage. C’est utile dans certains projets, mais ce n’est pas toujours un gain net. Les serveurs de langage peuvent se désynchroniser, consommer beaucoup de mémoire, varier selon la version ou le projet, et ralentir les flux de travail de l’agent. Dans de nombreux projets, il est préférable de faire exécuter directement par l’agent le lint, le typecheck ou d’autres outils CLI de diagnostic, afin que les erreurs reviennent dans la boucle de l’agent sans ces compromis. Documentez ces commandes dans des fichiers d’instructions comme `AGENTS.md` ou des skills afin que l’agent sache quoi exécuter. Activez LSP lorsque votre projet bénéficie d’un retour supplémentaire des serveurs de langage. * * * [Configuration](https://opencode.ai/docs/fr/lsp/#configuration) ---------------------------------------------------------------- Vous pouvez activer et personnaliser les serveurs LSP via la section `lsp` de votre configuration opencode. Pour activer tous les serveurs LSP intégrés, définissez `lsp` sur `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Utilisez un objet pour conserver les serveurs intégrés activés tout en configurant des remplacements ou des serveurs personnalisés. { "$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) Si `lsp` est omis, tous les serveurs LSP sont désactivés. Pour désactiver tous les serveurs LSP après qu’une autre configuration les a activés, 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. --- # LSP-servere | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/lsp/#_top) LSP-servere =========== opencode integreres med LSP-serverne dine. OpenCode kan integreres med Language Server Protocol (LSP)-servere for å bruke diagnostikk som tilbakemelding til agenten. * * * [Innebygde servere](https://opencode.ai/docs/nb/lsp/#innebygde-servere) ------------------------------------------------------------------------ OpenCode kommer med flere innebygde LSP-servere for populære språk: | LSP Server | Filendelser | Krav | | --- | --- | --- | | astro | .astro | Installeres automatisk for Astro-prosjekter | | bash | .sh, .bash, .zsh, .ksh | Installerer bash-language-server automatisk | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Installeres automatisk for C/C++-prosjekter | | csharp | .cs | `.NET SDK` installert | | clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` kommando tilgjengelig | | dart | .dart | `dart` kommando tilgjengelig | | deno | .ts, .tsx, .js, .jsx, .mjs | `deno` kommando tilgjengelig (automatisk oppdager deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | `elixir` kommando tilgjengelig | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` avhengighet i prosjekt | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` installert | | gleam | .gleam | `gleam` kommando tilgjengelig | | gopls | .go | `go` kommando tilgjengelig | | hls | .hs, .lhs | `haskell-language-server-wrapper` kommando tilgjengelig | | jdtls | .java | `Java SDK (version 21+)` installert | | julials | .jl | `julia` og `LanguageServer.jl` installert | | kotlin-ls | .kt, .kts | Installeres automatisk for Kotlin-prosjekter | | lua-ls | .lua | Installeres automatisk for Lua-prosjekter | | nixd | .nix | `nixd` kommando tilgjengelig | | ocaml-lsp | .ml, .mli | `ocamllsp` kommando tilgjengelig | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | `oxlint` avhengighet i prosjekt | | php intelephense | .php | Installeres automatisk for PHP-prosjekter | | prisma | .prisma | `prisma` kommando tilgjengelig | | pyright | .py, .pyi | `pyright` avhengighet installert | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | `ruby` og `gem` kommandoer tilgjengelig | | rust | .rs | `rust-analyzer` kommando tilgjengelig | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` installert (`xcode` på macOS) | | svelte | .svelte | Installeres automatisk for Svelte-prosjekter | | terraform | .tf, .tfvars | Installeres automatisk fra GitHub-utgivelser | | tinymist | .typ, .typc | Installeres automatisk fra GitHub-utgivelser | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` avhengighet i prosjekt | | vue | .vue | Installeres automatisk for Vue-prosjekter | | yaml-ls | .yaml, .yml | Installerer Red Hat yaml-language-server automatisk | | zls | .zig, .zon | `zig` kommando tilgjengelig | LSP er deaktivert som standard. Når det er aktivert, starter servere når en av filtypene ovenfor oppdages og kravene oppfylles. * * * [Slik fungerer det](https://opencode.ai/docs/nb/lsp/#slik-fungerer-det) ------------------------------------------------------------------------ Når LSP er aktivert og opencode åpner en fil, gjør den: 1. Kontrollerer filtypen mot alle aktiverte LSP-servere. 2. Starter den riktige LSP-serveren hvis den ikke allerede kjører. * * * [Beste praksis](https://opencode.ai/docs/nb/lsp/#beste-praksis) ---------------------------------------------------------------- LSP kan hjelpe agenten med å finne og fikse problemer ved å gi diagnostikk fra språkservere. Dette er nyttig i noen prosjekter, men er ikke alltid en klar gevinst. Språkservere kan komme ut av synk, bruke mye minne, variere etter versjon eller prosjekt og redusere agentarbeidsflyter. I mange prosjekter er det bedre at agenten kjører lint, typecheck eller andre diagnostiske CLI-verktøy direkte, slik at feil mates tilbake i agentløkken uten disse avveiningene. Dokumenter disse kommandoene i instruksjonsfiler som `AGENTS.md` eller skills, slik at agenten vet hva den skal kjøre. Aktiver LSP når prosjektet ditt har nytte av ekstra språkservertilbakemelding. * * * [Konfigurasjon](https://opencode.ai/docs/nb/lsp/#konfigurasjon) ---------------------------------------------------------------- Du kan aktivere og tilpasse LSP-servere gjennom `lsp`\-delen i OpenCode-konfigurasjonen. For å aktivere alle innebygde LSP-servere, sett `lsp` til `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Bruk et objekt for å beholde innebygde servere aktivert mens du konfigurerer overstyringer eller egendefinerte servere. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Hver LSP-server støtter følgende: | Egenskap | Type | Beskrivelse | | --- | --- | --- | | `disabled` | boolean | Sett dette til `true` for å deaktivere LSP-serveren | | `command` | string\[\] | Kommandoen for å starte LSP-serveren | | `extensions` | string\[\] | Filendelser denne LSP-serveren skal håndtere | | `env` | object | Miljøvariabler som skal angis når serveren startes | | `initialization` | object | Initialiseringsalternativer for å sende til LSP-serveren | La oss se på noen eksempler. * * * ### [Miljøvariabler](https://opencode.ai/docs/nb/lsp/#milj%C3%B8variabler) Bruk egenskapen `env` til å angi miljøvariabler når du starter LSP-serveren: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Initialiseringsalternativer](https://opencode.ai/docs/nb/lsp/#initialiseringsalternativer) Bruk egenskapen `initialization` til å sende initialiseringsalternativer til LSP-serveren. Dette er serverspesifikke innstillinger sendt under LSP `initialize`\-forespørselen: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Deaktivering av LSP-servere](https://opencode.ai/docs/nb/lsp/#deaktivering-av-lsp-servere) Hvis `lsp` utelates, er alle LSP-servere deaktivert. For å deaktivere alle LSP-servere etter at en annen konfigurasjon har aktivert dem, sett `lsp` til `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} For å deaktivere en **spesifikk** LSP-server, sett `disabled` til `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Egendefinerte LSP-servere](https://opencode.ai/docs/nb/lsp/#egendefinerte-lsp-servere) Du kan legge til egendefinerte LSP-servere ved å spesifisere kommandoen og filtypene: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Tilleggsinformasjon](https://opencode.ai/docs/nb/lsp/#tilleggsinformasjon) ---------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/nb/lsp/#php-intelephense) PHP Intelephense tilbyr førsteklasses funksjoner gjennom en lisensnøkkel. Du kan oppgi en lisensnøkkel ved å plassere (bare) nøkkelen i en tekstfil på: * På macOS/Linux: `$HOME/intelephense/license.txt` * På Windows: `%USERPROFILE%/intelephense/license.txt` Filen skal bare inneholde lisensnøkkelen uten ekstra innhold. --- # LSP Sunucuları | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/lsp/#_top) LSP Sunucuları ============== OpenCode, LSP sunucularınızla bütünleşir. OpenCode, tanılamayı agent için geri bildirim olarak kullanmak üzere Language Server Protocol (LSP) sunucularıyla bütünleşebilir. * * * [Yerleşik](https://opencode.ai/docs/tr/lsp/#yerle%C5%9Fik) ----------------------------------------------------------- OpenCode, popüler diller için çeşitli yerleşik LSP sunucularıyla birlikte gelir: | LSP Sunucu | Uzantılar | Gereksinimler | | --- | --- | --- | | astro | .astro | Astro projeleri için otomatik kurulumlar | | bash | .sh, .bash, .zsh, .ksh | `bash-language-server`’ı otomatik olarak yükler | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | C/C++ projeleri için otomatik kurulumlar | | csharp | .cs | `.NET SDK` kurulu | | clojure-lsp | .clj, .cljs, .cljc, .edn | `clojure-lsp` komutu mevcut | | dart | .dart | `dart` komutu mevcut | | deno | .ts, .tsx, .js, .jsx, .mjs | `deno` komutu mevcut (deno.json/deno.jsonc otomatik olarak algılanır) | | elixir-ls | .ex, .exs | `elixir` komutu mevcut | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | Projede `eslint` bağımlılığı | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` kurulu | | gleam | .gleam | `gleam` komutu mevcut | | gopls | .go | `go` komutu mevcut | | hls | .hs, .lhs | `haskell-language-server-wrapper` komutu mevcut | | jdtls | .java | `Java SDK (version 21+)` kurulu | | julials | .jl | `julia` ve `LanguageServer.jl` kurulu | | kotlin-ls | .kt, .kts | Kotlin projeleri için otomatik kurulumlar | | lua-ls | .lua | Lua projeleri için otomatik kurulumlar | | nixd | .nix | `nixd` komutu mevcut | | ocaml-lsp | .ml, .mli | `ocamllsp` komutu mevcut | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | Projede `oxlint` bağımlılığı | | php intelephense | .php | PHP projeleri için otomatik yüklemeler | | prisma | .prisma | `prisma` komutu mevcut | | pyright | .py, .pyi | `pyright` bağımlılığı kurulu | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | `ruby` ve `gem` komutları mevcut | | rust | .rs | `rust-analyzer` komutu mevcut | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` kurulu (macOS’ta `xcode`) | | svelte | .svelte | Svelte projeleri için otomatik kurulumlar | | terraform | .tf, .tfvars | GitHub sürümlerinden otomatik yüklemeler | | tinymist | .typ, .typc | GitHub sürümlerinden otomatik yüklemeler | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | Projede `typescript` bağımlılığı | | vue | .vue | Vue projeleri için otomatik yüklemeler | | yaml-ls | .yaml, .yml | Red Hat yaml-language-server’ı otomatik olarak yükler | | zls | .zig, .zon | `zig` komutu mevcut | LSP varsayılan olarak devre dışıdır. Etkinleştirildiğinde, yukarıdaki dosya uzantılarından biri tespit edilir ve gereksinimler karşılanırsa sunucular başlatılır. * * * [Nasıl Çalışır?](https://opencode.ai/docs/tr/lsp/#nas%C4%B1l-%C3%A7al%C4%B1%C5%9F%C4%B1r) ------------------------------------------------------------------------------------------ LSP etkinleştirildiğinde ve opencode bir dosyayı açtığında: 1. Dosya uzantısını tüm etkin LSP sunucularına göre kontrol eder. 2. Henüz çalışmıyorsa uygun LSP sunucusunu başlatır. * * * [En İyi Uygulamalar](https://opencode.ai/docs/tr/lsp/#en-i%CC%87yi-uygulamalar) -------------------------------------------------------------------------------- LSP, dil sunucularından tanılama sağlayarak agent’ın sorunları bulup düzeltmesine yardımcı olabilir. Bu bazı projelerde yararlıdır, ancak her zaman net bir kazanç değildir. Dil sunucuları senkronizasyonu kaybedebilir, önemli miktarda bellek kullanabilir, sürüme veya projeye göre değişebilir ve agent iş akışlarını yavaşlatabilir. Birçok projede agent’ın lint, typecheck veya diğer tanılama CLI araçlarını doğrudan çalıştırması daha iyidir; böylece hatalar bu ödünleşimler olmadan agent döngüsüne geri beslenir. Agent’ın ne çalıştıracağını bilmesi için bu komutları `AGENTS.md` veya skills gibi talimat dosyalarında belgeleyin. Projeniz ek dil sunucusu geri bildiriminden yararlanıyorsa LSP’yi etkinleştirin. * * * [Yapılandırma](https://opencode.ai/docs/tr/lsp/#yap%C4%B1land%C4%B1rma) ------------------------------------------------------------------------ LSP sunucularını, opencode yapılandırmanızdaki `lsp` bölümü aracılığıyla etkinleştirebilir ve özelleştirebilirsiniz. Tüm yerleşik LSP sunucularını etkinleştirmek için `lsp` değerini `true` olarak ayarlayın. { "$schema": "https://opencode.ai/config.json", "lsp": true} Yerleşik sunucuları etkin tutarken geçersiz kılmaları veya özel sunucuları yapılandırmak için bir nesne kullanın. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Her LSP sunucusu aşağıdakileri destekler: | Özellik | Tip | Açıklama | | --- | --- | --- | | `disabled` | boolean | LSP sunucusunu devre dışı bırakmak için bunu `true` olarak ayarlayın | | `command` | string\[\] | LSP sunucusunu başlatma komutu | | `extensions` | string\[\] | Bu LSP sunucusunun işlemesi gereken dosya uzantıları | | `env` | object | Sunucuyu başlatırken ayarlanacak ortam değişkenleri | | `initialization` | object | LSP sunucusuna gönderilecek başlatma seçenekleri | Bazı örneklere bakalım. * * * ### [Ortam değişkenleri](https://opencode.ai/docs/tr/lsp/#ortam-de%C4%9Fi%C5%9Fkenleri) LSP sunucusunu başlatırken ortam değişkenlerini ayarlamak için `env` özelliğini kullanın: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Başlatma seçenekleri](https://opencode.ai/docs/tr/lsp/#ba%C5%9Flatma-se%C3%A7enekleri) Başlatma seçeneklerini LSP sunucusuna iletmek için `initialization` özelliğini kullanın. Bunlar LSP `initialize` isteği sırasında gönderilen sunucuya özel ayarlardır: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [LSP sunucularını devre dışı bırakma](https://opencode.ai/docs/tr/lsp/#lsp-sunucular%C4%B1n%C4%B1-devre-d%C4%B1%C5%9F%C4%B1-b%C4%B1rakma) `lsp` atlanırsa tüm LSP sunucuları devre dışı kalır. Başka bir yapılandırma etkinleştirdikten sonra tüm LSP sunucularını devre dışı bırakmak için `lsp` değerini `false` olarak ayarlayın: { "$schema": "https://opencode.ai/config.json", "lsp": false} **Belirli** bir LSP sunucusunu devre dışı bırakmak için `disabled`’yi `true` olarak ayarlayın: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Özel LSP sunucuları](https://opencode.ai/docs/tr/lsp/#%C3%B6zel-lsp-sunucular%C4%B1) Komutu ve dosya uzantılarını belirterek özel LSP sunucuları ekleyebilirsiniz: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Ek Bilgiler](https://opencode.ai/docs/tr/lsp/#ek-bilgiler) ------------------------------------------------------------ ### [PHP Intelephense](https://opencode.ai/docs/tr/lsp/#php-intelephense) PHP Intelephense, bir lisans anahtarı aracılığıyla premium özellikler sunar. Anahtarı (yalnızca) şu adresteki bir metin dosyasına yerleştirerek bir lisans anahtarı sağlayabilirsiniz: * macOS/Linux’ta: `$HOME/intelephense/license.txt` * Windows’ta: `%USERPROFILE%/intelephense/license.txt` Dosya, ek içerik olmadan yalnızca lisans anahtarını içermelidir. --- # İzinler | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/permissions/#_top) İzinler ======= Hangi işlemlerin çalıştırılması için onay sürecini kontrol edin. opencode, belirli bir eylemin otomatik olarak mı çalıştırılacağına, size sorulacağına veya engelleneceğine karar vermek için `permission` yapılandırmasını kullanır. `v1.1.1` itibarıyla eski `tools` boolean yapılandırması kullanımdan kaldırıldı ve `permission` ile birleştirildi. Eski `tools` yapılandırması geriye dönük uyumluluk açısından hâlâ desteklenmektedir. * * * [Eylemler](https://opencode.ai/docs/tr/permissions/#eylemler) -------------------------------------------------------------- Her izin kuralı şunlardan birine çözümlenir: * `"allow"` — onay olmadan çalıştır * `"ask"` — onay istemi * `"deny"` — eylemi engelle * * * [Yapılandırma](https://opencode.ai/docs/tr/permissions/#yap%C4%B1land%C4%B1rma) -------------------------------------------------------------------------------- İzinleri genel olarak (`*` ile) ayarlayabilir ve belirli araçları geçersiz kılabilirsiniz. { "$schema": "https://opencode.ai/config.json", "permission": { "*": "ask", "bash": "allow", "edit": "deny" }} Ayrıca tüm izinleri aynı anda ayarlayabilirsiniz: { "$schema": "https://opencode.ai/config.json", "permission": "allow"} * * * [Ayrıntılı Kurallar (Nesne Sözdizimi)](https://opencode.ai/docs/tr/permissions/#ayr%C4%B1nt%C4%B1l%C4%B1-kurallar-nesne-s%C3%B6zdizimi) ---------------------------------------------------------------------------------------------------------------------------------------- Çoğu izin için, araç girişine bağlı olarak farklı eylemleri uygulamak için bir nesneyi kullanabilirsiniz. { "$schema": "https://opencode.ai/config.json", "permission": { "bash": { "*": "ask", "git *": "allow", "npm *": "allow", "rm *": "deny", "grep *": "allow" }, "edit": { "*": "deny", "packages/web/src/content/docs/*.mdx": "allow" } }} Kurallar, **son eşleşen kuralın kazanması** ile kalıp eşleşmesine göre değerlendirilir. Yaygın bir model, tümünü yakala `"*"` kuralını ilk sıraya koymak ve daha spesifik kuralları ondan sonra koymaktır. ### [Joker Karakterler](https://opencode.ai/docs/tr/permissions/#joker-karakterler) İzin kalıpları basit joker karakter eşleştirmesini kullanır: * `*` herhangi bir karakterin sıfır veya daha fazlasıyla eşleşir * `?` tam olarak bir karakterle eşleşir * Diğer tüm karakterler birebir eşleşir ### [Ana Dizin Genişletme](https://opencode.ai/docs/tr/permissions/#ana-dizin-geni%C5%9Fletme) Ana dizininize referans vermek için bir modelin başlangıcında `~` veya `$HOME` kullanabilirsiniz. Bu özellikle [`external_directory`](https://opencode.ai/docs/tr/permissions/#external-directories) kuralları için kullanışlıdır. * `~/projects/*` -> `/Users/username/projects/*` * `$HOME/projects/*` -> `/Users/username/projects/*` * `~` -> `/Users/username` ### [Harici Dizinler](https://opencode.ai/docs/tr/permissions/#harici-dizinler) opencode’un başlatıldığı çalışma dizini dışındaki yollara dokunan araç çağrılarına izin vermek için `external_directory` kullanın. Bu, girdi olarak bir yolu alan tüm araçlar için geçerlidir (örneğin `read`, `edit`, `glob`, `grep` ve birçok `bash` komutu). Ana sayfa genişletmesi (`~/...` gibi) yalnızca bir kalıbın nasıl yazıldığını etkiler. Geçerli çalışma alanının harici bir yolunu oluşturmaz, dolayısıyla çalışma dizini dışındaki yollara yine de `external_directory` aracılığıyla izin verilmesi gerekir. Örneğin bu, `~/projects/personal/` altındaki her şeye erişime izin verir: { "$schema": "https://opencode.ai/config.json", "permission": { "external_directory": { "~/projects/personal/**": "allow" } }} Burada izin verilen herhangi bir dizin, geçerli çalışma alanıyla aynı varsayılanları devralır. [`read` defaults to `allow`](https://opencode.ai/docs/tr/permissions/#defaults) ’dan bu yana, geçersiz kılınmadığı sürece `external_directory` altındaki girişler için okumalara da izin verilir. Bir aracın bu yollarda kısıtlanması gerektiğinde (okumaları tutarken düzenlemeleri engellemek gibi) açık kurallar ekleyin: { "$schema": "https://opencode.ai/config.json", "permission": { "external_directory": { "~/projects/personal/**": "allow" }, "edit": { "~/projects/personal/**": "deny" } }} Listeyi güvenilir yollara odaklı tutun ve diğer araçlar için gereken ekstra izin verme veya reddetme kurallarını katmanlayın (örneğin `bash`). * * * [Mevcut İzinler](https://opencode.ai/docs/tr/permissions/#mevcut-i%CC%87zinler) -------------------------------------------------------------------------------- opencode izinleri araç adına ve birkaç güvenlik önlemine göre anahtarlanır: * `read` — bir dosyayı okumak (dosya yoluyla eşleşir) * `edit` — tüm dosya değişiklikleri (`edit`, `write`, `patch`’i kapsar) * `glob` — dosya genellemesi (glob düzeniyle eşleşir) * `grep` — içerik arama (regex modeliyle eşleşir) * `bash` — kabuk komutlarını çalıştırma (`git status --porcelain` gibi ayrıştırılmış komutlarla eşleşir) * `task` — alt agent’ların başlatılması (alt agent türüyle eşleşir) * `skill` — bir skill yükleniyor (skill adıyla eşleşir) * `lsp` — LSP sorgularını çalıştırıyor (şu anda ayrıntılı değil) * `webfetch` — URL getiriliyor (URL ile eşleşiyor) * `websearch` — web arama (sorguyla eşleşir) * `external_directory` — bir araç proje çalışma dizini dışındaki yollara dokunduğunda tetiklenir * `doom_loop` — aynı araç çağrısı aynı girdiyle 3 kez tekrarlandığında tetiklenir * * * [Varsayılanlar](https://opencode.ai/docs/tr/permissions/#varsay%C4%B1lanlar) ----------------------------------------------------------------------------- Hiçbir şey belirtmezseniz opencode izin verilen varsayılanlardan başlar: * Çoğu izin varsayılan olarak `"allow"` şeklindedir. * `doom_loop` ve `external_directory` varsayılan olarak `"ask"`’dir. * `read`, `"allow"`’dır, ancak `.env` dosyaları varsayılan olarak reddedilir: { "permission": { "read": { "*": "allow", "*.env": "deny", "*.env.*": "deny", "*.env.example": "allow" } }} * * * [“Sor” Ne Yapar?](https://opencode.ai/docs/tr/permissions/#sor-ne-yapar) ------------------------------------------------------------------------- opencode onay istediğinde kullanıcı arayüzü üç sonuç sunar: * `once` — yalnızca bu isteği onayla * `always` — önerilen kalıplarla eşleşen gelecekteki istekleri onaylayın (geçerli opencode oturumunun geri kalanı için) * `reject` — isteği reddet `always`’ın onaylayacağı kalıp seti araç tarafından sağlanır (örneğin, bash onayları genellikle `git status*` gibi güvenli bir komut önekini beyaz listeye alır). * * * [Agent’lar](https://opencode.ai/docs/tr/permissions/#agentlar) --------------------------------------------------------------- Agent bazında izinleri geçersiz kılabilirsiniz. Agent izinleri global yapılandırmayla birleştirilir ve agent kuralları önceliklidir. [Daha fazla bilgi](https://opencode.ai/docs/agents#permissions) . { "$schema": "https://opencode.ai/config.json", "permission": { "bash": { "*": "ask", "git *": "allow", "git commit *": "deny", "git push *": "deny", "grep *": "allow" } }, "agent": { "build": { "permission": { "bash": { "*": "ask", "git *": "allow", "git commit *": "ask", "git push *": "deny", "grep *": "allow" } } } }} Agent izinlerini Markdown’da da yapılandırabilirsiniz: ---description: Code review without editsmode: subagentpermission: edit: deny bash: ask webfetch: deny--- Only analyze code and suggest changes. --- # LSP-серверы | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/lsp/#_top) LSP-серверы =========== opencode интегрируется с вашими серверами LSP. opencode может интегрироваться с серверами Language Server Protocol (LSP), чтобы использовать диагностику как обратную связь для агента. * * * [Встроенные](https://opencode.ai/docs/ru/lsp/#%D0%B2%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5) ------------------------------------------------------------------------------------------------------------ opencode поставляется с несколькими встроенными LSP-серверами для популярных языков: | LSP Server | Extensions | Requirements | | --- | --- | --- | | 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+)` установлен | | 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` установлен (`xcode` на macOS) | | svelte | .svelte | Автоматически устанавливается для проектов Svelte | | terraform | .tf, .tfvars | Автоматически устанавливается из релизов GitHub | | tinymist | .typ, .typc | Автоматически устанавливается из релизов GitHub | | 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/ru/lsp/#%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) -------------------------------------------------------------------------------------------------------------------------------------------- Когда LSP включен и opencode открывает файл, он: 1. Проверяет расширение файла на всех включенных серверах LSP. 2. Запускает соответствующий сервер LSP, если он еще не запущен. * * * [Рекомендации](https://opencode.ai/docs/ru/lsp/#%D1%80%D0%B5%D0%BA%D0%BE%D0%BC%D0%B5%D0%BD%D0%B4%D0%B0%D1%86%D0%B8%D0%B8) -------------------------------------------------------------------------------------------------------------------------- LSP может помочь агенту находить и исправлять проблемы, предоставляя диагностику от языковых серверов. Это полезно в некоторых проектах, но не всегда является однозначным преимуществом. Языковые серверы могут рассинхронизироваться, потреблять много памяти, отличаться по поведению между версиями или проектами и замедлять рабочие процессы агента. Во многих проектах лучше, чтобы агент напрямую запускал lint, typecheck или другие диагностические CLI-инструменты; так ошибки возвращаются в цикл агента без этих компромиссов. Задокументируйте эти команды в файлах инструкций, например `AGENTS.md` или skills, чтобы агент знал, что запускать. Включайте LSP, когда проект получает пользу от дополнительной обратной связи языкового сервера. * * * [Настройка](https://opencode.ai/docs/ru/lsp/#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0) ----------------------------------------------------------------------------------------------------- Вы можете включить и настроить серверы LSP через раздел `lsp` в конфигурации opencode. Чтобы включить все встроенные LSP-серверы, установите `lsp` в `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Используйте объект, чтобы оставить встроенные серверы включенными и при этом настроить переопределения или пользовательские серверы. { "$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/ru/lsp/#%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) Используйте свойство `env` для установки переменных среды при запуске сервера LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Параметры инициализации](https://opencode.ai/docs/ru/lsp/#%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B-%D0%B8%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B8) Используйте свойство `initialization` для передачи параметров инициализации на LSP-сервер. Это настройки, специфичные для сервера, отправляемые во время запроса LSP `initialize`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Отключение LSP-серверов](https://opencode.ai/docs/ru/lsp/#%D0%BE%D1%82%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-lsp-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D0%BE%D0%B2) Если `lsp` не указан, все LSP-серверы отключены. Чтобы отключить все 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/ru/lsp/#%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-lsp-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D1%8B) Вы можете добавить собственные LSP-серверы, указав команду и расширения файлов: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Дополнительная информация](https://opencode.ai/docs/ru/lsp/#%D0%B4%D0%BE%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F-%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%86%D0%B8%D1%8F) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/ru/lsp/#php-intelephense) PHP Intelephense предлагает дополнительные функции через лицензионный ключ. Вы можете предоставить лицензионный ключ, поместив (только) ключ в текстовый файл по адресу: * В macOS/Linux: `$HOME/intelephense/license.txt` * В Windows: `%USERPROFILE%/intelephense/license.txt` Файл должен содержать только лицензионный ключ без какого-либо дополнительного содержимого. --- # LSP เซิร์ฟเวอร์ | OpenCode [Skip to content](https://opencode.ai/docs/th/lsp/#_top) LSP เซิร์ฟเวอร์ =============== OpenCode ทำงานร่วมกับเซิร์ฟเวอร์ LSP ของคุณ OpenCode สามารถทำงานร่วมกับเซิร์ฟเวอร์ Language Server Protocol (LSP) เพื่อใช้ diagnostics เป็น feedback สำหรับ agent * * * [บิวท์อิน](https://opencode.ai/docs/th/lsp/#%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 มาพร้อมกับเซิร์ฟเวอร์ 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` (`xcode` บน macOS) | | svelte | .svelte | ติดตั้งอัตโนมัติสำหรับโครงการ Svelte | | terraform | .tf, .tfvars | ติดตั้งอัตโนมัติจากรุ่น GitHub | | tinymist | .typ, .typc | ติดตั้งอัตโนมัติจากรุ่น GitHub | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` การพึ่งพาในโครงการ | | vue | .vue | ติดตั้งอัตโนมัติสำหรับโปรเจ็กต์ Vue | | yaml-ls | .yaml, .yml | ติดตั้งเซิร์ฟเวอร์ภาษา Red Hat yaml โดยอัตโนมัติ | | zls | .zig, .zon | `zig` คำสั่งใช้ได้ | LSP ปิดใช้งานเป็นค่าเริ่มต้น เมื่อเปิดใช้งาน เซิร์ฟเวอร์จะเริ่มทำงานเมื่อตรวจพบนามสกุลไฟล์ข้างต้นและเป็นไปตามข้อกำหนด * * * [มันทำงานอย่างไร](https://opencode.ai/docs/th/lsp/#%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) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เมื่อเปิดใช้งาน LSP และ opencode เปิดไฟล์ มันจะ: 1. ตรวจสอบนามสกุลไฟล์กับเซิร์ฟเวอร์ LSP ที่เปิดใช้งานทั้งหมด 2. เริ่มเซิร์ฟเวอร์ LSP ที่เหมาะสมหากยังไม่ได้ทำงาน * * * [แนวทางปฏิบัติที่แนะนำ](https://opencode.ai/docs/th/lsp/#%E0%B9%81%E0%B8%99%E0%B8%A7%E0%B8%97%E0%B8%B2%E0%B8%87%E0%B8%9B%E0%B8%8F%E0%B8%B4%E0%B8%9A%E0%B8%B1%E0%B8%95%E0%B8%B4%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%81%E0%B8%99%E0%B8%B0%E0%B8%99%E0%B8%B3) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- LSP สามารถช่วยให้ agent ค้นหาและแก้ไขปัญหาโดยให้ diagnostics จากเซิร์ฟเวอร์ภาษา สิ่งนี้มีประโยชน์ในบางโปรเจ็กต์ แต่ไม่ได้เป็นผลบวกเสมอไป เซิร์ฟเวอร์ภาษาอาจไม่ตรงกับสถานะโปรเจ็กต์ ใช้หน่วยความจำมาก แตกต่างกันตามเวอร์ชันหรือโปรเจ็กต์ และทำให้เวิร์กโฟลว์ของ agent ช้าลง ในหลายโปรเจ็กต์ การให้ agent รัน lint, typecheck หรือเครื่องมือ CLI สำหรับ diagnostics อื่นโดยตรงจะดีกว่า เพราะข้อผิดพลาดจะถูกส่งกลับเข้า loop ของ agent โดยไม่มีข้อแลกเปลี่ยนเหล่านี้ ระบุคำสั่งเหล่านี้ไว้ในไฟล์คำแนะนำ เช่น `AGENTS.md` หรือ skills เพื่อให้ agent รู้ว่าต้องรันอะไร เปิดใช้งาน LSP เมื่อโปรเจ็กต์ของคุณได้ประโยชน์จาก feedback เพิ่มเติมของเซิร์ฟเวอร์ภาษา * * * [กำหนดค่า](https://opencode.ai/docs/th/lsp/#%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%84%E0%B9%88%E0%B8%B2) ---------------------------------------------------------------------------------------------------------------------- คุณสามารถเปิดใช้งานและปรับแต่งเซิร์ฟเวอร์ LSP ผ่านส่วน `lsp` ในการกำหนดค่า opencode หากต้องการเปิดใช้งานเซิร์ฟเวอร์ LSP ในตัวทั้งหมด ให้ตั้งค่า `lsp` เป็น `true` { "$schema": "https://opencode.ai/config.json", "lsp": true} ใช้อ็อบเจ็กต์เพื่อให้เซิร์ฟเวอร์ในตัวยังคงเปิดใช้งานอยู่ พร้อมกำหนดค่าการแทนที่หรือเซิร์ฟเวอร์แบบกำหนดเอง { "$schema": "https://opencode.ai/config.json", "lsp": {}} เซิร์ฟเวอร์ LSP แต่ละเซิร์ฟเวอร์รองรับสิ่งต่อไปนี้: | คุณสมบัติ | พิมพ์ | คำอธิบาย | | --- | --- | --- | | `disabled` | บูลีน | ตั้งค่านี้เป็น `true` เพื่อปิดการใช้งานเซิร์ฟเวอร์ LSP | | `command` | สตริง\[\] | คำสั่งเพื่อเริ่มต้นเซิร์ฟเวอร์ LSP | | `extensions` | สตริง\[\] | นามสกุลไฟล์ที่เซิร์ฟเวอร์ LSP นี้ควรจัดการ | | `env` | วัตถุ | ตัวแปรสภาพแวดล้อมที่จะตั้งค่าเมื่อเริ่มต้นเซิร์ฟเวอร์ | | `initialization` | วัตถุ | ตัวเลือกการเริ่มต้นที่จะส่งไปยังเซิร์ฟเวอร์ LSP | ลองดูตัวอย่างบางส่วน * * * ### [ตัวแปรสภาพแวดล้อม](https://opencode.ai/docs/th/lsp/#%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) ใช้คุณสมบัติ `env` เพื่อตั้งค่าตัวแปรสภาพแวดล้อมเมื่อเริ่มต้นเซิร์ฟเวอร์ LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [ตัวเลือกการเริ่มต้น](https://opencode.ai/docs/th/lsp/#%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%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%95%E0%B9%89%E0%B8%99) ใช้คุณสมบัติ `initialization` เพื่อส่งตัวเลือกการเริ่มต้นไปยังเซิร์ฟเวอร์ LSP นี่คือการตั้งค่าเฉพาะเซิร์ฟเวอร์ที่ส่งระหว่างคำขอ LSP `initialize`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [ปิดการใช้งานเซิร์ฟเวอร์ LSP](https://opencode.ai/docs/th/lsp/#%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%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-lsp) หากละเว้น `lsp` เซิร์ฟเวอร์ LSP ทั้งหมดจะถูกปิดใช้งาน หากการกำหนดค่าอื่นเปิดใช้งาน LSP ไว้ ให้ตั้งค่า `lsp` เป็น `false` เพื่อปิดใช้งานเซิร์ฟเวอร์ LSP ทั้งหมด: { "$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/th/lsp/#%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-lsp-%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) คุณสามารถเพิ่มเซิร์ฟเวอร์ LSP แบบกำหนดเองได้โดยระบุคำสั่งและนามสกุลไฟล์: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [ข้อมูลเพิ่มเติม](https://opencode.ai/docs/th/lsp/#%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5%E0%B9%80%E0%B8%9E%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B9%80%E0%B8%95%E0%B8%B4%E0%B8%A1) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [PHP อินเทเลฟินส์](https://opencode.ai/docs/th/lsp/#php-%E0%B8%AD%E0%B8%B4%E0%B8%99%E0%B9%80%E0%B8%97%E0%B9%80%E0%B8%A5%E0%B8%9F%E0%B8%B4%E0%B8%99%E0%B8%AA%E0%B9%8C) PHP Intelephense นำเสนอคุณสมบัติระดับพรีเมียมผ่านรหัสลิขสิทธิ์ คุณสามารถระบุรหัสสัญญาอนุญาตได้โดยการวาง (เท่านั้น) รหัสในไฟล์ข้อความที่: * บน macOS/Linux: `$HOME/intelephense/license.txt` * บน Windows: `%USERPROFILE%/intelephense/license.txt` ไฟล์ควรมีเฉพาะรหัสลิขสิทธิ์โดยไม่มีเนื้อหาเพิ่มเติม --- # الأدوات المخصصة | 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. --- # الإضافات | 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 [Skip to content](https://opencode.ai/docs/th/permissions/#_top) สิทธิ์ ====== ควบคุมการดำเนินการที่ต้องได้รับการอนุมัติจึงจะรันได้ OpenCode ใช้การกำหนดค่า `permission` เพื่อตัดสินใจว่าการดำเนินการที่กำหนดควรทำงานโดยอัตโนมัติ แจ้งให้คุณทราบ หรือถูกบล็อก ตั้งแต่ `v1.1.1` การกำหนดค่าบูลีนแบบเดิม `tools` เลิกใช้แล้วและได้รวมเข้ากับ `permission` แล้ว การกำหนดค่า `tools` แบบเก่ายังคงรองรับความเข้ากันได้แบบย้อนหลัง * * * [การดำเนินการ](https://opencode.ai/docs/th/permissions/#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%94%E0%B8%B3%E0%B9%80%E0%B8%99%E0%B8%B4%E0%B8%99%E0%B8%81%E0%B8%B2%E0%B8%A3) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- กฎการอนุญาตแต่ละข้อจะแก้ไขเป็นข้อใดข้อหนึ่งต่อไปนี้ * `"allow"` — ทำงานโดยไม่ได้รับการอนุมัติ * `"ask"` — พร้อมท์สำหรับการอนุมัติ * `"deny"` — บล็อกการกระทำ * * * [การกำหนดค่า](https://opencode.ai/docs/th/permissions/#%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) ------------------------------------------------------------------------------------------------------------------------------------------------------------ คุณสามารถตั้งค่าการอนุญาตทั่วโลก (ด้วย `*`) และแทนที่เครื่องมือเฉพาะ { "$schema": "https://opencode.ai/config.json", "permission": { "*": "ask", "bash": "allow", "edit": "deny" }} คุณยังสามารถตั้งค่าการอนุญาตทั้งหมดพร้อมกันได้: { "$schema": "https://opencode.ai/config.json", "permission": "allow"} * * * [กฎแบบละเอียด (ไวยากรณ์ของวัตถุ)](https://opencode.ai/docs/th/permissions/#%E0%B8%81%E0%B8%8E%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%A5%E0%B8%B0%E0%B9%80%E0%B8%AD%E0%B8%B5%E0%B8%A2%E0%B8%94-%E0%B9%84%E0%B8%A7%E0%B8%A2%E0%B8%B2%E0%B8%81%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%A7%E0%B8%B1%E0%B8%95%E0%B8%96%E0%B8%B8) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ สำหรับการอนุญาตส่วนใหญ่ คุณสามารถใช้ออบเจ็กต์เพื่อปรับใช้การดำเนินการต่างๆ ตามอินพุตของเครื่องมือได้ { "$schema": "https://opencode.ai/config.json", "permission": { "bash": { "*": "ask", "git *": "allow", "npm *": "allow", "rm *": "deny", "grep *": "allow" }, "edit": { "*": "deny", "packages/web/src/content/docs/*.mdx": "allow" } }} กฎจะได้รับการประเมินโดยการจับคู่รูปแบบ โดย **กฎการจับคู่สุดท้ายจะชนะ** รูปแบบทั่วไปคือการใส่กฎ catch-all `"*"` ก่อน และใส่กฎที่เฉพาะเจาะจงมากขึ้นหลังจากนั้น ### [สัญลักษณ์แทน](https://opencode.ai/docs/th/permissions/#%E0%B8%AA%E0%B8%B1%E0%B8%8D%E0%B8%A5%E0%B8%B1%E0%B8%81%E0%B8%A9%E0%B8%93%E0%B9%8C%E0%B9%81%E0%B8%97%E0%B8%99) รูปแบบการอนุญาตใช้การจับคู่ไวด์การ์ดแบบง่าย: * `*` จับคู่อักขระใดๆ ตั้งแต่ศูนย์ขึ้นไป * `?` ตรงกับอักขระหนึ่งตัวเท่านั้น * อักขระอื่นๆ ทั้งหมดตรงกันอย่างแท้จริง ### [การขยายโฮมไดเร็กทอรี](https://opencode.ai/docs/th/permissions/#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%82%E0%B8%A2%E0%B8%B2%E0%B8%A2%E0%B9%82%E0%B8%AE%E0%B8%A1%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) คุณสามารถใช้ `~` หรือ `$HOME` ที่จุดเริ่มต้นของรูปแบบเพื่ออ้างอิงโฮมไดเร็กตอรี่ของคุณ สิ่งนี้มีประโยชน์อย่างยิ่งสำหรับกฎของ [`external_directory`](https://opencode.ai/docs/th/permissions/#external-directories) * `~/projects/*` -> `/Users/username/projects/*` * `$HOME/projects/*` -> `/Users/username/projects/*` * `~` -> `/Users/username` ### [ไดเรกทอรีภายนอก](https://opencode.ai/docs/th/permissions/#%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%A0%E0%B8%B2%E0%B8%A2%E0%B8%99%E0%B8%AD%E0%B8%81) ใช้ `external_directory` เพื่ออนุญาตการเรียกใช้เครื่องมือที่สัมผัสเส้นทางนอกไดเร็กทอรีการทำงานที่ OpenCode เริ่มทำงาน สิ่งนี้ใช้ได้กับเครื่องมือใดๆ ที่ใช้เส้นทางเป็นอินพุต (เช่น `read`, `edit`, `glob`, `grep` และคำสั่ง `bash` จำนวนมาก) การขยายบ้าน (เช่น `~/...`) ส่งผลต่อวิธีการเขียนรูปแบบเท่านั้น ไม่ได้ทำให้เส้นทางภายนอกเป็นส่วนหนึ่งของพื้นที่ทำงานปัจจุบัน ดังนั้นเส้นทางภายนอกไดเรกทอรีการทำงานยังต้องได้รับอนุญาตผ่าน `external_directory` ตัวอย่างเช่น อนุญาตให้เข้าถึงทุกสิ่งภายใต้ `~/projects/personal/`: { "$schema": "https://opencode.ai/config.json", "permission": { "external_directory": { "~/projects/personal/**": "allow" } }} ไดเร็กทอรีใดๆ ที่ได้รับอนุญาตที่นี่จะสืบทอดค่าเริ่มต้นเดียวกันกับพื้นที่ทำงานปัจจุบัน เนื่องจาก [`read` มีค่าเริ่มต้นเป็น `allow`](https://opencode.ai/docs/th/permissions/#defaults) การอ่านจึงได้รับอนุญาตสำหรับรายการภายใต้ `external_directory` เว้นแต่จะถูกแทนที่ เพิ่มกฎที่ชัดเจนเมื่อควรจำกัดเครื่องมือในเส้นทางเหล่านี้ เช่น การบล็อกการแก้ไขในขณะที่ยังคงอ่านอยู่: { "$schema": "https://opencode.ai/config.json", "permission": { "external_directory": { "~/projects/personal/**": "allow" }, "edit": { "~/projects/personal/**": "deny" } }} ให้รายการมุ่งเน้นไปที่เส้นทางที่เชื่อถือได้ และเลเยอร์อนุญาตหรือปฏิเสธกฎเพิ่มเติมตามที่จำเป็นสำหรับเครื่องมืออื่นๆ (เช่น `bash`) * * * [สิทธิ์ที่มีอยู่](https://opencode.ai/docs/th/permissions/#%E0%B8%AA%E0%B8%B4%E0%B8%97%E0%B8%98%E0%B8%B4%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) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- สิทธิ์ของ OpenCode จะกำหนดไว้ตามชื่อเครื่องมือ พร้อมด้วย guardrails อีก 2-3 คน: * `read` — อ่านไฟล์ (ตรงกับเส้นทางของไฟล์) * `edit` — การแก้ไขไฟล์ทั้งหมด (ครอบคลุมถึง `edit`, `write`, `patch`) * `glob` — ไฟล์ globbing (ตรงกับรูปแบบ glob) * `grep` — การค้นหาเนื้อหา (ตรงกับรูปแบบ regex) * `bash` — การรันคำสั่ง shell (ตรงกับคำสั่งที่แยกวิเคราะห์เช่น `git status --porcelain`) * `task` — การเปิดตัวตัวแทนย่อย (ตรงกับประเภทตัวแทนย่อย) * `skill` — กำลังโหลดทักษะ (ตรงกับชื่อทักษะ) * `lsp` — กำลังเรียกใช้คำสั่ง LSP (ปัจจุบันยังไม่ละเอียด) * `webfetch` — กำลังดึง URL (ตรงกับ URL) * `websearch` — การค้นหาเว็บ (ตรงกับข้อความค้นหา) * `external_directory` — ทริกเกอร์เมื่อเครื่องมือแตะเส้นทางนอกไดเร็กทอรีการทำงานของโปรเจ็กต์ * `doom_loop` — ทริกเกอร์เมื่อมีการเรียกใช้เครื่องมือเดียวกันซ้ำ 3 ครั้งโดยมีอินพุตเหมือนกัน * * * [ค่าเริ่มต้น](https://opencode.ai/docs/th/permissions/#%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 จะเริ่มต้นจากค่าเริ่มต้นที่อนุญาต: * การอนุญาตส่วนใหญ่มีค่าเริ่มต้นเป็น `"allow"` * `doom_loop` และ `external_directory` มีค่าเริ่มต้นเป็น `"ask"` * `read` คือ `"allow"` แต่ไฟล์ `.env` ถูกปฏิเสธโดยค่าเริ่มต้น: { "permission": { "read": { "*": "allow", "*.env": "deny", "*.env.*": "deny", "*.env.example": "allow" } }} * * * [สิ่งที่ “ถาม” ทำ](https://opencode.ai/docs/th/permissions/#%E0%B8%AA%E0%B8%B4%E0%B9%88%E0%B8%87%E0%B8%97%E0%B8%B5%E0%B9%88-%E0%B8%96%E0%B8%B2%E0%B8%A1-%E0%B8%97%E0%B8%B3) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เมื่อ OpenCode แจ้งให้อนุมัติ UI จะเสนอผลลัพธ์สามประการ: * `once` — อนุมัติเพียงคำขอนี้ * `always` — อนุมัติคำขอในอนาคตที่ตรงกับรูปแบบที่แนะนำ (สำหรับส่วนที่เหลือของเซสชัน OpenCode ปัจจุบัน) * `reject` — ปฏิเสธคำขอ ชุดรูปแบบที่ `always` จะอนุมัตินั้นมาจากเครื่องมือ (เช่น โดยทั่วไปการอนุมัติ bash จะกำหนดไวท์ลิสต์คำนำหน้าคำสั่งที่ปลอดภัย เช่น `git status*`) * * * [ตัวแทน](https://opencode.ai/docs/th/permissions/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%97%E0%B8%99) ---------------------------------------------------------------------------------------------------------- คุณสามารถแทนที่สิทธิ์ต่อตัวแทนได้ สิทธิ์ของตัวแทนจะผสานเข้ากับการกำหนดค่าส่วนกลาง และกฎของตัวแทนจะมีความสำคัญกว่า [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/agents#permissions) เกี่ยวกับการอนุญาตของตัวแทน { "$schema": "https://opencode.ai/config.json", "permission": { "bash": { "*": "ask", "git *": "allow", "git commit *": "deny", "git push *": "deny", "grep *": "allow" } }, "agent": { "build": { "permission": { "bash": { "*": "ask", "git *": "allow", "git commit *": "ask", "git push *": "deny", "grep *": "allow" } } } }} คุณยังสามารถกำหนดค่าการอนุญาตตัวแทนใน Markdown ได้: ---description: Code review without editsmode: subagentpermission: edit: deny bash: ask webfetch: deny--- Only analyze code and suggest changes. --- # Темы | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/themes/#_top) Темы ==== Выберите встроенную тему или определите свою собственную. С помощью opencode вы можете выбрать одну из нескольких встроенных тем, использовать тему, которая адаптируется к теме вашего терминала, или определить свою собственную тему. По умолчанию opencode использует нашу собственную тему `opencode`. * * * [Требования к терминалу](https://opencode.ai/docs/ru/themes/#%D1%82%D1%80%D0%B5%D0%B1%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-%D0%BA-%D1%82%D0%B5%D1%80%D0%BC%D0%B8%D0%BD%D0%B0%D0%BB%D1%83) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Чтобы темы корректно отображались в полной цветовой палитре, ваш терминал должен поддерживать **truecolor** (24-битный цвет). Большинство современных терминалов поддерживают это по умолчанию, но вам может потребоваться включить его: * **Проверьте поддержку**: запустите `echo $COLORTERM` — должен появиться `truecolor` или `24bit`. * **Включить truecolor**: установите переменную среды `COLORTERM=truecolor` в профиле shell. * **Совместимость терминала**: убедитесь, что ваш эмулятор терминала поддерживает 24-битный цвет (большинство современных терминалов, таких как iTerm2, Alacritty, Kitty, Windows Terminal и последние версии GNOME Terminal, поддерживают). Без поддержки truecolor темы могут отображаться с пониженной точностью цветопередачи или вернуться к ближайшему приближению к 256 цветам. * * * [Встроенные темы](https://opencode.ai/docs/ru/themes/#%D0%B2%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5-%D1%82%D0%B5%D0%BC%D1%8B) --------------------------------------------------------------------------------------------------------------------------------------------- opencode поставляется с несколькими встроенными темами. | Имя | Описание | | --- | --- | | `system` | Адаптируется к фоновому цвету терминала | | `tokyonight` | Based on the [tokyonight](https://github.com/folke/tokyonight.nvim)
theme | | `everforest` | Based on the [Everforest](https://github.com/sainnhe/everforest)
theme | | `ayu` | Based on the [Ayu](https://github.com/ayu-theme)
dark theme | | `catppuccin` | Based on the [Catppuccin](https://github.com/catppuccin)
theme | | `catppuccin-macchiato` | Based on the [Catppuccin](https://github.com/catppuccin)
theme | | `gruvbox` | Based on the [Gruvbox](https://github.com/morhetz/gruvbox)
theme | | `kanagawa` | Based on the [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
theme | | `nord` | Based on the [Nord](https://github.com/nordtheme/nord)
theme | | `matrix` | Хакерская тема: зеленый на черном | | `one-dark` | Based on the [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark theme | И более того, мы постоянно добавляем новые темы. * * * [Системная тема](https://opencode.ai/docs/ru/themes/#%D1%81%D0%B8%D1%81%D1%82%D0%B5%D0%BC%D0%BD%D0%B0%D1%8F-%D1%82%D0%B5%D0%BC%D0%B0) -------------------------------------------------------------------------------------------------------------------------------------- Тема `system` автоматически адаптируется к цветовой схеме вашего терминала. В отличие от традиционных тем, использующих фиксированные цвета, тема _system_: * **Создает шкалу серого**: создает пользовательскую шкалу серого на основе цвета фона вашего терминала, обеспечивая оптимальный контраст. * **Использует цвета ANSI**: использует стандартные цвета ANSI (0–15) для подсветки синтаксиса и элементов пользовательского интерфейса, которые соответствуют цветовой палитре вашего терминала. * **Сохраняет настройки терминала по умолчанию**: использует `none` для цветов текста и фона, чтобы сохранить естественный вид вашего терминала. Системная тема предназначена для пользователей, которые: * Хотите, чтобы opencode соответствовал внешнему виду их терминала * Используйте пользовательские цветовые схемы терминала * Предпочитайте единообразный вид для всех терминальных приложений. * * * [Использование темы](https://opencode.ai/docs/ru/themes/#%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%82%D0%B5%D0%BC%D1%8B) ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Вы можете выбрать тему, вызвав выбор темы с помощью команды `/theme`. Или вы можете указать это в файле [tui.json](https://opencode.ai/docs/config#tui) . { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Пользовательские темы](https://opencode.ai/docs/ru/themes/#%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%82%D0%B5%D0%BC%D1%8B) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- opencode поддерживает гибкую систему тем на основе JSON, которая позволяет пользователям легко создавать и настраивать темы. * * * ### [Иерархия](https://opencode.ai/docs/ru/themes/#%D0%B8%D0%B5%D1%80%D0%B0%D1%80%D1%85%D0%B8%D1%8F) Темы загружаются из нескольких каталогов в следующем порядке: более поздние каталоги переопределяют предыдущие: 1. **Встроенные темы** – они встроены в двоичный файл. 2. **Каталог конфигурации пользователя** – определяется в `~/.config/opencode/themes/*.json` или `$XDG_CONFIG_HOME/opencode/themes/*.json`. 3. **Корневой каталог проекта** – определено в `/.opencode/themes/*.json`. 4. **Текущий рабочий каталог** – определено в `./.opencode/themes/*.json`. Если несколько каталогов содержат тему с одинаковым именем, будет использоваться тема из каталога с более высоким приоритетом. * * * ### [Создание темы](https://opencode.ai/docs/ru/themes/#%D1%81%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5-%D1%82%D0%B5%D0%BC%D1%8B) Чтобы создать собственную тему, создайте файл JSON в одном из каталогов темы. Для глобальных тем: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json Для тем проекта: mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [Формат JSON](https://opencode.ai/docs/ru/themes/#%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82-json) В темах используется гибкий формат JSON с поддержкой: * **Шестнадцатеричные цвета**: `"#ffffff"` * **Цвета ANSI**: `3` (0–255). * **Ссылки на цвета**: `"primary"` или пользовательские определения. * **Темный/светлый варианты**: `{"dark": "#000", "light": "#fff"}` * **Нет цвета**: `"none"` — используется цвет терминала по умолчанию или прозрачный. * * * ### [Определения цвета](https://opencode.ai/docs/ru/themes/#%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F-%D1%86%D0%B2%D0%B5%D1%82%D0%B0) Раздел `defs` является необязательным и позволяет вам определять повторно используемые цвета, на которые можно ссылаться в теме. * * * ### [Настройки терминала по умолчанию](https://opencode.ai/docs/ru/themes/#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B8-%D1%82%D0%B5%D1%80%D0%BC%D0%B8%D0%BD%D0%B0%D0%BB%D0%B0-%D0%BF%D0%BE-%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E) Специальное значение `"none"` можно использовать для любого цвета, чтобы наследовать цвет терминала по умолчанию. Это особенно полезно для создания тем, которые органично сочетаются с цветовой схемой вашего терминала: * `"text": "none"` — использует цвет переднего плана терминала по умолчанию. * `"background": "none"` — использует цвет фона терминала по умолчанию. * * * ### [Пример](https://opencode.ai/docs/ru/themes/#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80) Вот пример пользовательской темы: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Themes | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/themes/#_top) Themes ====== Wybierz wbudowany motyw lub zdefiniuj własny. Dzięki opencode możesz wybrać jeden z kilku wbudowanych motywów, użyć motywu, który dostosowuje się do motywu terminala lub zdefiniować własny, niestandardowy motyw. Domyślnie opencode używa naszego własnego motywu `opencode`. * * * [Wymagania terminala](https://opencode.ai/docs/pl/themes/#wymagania-terminala) ------------------------------------------------------------------------------- Aby motywy wyświetlały się poprawnie z pełną paletą kolorów, Twój terminal musi obsługiwać **truecolor** (kolor 24-bitowy). Większość nowoczesnych terminali domyślnie obsługuje tę opcję, ale może być konieczne jej włączenie: * **Sprawdź wsparcie**: Uruchom `echo $COLORTERM` - powinno wypisać `truecolor` lub `24bit` * **Włącz truecolor**: Ustaw zmienną środowiskową `COLORTERM=truecolor` w swoim profilu shell * **Zgodność terminala**: Upewnij się, że emulator terminala obsługuje 24-bitowy kolor (większość nowoczesnych terminali, takich jak iTerm2, Alacritty, Kitty, Windows Terminal i najnowsze wersje terminala GNOME tak) Bez obsługi Truecolor motywy mogą pojawiać się ze zmniejszoną dokładnością kolorów lub wracać do najbliższego przybliżenia 256 kolorów. * * * [Wbudowane motywy](https://opencode.ai/docs/pl/themes/#wbudowane-motywy) ------------------------------------------------------------------------- opencode ma kilka wbudowanych motywów. | Name | Description | | --- | --- | | `system` | Dopasowuje się do koloru tła terminala | | `tokyonight` | Na podstawie motywu [tokyonight](https://github.com/folke/tokyonight.nvim) | | `everforest` | Na podstawie motywu [Everforest](https://github.com/sainnhe/everforest) | | `ayu` | Na podstawie ciemnego motywu [Ayu](https://github.com/ayu-theme) | | `catppuccin` | Na podstawie motywu [Catppuccin](https://github.com/catppuccin) | | `catppuccin-macchiato` | Na podstawie motywu [Catppuccin](https://github.com/catppuccin) | | `gruvbox` | Na podstawie motywu [Gruvbox](https://github.com/morhetz/gruvbox) | | `kanagawa` | Na podstawie motywu [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | | `nord` | Na podstawie motywu [Nord](https://github.com/nordtheme/nord) | | `matrix` | Hacker-style green on black theme | | `one-dark` | Na podstawie ciemnego motywu [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | Co więcej, stale dodajemy nowe motywy. * * * [Motyw systemowy](https://opencode.ai/docs/pl/themes/#motyw-systemowy) ----------------------------------------------------------------------- Motyw `system` został zaprojektowany tak, aby automatycznie dostosowywał się do schematu kolorów terminala. W przeciwieństwie do tradycyjnych motywów, które używają stałych kolorów, motyw _system_: * **Generuje skalę szarości**: Tworzy niestandardową skalę szarości w oparciu o kolor tła terminala, zapewniając optymalny kontrast. * **Używa kolorów ANSI**: Wykorzystuje standardowe kolory ANSI (0-15) do podświetlania składni i elementów interfejsu użytkownika, które odpowiadają palecie kolorów terminala. * **Zachowuje ustawienia domyślne terminala**: Używa `none` dla kolorów tekstu i tła, aby zachować natywny wygląd terminala. Motyw systemu przeznaczony jest dla użytkowników, którzy: * Chcą, aby OpenCode pasował do wyglądu ich terminala * Używają niestandardowych schematów kolorów terminala * Preferują spójny wygląd we wszystkich aplikacjach terminalowych * * * [Używanie motywu](https://opencode.ai/docs/pl/themes/#u%C5%BCywanie-motywu) ---------------------------------------------------------------------------- Możesz wybrać motyw, wywołując opcję wyboru motywu za pomocą polecenia `/theme`. Możesz też określić to w `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Motywy niestandardowe](https://opencode.ai/docs/pl/themes/#motywy-niestandardowe) ----------------------------------------------------------------------------------- opencode obsługuje elastyczny system motywów oparty na JSON, który pozwala użytkownikom łatwo tworzyć i dostosowywać motywy. * * * ### [Hierarchia](https://opencode.ai/docs/pl/themes/#hierarchia) Motywy są ładowane z wielu katalogów w następującej kolejności, przy czym późniejsze katalogi zastępują wcześniejsze: 1. **Wbudowane motywy** – są osadzone w formacie binarnym 2. **Katalog konfiguracji użytkownika** - Zdefiniowany w `~/.config/opencode/themes/*.json` lub `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Katalog główny projektu** - Zdefiniowany w `/.opencode/themes/*.json` 4. **Bieżący katalog roboczy** - Zdefiniowany w `./.opencode/themes/*.json` Jeśli wiele katalogów zawiera motyw o tej samej nazwie, zostanie użyty motyw z katalogu o wyższym priorytecie. * * * ### [Tworzenie motywu](https://opencode.ai/docs/pl/themes/#tworzenie-motywu) Aby utworzyć niestandardowy motyw, utwórz plik JSON w jednym z katalogów motywów. W przypadku motywów dla całego użytkownika: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json Oraz dla tematów specyficznych dla projektu. mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [Format JSON](https://opencode.ai/docs/pl/themes/#format-json) Motywy korzystają z elastycznego formatu JSON z obsługą: * **Kolorów Hex**: `"#ffffff"` * **Kolorów ANSI**: `3` (0-255) * **Referencji kolorów**: `"primary"` lub definicje niestandardowe * **Wariantów Ciemny/Jasny**: `{"dark": "#000", "light": "#fff"}` * **Braku koloru**: `"none"` - Używa domyślnego koloru terminala lub przezroczystości * * * ### [Definicje kolorów](https://opencode.ai/docs/pl/themes/#definicje-kolor%C3%B3w) Sekcja `defs` jest opcjonalna i pozwala zdefiniować kolory wielokrotnego użytku, do których można się odwoływać w motywie. * * * ### [Domyślne ustawienia terminala](https://opencode.ai/docs/pl/themes/#domy%C5%9Blne-ustawienia-terminala) Wartość specjalna `"none"` może zostać użyta dla dowolnego koloru, aby przejąć domyślny kolor terminala. Jest to szczególnie przydatne do tworzenia motywów, które płynnie komponują się ze schematem kolorów terminala: * `"text": "none"` - Używa domyślnego koloru pierwszego planu terminala * `"background": "none"` - Używa domyślnego koloru tła terminala * * * ### [Przykład](https://opencode.ai/docs/pl/themes/#przyk%C5%82ad) Oto przykład niestandardowego motywu: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Temi | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/themes/#_top) Temi ==== Seleziona un tema integrato o definiscine uno tuo. Con OpenCode puoi scegliere tra diversi temi integrati, usare un tema che si adatta al tema del tuo terminale oppure definire un tema personalizzato. Per impostazione predefinita, OpenCode usa il tema `opencode`. * * * [Requisiti del terminale](https://opencode.ai/docs/it/themes/#requisiti-del-terminale) --------------------------------------------------------------------------------------- Per visualizzare correttamente i temi con l’intera palette, il terminale deve supportare **truecolor** (colore a 24 bit). La maggior parte dei terminali moderni lo supporta di default, ma potrebbe essere necessario abilitarlo: * **Verifica supporto**: esegui `echo $COLORTERM` - dovrebbe stampare `truecolor` o `24bit` * **Abilita truecolor**: imposta la variabile d’ambiente `COLORTERM=truecolor` nel profilo della shell * **Compatibilità del terminale**: assicurati che l’emulatore supporti il colore a 24 bit (la maggior parte dei terminali moderni come iTerm2, Alacritty, Kitty, Windows Terminal e le versioni recenti di GNOME Terminal) Senza truecolor, i temi potrebbero apparire con colori meno accurati oppure fare fallback alla migliore approssimazione a 256 colori. * * * [Temi integrati](https://opencode.ai/docs/it/themes/#temi-integrati) --------------------------------------------------------------------- OpenCode include diversi temi integrati. | Nome | Descrizione | | --- | --- | | `system` | Si adatta al colore di sfondo del terminale | | `tokyonight` | Basato sul tema [Tokyonight](https://github.com/folke/tokyonight.nvim) | | `everforest` | Basato sul tema [Everforest](https://github.com/sainnhe/everforest) | | `ayu` | Basato sul tema scuro [Ayu](https://github.com/ayu-theme) | | `catppuccin` | Basato sul tema [Catppuccin](https://github.com/catppuccin) | | `catppuccin-macchiato` | Basato sul tema [Catppuccin](https://github.com/catppuccin) | | `gruvbox` | Basato sul tema [Gruvbox](https://github.com/morhetz/gruvbox) | | `kanagawa` | Basato sul tema [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | | `nord` | Basato sul tema [Nord](https://github.com/nordtheme/nord) | | `matrix` | Tema verde su nero in stile hacker | | `one-dark` | Basato sul tema Dark [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | E altri ancora: aggiungiamo costantemente nuovi temi. * * * [Tema di sistema](https://opencode.ai/docs/it/themes/#tema-di-sistema) ----------------------------------------------------------------------- Il tema `system` è progettato per adattarsi automaticamente allo schema colori del tuo terminale. A differenza dei temi tradizionali con colori fissi, il tema _system_: * **Genera una scala di grigi**: crea una scala di grigi personalizzata in base al colore di sfondo del terminale, garantendo un contrasto ottimale. * **Usa colori ANSI**: sfrutta i colori ANSI standard (0-15) per evidenziazione della sintassi ed elementi UI, rispettando la palette del terminale. * **Preserva i default del terminale**: usa `none` per testo e sfondo per mantenere l’aspetto nativo del terminale. Il tema di sistema è pensato per chi: * Vuole che OpenCode corrisponda all’aspetto del terminale * Usa schemi colori personalizzati del terminale * Preferisce un aspetto coerente tra tutte le applicazioni da terminale * * * [Usare un tema](https://opencode.ai/docs/it/themes/#usare-un-tema) ------------------------------------------------------------------- Puoi selezionare un tema aprendo la selezione temi con il comando `/theme`. In alternativa, puoi specificarlo in `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Temi personalizzati](https://opencode.ai/docs/it/themes/#temi-personalizzati) ------------------------------------------------------------------------------- OpenCode supporta un sistema di temi flessibile basato su JSON che permette di creare e personalizzare temi facilmente. * * * ### [Gerarchia](https://opencode.ai/docs/it/themes/#gerarchia) I temi vengono caricati da più directory nel seguente ordine, dove le directory successive sovrascrivono le precedenti: 1. **Temi integrati** - incorporati nel binario 2. **Directory di configurazione utente** - in `~/.config/opencode/themes/*.json` o `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Directory root del progetto** - in `/.opencode/themes/*.json` 4. **Directory di lavoro corrente** - in `./.opencode/themes/*.json` Se più directory contengono un tema con lo stesso nome, verrà usato il tema della directory con priorità più alta. * * * ### [Creare un tema](https://opencode.ai/docs/it/themes/#creare-un-tema) Per creare un tema personalizzato, crea un file JSON in una delle directory dei temi. Per temi a livello utente: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json E per temi specifici del progetto. mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [Formato JSON](https://opencode.ai/docs/it/themes/#formato-json) I temi usano un formato JSON flessibile che supporta: * **Colori hex**: `"#ffffff"` * **Colori ANSI**: `3` (0-255) * **Riferimenti colore**: `"primary"` o definizioni personalizzate * **Varianti scuro/chiaro**: `{"dark": "#000", "light": "#fff"}` * **Nessun colore**: `"none"` - usa il colore predefinito del terminale o trasparente * * * ### [Definizioni dei colori](https://opencode.ai/docs/it/themes/#definizioni-dei-colori) La sezione `defs` è opzionale e ti permette di definire colori riutilizzabili che possono essere referenziati nel tema. * * * ### [Valori predefiniti del terminale](https://opencode.ai/docs/it/themes/#valori-predefiniti-del-terminale) Il valore speciale `"none"` può essere usato per qualunque colore per ereditare il colore predefinito del terminale. È particolarmente utile per creare temi che si fondono con lo schema colori del terminale: * `"text": "none"` - usa il colore del testo predefinito del terminale * `"background": "none"` - usa il colore di sfondo predefinito del terminale * * * ### [Esempio](https://opencode.ai/docs/it/themes/#esempio) Ecco un esempio di tema personalizzato: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # ธีมส์ | OpenCode [Skip to content](https://opencode.ai/docs/th/themes/#_top) ธีมส์ ===== เลือกธีมในตัวหรือกำหนดธีมของคุณเอง ด้วย OpenCode คุณสามารถเลือกจากหนึ่งในธีมที่มีอยู่แล้วภายใน ใช้ธีมที่ปรับให้เข้ากับธีม terminal ของคุณ หรือกำหนดธีมที่คุณกำหนดเองได้ ตามค่าเริ่มต้น OpenCode จะใช้ธีม `opencode` ของเราเอง * * * [ข้อกำหนดของ terminal](https://opencode.ai/docs/th/themes/#%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%82%E0%B8%AD%E0%B8%87-terminal) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เพื่อให้ธีมแสดงได้อย่างถูกต้องด้วยชุดสีทั้งหมด terminal ของคุณต้องรองรับ **truecolor** (สี 24 บิต) terminal สมัยใหม่ส่วนใหญ่จะรองรับสิ่งนี้ตามค่าเริ่มต้น แต่คุณอาจต้องเปิดใช้งาน: * **ตรวจสอบการสนับสนุน**: เรียกใช้ `echo $COLORTERM` - ​​ควรส่งออก `truecolor` หรือ `24bit` * **เปิดใช้งานสีจริง**: ตั้งค่าตัวแปรสภาพแวดล้อม `COLORTERM=truecolor` ในโปรไฟล์ shell ของคุณ * **ความเข้ากันได้ของ terminal**: ตรวจสอบให้แน่ใจว่าโปรแกรมจำลอง terminal ของคุณรองรับสี 24 บิต (terminal ที่ทันสมัยที่สุด เช่น iTerm2, Alacritty, Kitty, Windows Terminal และ GNOME Terminal do เวอร์ชันล่าสุด) หากไม่รองรับสีจริง ธีมอาจปรากฏขึ้นโดยมีความแม่นยำของสีลดลงหรือกลับไปใช้การประมาณสี 256 สีที่ใกล้ที่สุด * * * [ธีมในตัว](https://opencode.ai/docs/th/themes/#%E0%B8%98%E0%B8%B5%E0%B8%A1%E0%B9%83%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7) ------------------------------------------------------------------------------------------------------------------------- OpenCode มาพร้อมกับธีมในตัวหลายธีม | ชื่อ | คำอธิบาย | | --- | --- | | `system` | ปรับให้เข้ากับสีพื้นหลังของ terminal ของคุณ | | `tokyonight` | อิงตามธีมของ [Tokyonight](https://github.com/folke/tokyonight.nvim) | | `everforest` | อิงตามธีม [Everforest](https://github.com/sainnhe/everforest) | | `ayu` | อิงตามธีมสีเข้มของ [Ayu](https://github.com/ayu-theme) | | `catppuccin` | อิงตามธีม [Catppuccin](https://github.com/catppuccin) | | `catppuccin-macchiato` | อิงตามธีม [Catppuccin](https://github.com/catppuccin) | | `gruvbox` | อิงตามธีม [Gruvbox](https://github.com/morhetz/gruvbox) | | `kanagawa` | อิงตามธีมของ [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | | `nord` | อิงตามธีม [Nord](https://github.com/nordtheme/nord) | | `matrix` | ธีมสีเขียวสไตล์แฮ็กเกอร์บนสีดำ | | `one-dark` | อิงตามธีม [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark | และยิ่งไปกว่านั้น เรายังเพิ่มธีมใหม่ๆ อย่างต่อเนื่อง * * * [ธีมของระบบ](https://opencode.ai/docs/th/themes/#%E0%B8%98%E0%B8%B5%E0%B8%A1%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A) --------------------------------------------------------------------------------------------------------------------------------------------- ธีม `system` ได้รับการออกแบบให้ปรับให้เข้ากับโทนสีของเครื่อง terminal ของคุณโดยอัตโนมัติ ไม่เหมือนกับธีมดั้งเดิมที่ใช้สีคงที่ ธีม _system_: * **สร้างระดับสีเทา**: สร้างระดับสีเทาแบบกำหนดเองตามสีพื้นหลังของ terminal ของคุณ เพื่อให้มั่นใจว่ามีคอนทราสต์ที่เหมาะสมที่สุด * **ใช้สี ANSI**: ใช้ประโยชน์จากสี ANSI มาตรฐาน (0-15) สำหรับการเน้นไวยากรณ์และองค์ประกอบ UI ซึ่งเคารพชุดสีของ terminal ของคุณ * **รักษาค่าเริ่มต้นของ terminal**: ใช้ `none` สำหรับสีข้อความและพื้นหลัง เพื่อรักษารูปลักษณ์ดั้งเดิมของ terminal ของคุณ ธีมของระบบมีไว้สำหรับผู้ใช้ที่: * ต้องการให้ OpenCode ตรงกับรูปลักษณ์ของ terminal * ใช้โครงร่างสี terminal แบบกำหนดเอง * ต้องการรูปลักษณ์ที่สอดคล้องกันในแอปพลิเคชัน terminal ทั้งหมด * * * [การใช้ธีม](https://opencode.ai/docs/th/themes/#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%98%E0%B8%B5%E0%B8%A1) ----------------------------------------------------------------------------------------------------------------------------------- คุณสามารถเลือกธีมได้โดยเปิดการเลือกธีมขึ้นมาด้วยคำสั่ง `/theme` หรือคุณสามารถระบุได้ใน `tui.json` { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [ธีมที่กำหนดเอง](https://opencode.ai/docs/th/themes/#%E0%B8%98%E0%B8%B5%E0%B8%A1%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 รองรับระบบธีมที่ใช้ JSON ที่ยืดหยุ่น ซึ่งช่วยให้ผู้ใช้สามารถสร้างและปรับแต่งธีมได้อย่างง่ายดาย * * * ### [ลำดับชั้น](https://opencode.ai/docs/th/themes/#%E0%B8%A5%E0%B8%B3%E0%B8%94%E0%B8%B1%E0%B8%9A%E0%B8%8A%E0%B8%B1%E0%B9%89%E0%B8%99) ธีมจะถูกโหลดจากหลายไดเร็กทอรีตามลำดับต่อไปนี้ โดยไดเร็กทอรีรุ่นหลังจะแทนที่ไดเร็กทอรีก่อนหน้า: 1. **ธีมในตัว** - ธีมเหล่านี้ฝังอยู่ในไบนารี 2. **ไดเรกทอรีกำหนดค่าผู้ใช้** - กำหนดใน `~/.config/opencode/themes/*.json` หรือ `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **ไดเรกทอรีรากของโครงการ** - กำหนดไว้ใน `/.opencode/themes/*.json` 4. **ไดเร็กทอรีการทำงานปัจจุบัน** - กำหนดใน `./.opencode/themes/*.json` หากหลายไดเร็กทอรีมีธีมที่มีชื่อเดียวกัน ธีมจากไดเร็กทอรีที่มีลำดับความสำคัญสูงกว่าจะถูกนำมาใช้ * * * ### [การสร้างธีม](https://opencode.ai/docs/th/themes/#%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%B8%98%E0%B8%B5%E0%B8%A1) หากต้องการสร้างธีมที่กำหนดเอง ให้สร้างไฟล์ JSON ในไดเร็กทอรีธีมรายการใดรายการหนึ่ง สำหรับธีมทั้งผู้ใช้: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json และสำหรับธีมเฉพาะโครงการ mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON รูปแบบ](https://opencode.ai/docs/th/themes/#json-%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B9%81%E0%B8%9A%E0%B8%9A) ธีมใช้รูปแบบ JSON ที่ยืดหยุ่นพร้อมรองรับ: * **สีฐานสิบหก**: `"#ffffff"` * **ANSI สี**: `3` (0-255) * **การอ้างอิงสี**: `"primary"` หรือคำจำกัดความที่กำหนดเอง * **Dark/light ตัวแปร**: `{"dark": "#000", "light": "#fff"}` * **ไม่มีสี**: `"none"` - ​​ใช้สีเริ่มต้นของ terminal หรือโปร่งใส * * * ### [คำจำกัดความของสี](https://opencode.ai/docs/th/themes/#%E0%B8%84%E0%B8%B3%E0%B8%88%E0%B8%B3%E0%B8%81%E0%B8%B1%E0%B8%94%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%AA%E0%B8%B5) ส่วน `defs` เป็นทางเลือก และอนุญาตให้คุณกำหนดสีที่ใช้ซ้ำได้ซึ่งสามารถอ้างอิงในธีมได้ * * * ### [ค่าเริ่มต้นของ terminal](https://opencode.ai/docs/th/themes/#%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%E0%B8%82%E0%B8%AD%E0%B8%87-terminal) ค่าพิเศษ `"none"` สามารถใช้กับสีใดก็ได้เพื่อสืบทอดสีเริ่มต้นของ terminal สิ่งนี้มีประโยชน์อย่างยิ่งสำหรับการสร้างธีมที่ผสมผสานอย่างลงตัวกับโทนสีของ terminal ของคุณ: * `"text": "none"` - ​​ใช้สีพื้นหน้าเริ่มต้นของ terminal * `"background": "none"` - ​​ใช้สีพื้นหลังเริ่มต้นของ terminal * * * ### [ตัวอย่าง](https://opencode.ai/docs/th/themes/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87) นี่คือตัวอย่างของธีมที่กำหนดเอง: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # 外掛 | 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` 陣列將被忽略。 --- # 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. --- # 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. --- # ปลั๊กอิน | 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` จะถูกละเว้นในกรณีนี้ --- # 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`. --- # 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/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` в этом случае игнорируется. --- # السمات | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/themes/#_top) السمات ====== اختر سمة مدمجة أو عرّف سمة خاصة بك. مع OpenCode يمكنك الاختيار من بين عدة سمات مدمجة، أو استخدام سمة تتكيّف مع سمة terminal لديك، أو تعريف سمة مخصصة خاصة بك. افتراضيًا، يستخدم OpenCode سمتنا `opencode`. * * * [متطلبات terminal](https://opencode.ai/docs/ar/themes/#%D9%85%D8%AA%D8%B7%D9%84%D8%A8%D8%A7%D8%AA-terminal) ------------------------------------------------------------------------------------------------------------ لكي تُعرض السمات بشكل صحيح مع لوحة ألوانها الكاملة، يجب أن يدعم terminal لديك **truecolor** (ألوان 24-بت). تدعم معظم تطبيقات terminal الحديثة ذلك افتراضيًا، لكن قد تحتاج إلى تفعيله: * **التحقق من الدعم**: شغّل `echo $COLORTERM` - يجب أن يطبع `truecolor` أو `24bit` * **تفعيل truecolor**: اضبط متغير البيئة `COLORTERM=truecolor` في ملف إعدادات shell * **توافق terminal**: تأكد من أن محاكي terminal يدعم ألوان 24-بت (معظم تطبيقات terminal الحديثة مثل iTerm2 وAlacritty وKitty وWindows Terminal والإصدارات الحديثة من GNOME Terminal تدعم ذلك) بدون دعم truecolor، قد تظهر السمات بدقة ألوان أقل أو تعود إلى أقرب تقريب ضمن 256 لونًا. * * * [السمات المدمجة](https://opencode.ai/docs/ar/themes/#%D8%A7%D9%84%D8%B3%D9%85%D8%A7%D8%AA-%D8%A7%D9%84%D9%85%D8%AF%D9%85%D8%AC%D8%A9) -------------------------------------------------------------------------------------------------------------------------------------- يأتي OpenCode مع عدة سمات مدمجة. | الاسم | الوصف | | --- | --- | | `system` | يتكيّف مع لون خلفية terminal لديك | | `tokyonight` | مبني على سمة [Tokyonight](https://github.com/folke/tokyonight.nvim) | | `everforest` | مبني على سمة [Everforest](https://github.com/sainnhe/everforest) | | `ayu` | مبني على السمة الداكنة [Ayu](https://github.com/ayu-theme) | | `catppuccin` | مبني على سمة [Catppuccin](https://github.com/catppuccin) | | `catppuccin-macchiato` | مبني على سمة [Catppuccin](https://github.com/catppuccin) | | `gruvbox` | مبني على سمة [Gruvbox](https://github.com/morhetz/gruvbox) | | `kanagawa` | مبني على سمة [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | | `nord` | مبني على سمة [Nord](https://github.com/nordtheme/nord) | | `matrix` | سمة خضراء على أسود بأسلوب الهاكر | | `one-dark` | مبني على السمة الداكنة [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | وغير ذلك؛ نضيف سمات جديدة باستمرار. * * * [سمة النظام](https://opencode.ai/docs/ar/themes/#%D8%B3%D9%85%D8%A9-%D8%A7%D9%84%D9%86%D8%B8%D8%A7%D9%85) ---------------------------------------------------------------------------------------------------------- صُممت سمة `system` لتتكيّف تلقائيًا مع مخطط ألوان terminal لديك. وعلى عكس السمات التقليدية التي تستخدم ألوانًا ثابتة، فإن سمة _system_: * **توليد تدرج رمادي**: تنشئ تدرجًا رماديًا مخصصًا اعتمادًا على لون خلفية terminal لديك، بما يضمن أفضل تباين. * **استخدام ألوان ANSI**: تستفيد من ألوان ANSI القياسية (0-15) لإبراز الصياغة وعناصر الواجهة، والتي تحترم لوحة ألوان terminal لديك. * **الحفاظ على افتراضيات terminal**: تستخدم `none` لألوان النص والخلفية للحفاظ على مظهر terminal الأصلي. سمة النظام مناسبة للمستخدمين الذين: * يريدون أن يطابق OpenCode مظهر terminal لديهم * يستخدمون مخططات ألوان مخصصة لـ terminal * يفضلون مظهرًا متسقًا عبر جميع تطبيقات terminal * * * [استخدام سمة](https://opencode.ai/docs/ar/themes/#%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85-%D8%B3%D9%85%D8%A9) ----------------------------------------------------------------------------------------------------------------- يمكنك اختيار سمة بفتح منتقي السمات باستخدام الأمر `/theme`. أو يمكنك تحديدها في [الضبط](https://opencode.ai/docs/config) . { "$schema": "https://opencode.ai/config.json", "theme": "tokyonight"} * * * [سمات مخصصة](https://opencode.ai/docs/ar/themes/#%D8%B3%D9%85%D8%A7%D8%AA-%D9%85%D8%AE%D8%B5%D8%B5%D8%A9) ---------------------------------------------------------------------------------------------------------- يدعم OpenCode نظام سمات مرنًا قائمًا على JSON يتيح للمستخدمين إنشاء السمات وتخصيصها بسهولة. * * * ### [التسلسل الهرمي](https://opencode.ai/docs/ar/themes/#%D8%A7%D9%84%D8%AA%D8%B3%D9%84%D8%B3%D9%84-%D8%A7%D9%84%D9%87%D8%B1%D9%85%D9%8A) تُحمَّل السمات من عدة مجلدات بالترتيب التالي، حيث تتجاوز المجلدات اللاحقة المجلدات السابقة: 1. **السمات المدمجة** - تكون مضمنة داخل الملف التنفيذي 2. **مجلد ضبط المستخدم** - معرّف في `~/.config/opencode/themes/*.json` أو `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **مجلد جذر المشروع** - معرّف في `/.opencode/themes/*.json` 4. **مجلد العمل الحالي** - معرّف في `./.opencode/themes/*.json` إذا احتوت عدة مجلدات على سمة بالاسم نفسه، فستُستخدم السمة من المجلد ذي الأولوية الأعلى. * * * ### [إنشاء سمة](https://opencode.ai/docs/ar/themes/#%D8%A5%D9%86%D8%B4%D8%A7%D8%A1-%D8%B3%D9%85%D8%A9) لإنشاء سمة مخصصة، أنشئ ملف JSON في أحد مجلدات السمات. للسمات على مستوى المستخدم: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json وللسمات الخاصة بالمشروع: mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [تنسيق JSON](https://opencode.ai/docs/ar/themes/#%D8%AA%D9%86%D8%B3%D9%8A%D9%82-json) تستخدم السمات تنسيق JSON مرنًا مع دعم لـ: * **ألوان سداسية عشرية**: `"#ffffff"` * **ألوان ANSI**: `3` (0-255) * **مراجع الألوان**: `"primary"` أو تعريفات مخصصة * **متغيرات داكن/فاتح**: `{"dark": "#000", "light": "#fff"}` * **بدون لون**: `"none"` - يستخدم اللون الافتراضي لـ terminal أو يكون شفافًا * * * ### [تعريفات الألوان](https://opencode.ai/docs/ar/themes/#%D8%AA%D8%B9%D8%B1%D9%8A%D9%81%D8%A7%D8%AA-%D8%A7%D9%84%D8%A3%D9%84%D9%88%D8%A7%D9%86) قسم `defs` اختياري، ويتيح لك تعريف ألوان قابلة لإعادة الاستخدام يمكن الإشارة إليها داخل السمة. * * * ### [افتراضيات terminal](https://opencode.ai/docs/ar/themes/#%D8%A7%D9%81%D8%AA%D8%B1%D8%A7%D8%B6%D9%8A%D8%A7%D8%AA-terminal) يمكن استخدام القيمة الخاصة `"none"` لأي لون لوراثة اللون الافتراضي لـ terminal. هذا مفيد خصوصًا لإنشاء سمات تمتزج بسلاسة مع مخطط ألوان terminal لديك: * `"text": "none"` - يستخدم لون المقدمة الافتراضي لـ terminal * `"background": "none"` - يستخدم لون الخلفية الافتراضي لـ terminal * * * ### [مثال](https://opencode.ai/docs/ar/themes/#%D9%85%D8%AB%D8%A7%D9%84) إليك مثالًا على سمة مخصصة: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Ecossistema | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/ecosystem/#_top) Ecossistema =========== Projetos e integrações construídos com o OpenCode. Uma coleção de projetos da comunidade construídos sobre o OpenCode. Você também pode conferir [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) e [opencode.cafe](https://opencode.cafe/) , uma comunidade que agrega o ecossistema e a comunidade. * * * [Plugins](https://opencode.ai/docs/pt-br/ecosystem/#plugins) ------------------------------------------------------------- | Nome | Descrição | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | Execute automaticamente sessões do OpenCode em sandboxes isoladas do Daytona com sincronização git e pré-visualizações ao vivo | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Injete automaticamente cabeçalhos de sessão Helicone para agrupamento de requisições | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Auto-injetar tipos TypeScript/Svelte em leituras de arquivos com ferramentas de busca | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Use sua assinatura ChatGPT Plus/Pro em vez de créditos de API | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Use seu plano Gemini existente em vez de cobrança de API | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Use os modelos gratuitos do Antigravity em vez de cobrança de API | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Isolamento de devcontainer multi-branch com clones rasos e portas atribuídas automaticamente | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Plugin Google Antigravity OAuth, com suporte para Google Search e manuseio de API mais robusto | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Otimize o uso de tokens podando saídas de ferramentas obsoletas | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | Oculte segredos/PII em marcadores estilo VibeGuard antes de chamadas LLM; restaure localmente | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Adicione suporte nativo de pesquisa na web para provedores suportados com estilo fundamentado no Google | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Permite que agentes de IA executem processos em segundo plano em um PTY, enviando entrada interativa para eles. | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Instruções para comandos de shell não interativos - evita travamentos de operações dependentes de TTY | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Acompanhe o uso do OpenCode com Wakatime | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Limpe tabelas markdown produzidas por LLMs | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | Edição Fast Apply, busca de código WarpGrep e compactação de contexto via Morph | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agentes em segundo plano, ferramentas LSP/AST/MCP pré-construídas, agentes curados, compatível com Claude Code | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | Notificações de desktop e alertas sonoros para sessões do OpenCode | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Notificações de desktop e alertas sonoros para eventos de permissão, conclusão e erro | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Nomeação automática de sessões Zellij com suporte de IA com base no contexto do OpenCode | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Permite que agentes do OpenCode carreguem prompts sob demanda com descoberta e injeção de habilidades | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Memória persistente entre sessões usando Supermemory | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Revisão de plano interativa com anotação visual e compartilhamento privado/offline | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Estenda opencode /commands em um poderoso sistema de orquestração com controle de fluxo granular | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Agende trabalhos recorrentes usando launchd (Mac) ou systemd (Linux) com sintaxe cron | | [micode](https://github.com/vtemian/micode) | Fluxo de trabalho Estruturado Brainstorm → Planejar → Implementar com continuidade de sessão | | [octto](https://github.com/vtemian/octto) | UI interativa do navegador para brainstorming de IA com formulários de múltiplas perguntas | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Agentes em segundo plano estilo Claude Code com delegação assíncrona e persistência de contexto | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Notificações nativas do OS para OpenCode – saiba quando as tarefas são concluídas | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Conjunto de orquestração multi-agente – 16 componentes, uma instalação | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Worktrees git sem atrito para OpenCode | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | Rastreie e depure seus agentes de IA com o Sentry AI Monitoring | * * * [Projetos](https://opencode.ai/docs/pt-br/ecosystem/#projetos) --------------------------------------------------------------- | Nome | Descrição | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | Bot do Discord para controlar sessões do OpenCode, construído sobre o SDK | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Plugin Neovim para prompts cientes do editor, construído sobre a API | | [portal](https://github.com/hosenur/portal) | UI web mobile-first para OpenCode sobre Tailscale/VPN | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Template para construir plugins do OpenCode | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim para OpenCode - um agente de codificação IA baseado em terminal | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Provedor Vercel AI SDK para usar OpenCode via @opencode-ai/sdk | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | Aplicativo Web / Desktop e Extensão do VS Code para OpenCode | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Plugin Obsidian que incorpora OpenCode na UI do Obsidian | | [OpenWork](https://github.com/different-ai/openwork) | Uma alternativa de código aberto ao Claude Cowork, alimentada pelo OpenCode | | [ocx](https://github.com/kdcokenny/ocx) | Gerenciador de extensões OpenCode com perfis portáteis e isolados. | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Aplicativo Desktop, Web, Mobile e Cliente Remoto para OpenCode | * * * [Agentes](https://opencode.ai/docs/pt-br/ecosystem/#agentes) ------------------------------------------------------------- | Nome | Descrição | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | Agentes e comandos de IA modulares para desenvolvimento estruturado | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Configurações, prompts, agentes e plugins para fluxos de trabalho aprimorados | --- # Themes | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/themes/#_top) Themes ====== Waehle ein eingebautes Theme oder erstelle eins. Mit OpenCode kannst du ein eingebautes Theme waehlen, ein an dein Terminal angepasstes Theme nutzen oder ein eigenes Theme definieren. Standardmaessig verwendet OpenCode das `opencode`\-Theme. * * * [Terminal-Anforderungen](https://opencode.ai/docs/de/themes/#terminal-anforderungen) ------------------------------------------------------------------------------------- Damit Themes mit voller Farbpalette korrekt angezeigt werden, muss dein Terminal **truecolor** (24-Bit-Farben) unterstuetzen. Die meisten modernen Terminals koennen das bereits, eventuell musst du es aber aktivieren: * **Support pruefen**: Fuehre `echo $COLORTERM` aus - erwartet ist `truecolor` oder `24bit` * **Truecolor aktivieren**: Setze in deinem Shell-Profil `COLORTERM=truecolor` * **Terminal-Kompatibilitaet**: Stelle sicher, dass dein Terminal-Emulator 24-Bit-Farben unterstuetzt Ohne truecolor werden Farben weniger exakt dargestellt oder auf eine 256-Farben-Naeherung reduziert. * * * [Eingebaute Themes](https://opencode.ai/docs/de/themes/#eingebaute-themes) --------------------------------------------------------------------------- OpenCode liefert mehrere eingebaute Themes mit. | Name | Description | | --- | --- | | `system` | Adapts to your terminal’s background color | | `tokyonight` | Based on the [Tokyonight](https://github.com/folke/tokyonight.nvim)
theme | | `everforest` | Based on the [Everforest](https://github.com/sainnhe/everforest)
theme | | `ayu` | Based on the [Ayu](https://github.com/ayu-theme)
dark theme | | `catppuccin` | Based on the [Catppuccin](https://github.com/catppuccin)
theme | | `catppuccin-macchiato` | Based on the [Catppuccin](https://github.com/catppuccin)
theme | | `gruvbox` | Based on the [Gruvbox](https://github.com/morhetz/gruvbox)
theme | | `kanagawa` | Based on the [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
theme | | `nord` | Based on the [Nord](https://github.com/nordtheme/nord)
theme | | `matrix` | Hacker-style green on black theme | | `one-dark` | Based on the [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark theme | Und es kommen laufend weitere dazu. * * * [System-Theme](https://opencode.ai/docs/de/themes/#system-theme) ----------------------------------------------------------------- Das `system`\-Theme passt sich automatisch an das Farbschema deines Terminals an. Im Gegensatz zu Themes mit festen Farben gilt beim _system_\-Theme: * **Generiert Graustufen**: Basierend auf deiner Terminal-Hintergrundfarbe fuer guten Kontrast * **Nutzt ANSI-Farben**: Verwendet Standardfarben (0-15), die dein Terminalschema respektieren * **Behaelt Terminal-Defaults**: Verwendet `none` fuer Text und Hintergruende Das System-Theme ist ideal fuer Nutzer, die: * OpenCode optisch ans Terminal anpassen wollen * eigene Terminal-Farbschemata nutzen * ein konsistentes Erscheinungsbild in Terminal-Apps bevorzugen * * * [Theme verwenden](https://opencode.ai/docs/de/themes/#theme-verwenden) ----------------------------------------------------------------------- Du kannst ein Theme ueber `/theme` auswaehlen oder direkt in der [Konfiguration](https://opencode.ai/docs/config) setzen. { "$schema": "https://opencode.ai/config.json", "theme": "tokyonight"} * * * [Eigene Themes](https://opencode.ai/docs/de/themes/#eigene-themes) ------------------------------------------------------------------- OpenCode unterstuetzt ein flexibles JSON-basiertes Theme-System. Damit lassen sich Themes einfach erstellen und anpassen. * * * ### [Hierarchie](https://opencode.ai/docs/de/themes/#hierarchie) Themes werden aus mehreren Verzeichnissen in folgender Reihenfolge geladen, wobei spaetere Verzeichnisse fruehere ueberschreiben: 1. **Eingebaute Themes** - Diese sind im Binary eingebettet 2. **Benutzer-Config-Verzeichnis** - Definiert in `~/.config/opencode/themes/*.json` oder `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Projekt-Root-Verzeichnis** - Definiert in `/.opencode/themes/*.json` 4. **Aktuelles Arbeitsverzeichnis** - Definiert in `./.opencode/themes/*.json` Wenn mehrere Verzeichnisse ein Theme mit demselben Namen enthalten, wird das Theme aus dem Verzeichnis mit der hoeheren Prioritaet verwendet. * * * ### [Theme erstellen](https://opencode.ai/docs/de/themes/#theme-erstellen) Um ein eigenes Theme zu erstellen, lege eine JSON-Datei in einem der Theme-Verzeichnisse an. Fuer benutzerweite Themes: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json Und fuer projektspezifische Themes: mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON-Format](https://opencode.ai/docs/de/themes/#json-format) Themes nutzen ein flexibles JSON-Format mit Unterstuetzung fuer: * **Hex-Farben**: `"#ffffff"` * **ANSI-Farben**: `3` (0-255) * **Farbreferenzen**: `"primary"` oder eigene Definitionen * **Dunkel/Hell-Varianten**: `{"dark": "#000", "light": "#fff"}` * **Keine Farbe**: `"none"` - Nutzt die Standardfarbe des Terminals oder transparent * * * ### [Farbdefinitionen](https://opencode.ai/docs/de/themes/#farbdefinitionen) Der `defs`\-Abschnitt ist optional und erlaubt es dir, wiederverwendbare Farben zu definieren, die im Theme referenziert werden koennen. * * * ### [Terminal-Standardwerte](https://opencode.ai/docs/de/themes/#terminal-standardwerte) Der spezielle Wert `"none"` kann fuer jede Farbe verwendet werden, um die Standardfarbe des Terminals zu erben. Das ist besonders nuetzlich, um Themes zu erstellen, die nahtlos mit deinem Terminal-Farbschema verschmelzen: * `"text": "none"` - Nutzt die Standard-Vordergrundfarbe des Terminals * `"background": "none"` - Nutzt die Standard-Hintergrundfarbe des Terminals * * * ### [Beispiel](https://opencode.ai/docs/de/themes/#beispiel) Hier ist ein Beispiel fuer ein eigenes Theme: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # テーマ | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/themes/#_top) テーマ === 組み込みのテーマを選択するか、独自のテーマを定義します。 OpenCode を使用すると、いくつかの組み込みテーマから 1 つを選択したり、ターミナルのテーマに適合するテーマを使用したり、独自のカスタムテーマを定義したりできます。 デフォルトでは、OpenCode は独自の `opencode` テーマを使用します。 * * * [ターミナル要件](https://opencode.ai/docs/ja/themes/#%E3%82%BF%E3%83%BC%E3%83%9F%E3%83%8A%E3%83%AB%E8%A6%81%E4%BB%B6) --------------------------------------------------------------------------------------------------------------- テーマをフルカラーパレットで正しく表示するには、ターミナルが **Truecolor** (24 ビットカラー) をサポートしている必要があります。最新のターミナルのほとんどはデフォルトでこれをサポートしていますが、有効にする必要がある場合があります。 * **サポートを確認してください**: `echo $COLORTERM` を実行します - `truecolor` または `24bit` が出力されるはずです * **Truecolor を有効にする**: シェルプロファイルで環境変数 `COLORTERM=truecolor` を設定します。 * **ターミナルの互換性**: ターミナルエミュレータが 24 ビットカラーをサポートしていることを確認してください (iTerm2、Alacritty、Kitty、Windows Terminal、および GNOME Terminal の最新バージョンなどのほとんどの最新のターミナルはサポートしています)。 Truecolor のサポートがないと、テーマの色の精度が低下したり、最も近い 256 色の近似値に戻ったりする可能性があります。 * * * [組み込みのテーマ](https://opencode.ai/docs/ja/themes/#%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF%E3%81%AE%E3%83%86%E3%83%BC%E3%83%9E) ------------------------------------------------------------------------------------------------------------------------- OpenCode にはいくつかの組み込みテーマが付属しています。 | Name | Description | | --- | --- | | `system` | Adapts to your terminal’s background color | | `tokyonight` | Based on the [Tokyonight](https://github.com/folke/tokyonight.nvim)
theme | | `everforest` | Based on the [Everforest](https://github.com/sainnhe/everforest)
theme | | `ayu` | Based on the [Ayu](https://github.com/ayu-theme)
dark theme | | `catppuccin` | Based on the [Catppuccin](https://github.com/catppuccin)
theme | | `catppuccin-macchiato` | Based on the [Catppuccin](https://github.com/catppuccin)
theme | | `gruvbox` | Based on the [Gruvbox](https://github.com/morhetz/gruvbox)
theme | | `kanagawa` | Based on the [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
theme | | `nord` | Based on the [Nord](https://github.com/nordtheme/nord)
theme | | `matrix` | Hacker-style green on black theme | | `one-dark` | Based on the [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark theme | さらに、新しいテーマも常に追加されています。 * * * [システムテーマ](https://opencode.ai/docs/ja/themes/#%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0%E3%83%86%E3%83%BC%E3%83%9E) --------------------------------------------------------------------------------------------------------------- `system` テーマは、ターミナルのカラースキームに自動的に適応するように設計されています。固定色を使用する従来のテーマとは異なり、_system_ テーマは次のようになります。 * **グレースケールを生成**: ターミナルの背景色に基づいてカスタムグレースケールを作成し、最適なコントラストを確保します。 * **ANSI カラーを使用**: 構文の強調表示と UI 要素に標準の ANSI カラー (0 ~ 15) を利用し、ターミナルのカラーパレットを尊重します。 * **ターミナルのデフォルトを維持**: テキストと背景の色に `none` を使用して、ターミナルのネイティブの外観を維持します。 システムテーマは、次のようなユーザーを対象としています。 * OpenCode をターミナルの外観と一致させたい * カスタムターミナルのカラースキームを使用する * すべてのターミナルアプリケーションにわたって一貫した外観を好む * * * [テーマの使用](https://opencode.ai/docs/ja/themes/#%E3%83%86%E3%83%BC%E3%83%9E%E3%81%AE%E4%BD%BF%E7%94%A8) ----------------------------------------------------------------------------------------------------- テーマを選択するには、`/theme` コマンドでテーマ選択を表示します。または、`tui.json` で指定することもできます。 { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [カスタムテーマ](https://opencode.ai/docs/ja/themes/#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%86%E3%83%BC%E3%83%9E) --------------------------------------------------------------------------------------------------------------- OpenCode は、ユーザーがテーマを簡単に作成およびカスタマイズできる柔軟な JSON ベースのテーマシステムをサポートしています。 * * * ### [優先順位](https://opencode.ai/docs/ja/themes/#%E5%84%AA%E5%85%88%E9%A0%86%E4%BD%8D) テーマは複数のディレクトリから次の順序でロードされ、後のディレクトリが前のディレクトリをオーバーライドします。 1. **組み込みテーマ** - これらはバイナリに埋め込まれています 2. **ユーザー設定ディレクトリ** - `~/.config/opencode/themes/*.json` または `$XDG_CONFIG_HOME/opencode/themes/*.json` で定義されます 3. **プロジェクトのルートディレクトリ** - `/.opencode/themes/*.json` で定義されます。 4. **現在の作業ディレクトリ** - `./.opencode/themes/*.json` で定義 複数のディレクトリに同じ名前のテーマが含まれている場合は、優先度の高いディレクトリのテーマが使用されます。 * * * ### [テーマの作成](https://opencode.ai/docs/ja/themes/#%E3%83%86%E3%83%BC%E3%83%9E%E3%81%AE%E4%BD%9C%E6%88%90) カスタムテーマを作成するには、テーマディレクトリの 1 つに JSON ファイルを作成します。 ユーザー全体のテーマの場合: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json そしてプロジェクト固有のテーマについても。 mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON 形式](https://opencode.ai/docs/ja/themes/#json-%E5%BD%A2%E5%BC%8F) テーマは、以下をサポートする柔軟な JSON 形式を使用します。 * **16 進数の色**: `"#ffffff"` * **ANSI カラー**: `3` (0-255) * **色の参照**: `"primary"` またはカスタム定義 * **ダーク/ライトのバリエーション**: `{"dark": "#000", "light": "#fff"}` * **色なし**: `"none"` - ターミナルのデフォルトの色または透明を使用します。 * * * ### [色の定義](https://opencode.ai/docs/ja/themes/#%E8%89%B2%E3%81%AE%E5%AE%9A%E7%BE%A9) `defs` セクションはオプションであり、テーマ内で参照できる再利用可能な色を定義できます。 * * * ### [ターミナルのデフォルト](https://opencode.ai/docs/ja/themes/#%E3%82%BF%E3%83%BC%E3%83%9F%E3%83%8A%E3%83%AB%E3%81%AE%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88) 特別な値 `"none"` を任意の色に使用して、ターミナルのデフォルトの色を継承できます。これは、ターミナルの配色とシームレスに融合するテーマを作成する場合に特に便利です。 * `"text": "none"` - ターミナルのデフォルトの前景色を使用します * `"background": "none"` - ターミナルのデフォルトの背景色を使用します * * * ### [例](https://opencode.ai/docs/ja/themes/#%E4%BE%8B) カスタムテーマの例を次に示します。 { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} * * * [カスタムテーマ](https://opencode.ai/docs/ja/themes/#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%86%E3%83%BC%E3%83%9E-1) ----------------------------------------------------------------------------------------------------------------- OpenCode は、ユーザーがテーマを簡単に作成およびカスタマイズできる柔軟な JSON ベースのテーマ システムをサポートしています。 * * * ### [階層](https://opencode.ai/docs/ja/themes/#%E9%9A%8E%E5%B1%A4) テーマは複数のディレクトリから次の順序でロードされ、後のディレクトリが前のディレクトリをオーバーライドします。 1. **組み込みテーマ** - これらはバイナリに埋め込まれています 2. **ユーザー設定ディレクトリ** - `~/.config/opencode/themes/*.json` または `$XDG_CONFIG_HOME/opencode/themes/*.json` で定義されます 3. **プロジェクトのルート ディレクトリ** - `/.opencode/themes/*.json` で定義されます。 4. **現在の作業ディレクトリ** - `./.opencode/themes/*.json` で定義 複数のディレクトリに同じ名前のテーマが含まれている場合は、優先度の高いディレクトリのテーマが使用されます。 * * * ### [テーマの作成](https://opencode.ai/docs/ja/themes/#%E3%83%86%E3%83%BC%E3%83%9E%E3%81%AE%E4%BD%9C%E6%88%90-1) カスタム テーマを作成するには、テーマ ディレクトリの 1 つに JSON ファイルを作成します。 ユーザー全体のテーマの場合: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json そしてプロジェクト固有のテーマについても。 mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON形式](https://opencode.ai/docs/ja/themes/#json%E5%BD%A2%E5%BC%8F) テーマは、以下をサポートする柔軟な JSON 形式を使用します。 * **16 進数の色**: `"#ffffff"` * **ANSI カラー**: `3` (0-255) * **色の参照**: `"primary"` またはカスタム定義 * **ダーク/ライトのバリエーション**: `{"dark": "#000", "light": "#fff"}` * **色なし**: `"none"` - terminal のデフォルトの色または透明を使用します。 * * * ### [色の定義](https://opencode.ai/docs/ja/themes/#%E8%89%B2%E3%81%AE%E5%AE%9A%E7%BE%A9-1) `defs` セクションはオプションであり、テーマ内で参照できる再利用可能な色を定義できます。 * * * ### [ターミナルのデフォルト](https://opencode.ai/docs/ja/themes/#%E3%82%BF%E3%83%BC%E3%83%9F%E3%83%8A%E3%83%AB%E3%81%AE%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88-1) 特別な値 `"none"` を任意の色に使用して、terminal のデフォルトの色を継承できます。これは、terminal の配色とシームレスに融合するテーマを作成する場合に特に便利です。 * `"text": "none"` - terminal のデフォルトの前景色を使用します * `"background": "none"` - terminal のデフォルトの背景色を使用します * * * ### [例](https://opencode.ai/docs/ja/themes/#%E4%BE%8B-1) カスタム テーマの例を次に示します。 { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Écosystème | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/ecosystem/#_top) Écosystème ========== Projets et intégrations construits avec OpenCode. Une collection de projets communautaires construits sur OpenCode. Vous pouvez également consulter [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) et [opencode.cafe](https://opencode.cafe/) , une communauté qui regroupe l’écosystème et la communauté. * * * [Extensions](https://opencode.ai/docs/fr/ecosystem/#extensions) ---------------------------------------------------------------- | Nom | Description | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | Exécute automatiquement des sessions OpenCode dans des sandbox Daytona isolées avec synchronisation git et prévisualisations en direct | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Injecte automatiquement les en-têtes de session Helicone pour le regroupement des requêtes | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Injecte automatiquement les types TypeScript/Svelte dans les lectures de fichiers avec des outils de recherche | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Utilise votre abonnement ChatGPT Plus/Pro au lieu de crédits API | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Utilise votre forfait Gemini existant au lieu de la facturation API | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Utilise les modèles gratuits d’Antigravity au lieu de la facturation API | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Isolation de conteneur de développement multi-branches avec clones superficiels et ports attribués automatiquement | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Plugin OAuth Google Antigravity, avec prise en charge de la recherche Google et une gestion d’API plus robuste | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optimise l’utilisation des jetons en élaguant les sorties d’outils obsolètes | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | Masque les secrets/PII par des espaces réservés de style VibeGuard avant les appels LLM ; restaure localement | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Ajoute le support natif de la recherche web pour les fournisseurs pris en charge avec le style Google Grounding | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Permet aux agents IA d’exécuter des processus en arrière-plan dans un PTY et de leur envoyer des entrées interactives. | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Instructions pour les commandes shell non interactives - empêche les blocages dus aux opérations dépendantes du TTY | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Suit l’utilisation d’OpenCode avec Wakatime | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Nettoie les tableaux Markdown produits par les LLM | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | Édition Fast Apply, recherche de code WarpGrep et compaction de contexte via Morph | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agents d’arrière-plan, outils LSP/AST/MCP pré-construits, agents sélectionnés, compatible Claude Code | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | Notifications de bureau et alertes sonores pour les sessions OpenCode | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Notifications de bureau et alertes sonores pour les événements de permission, d’achèvement et d’erreur | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Nommage automatique de session Zellij alimenté par l’IA basé sur le contexte OpenCode | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Permet aux agents OpenCode le chargement différé de prompts à la demande avec découverte et injection de compétences | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Mémoire persistante entre les sessions utilisant Supermemory | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Révision de plan interactive avec annotation visuelle et partage privé/hors ligne | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Étend opencode /commands en un système d’orchestration puissant avec contrôle de flux granulaire | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Planifie des tâches récurrentes en utilisant launchd (Mac) ou systemd (Linux) avec la syntaxe cron | | [micode](https://github.com/vtemian/micode) | Flux de travail structuré Brainstorming → Planification → Implémentation avec continuité de session | | [octto](https://github.com/vtemian/octto) | Interface utilisateur de navigateur interactive pour le brainstorming IA avec des formulaires multi-questions | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Agents d’arrière-plan de style Claude Code avec délégation asynchrone et persistance du contexte | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Notifications natives de l’OS pour OpenCode – sachez quand les tâches sont terminées | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Harnais d’orchestration multi-agents groupé – 16 composants, une installation | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Worktrees git sans friction pour OpenCode | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | Tracez et déboguez vos agents IA avec Sentry AI Monitoring | * * * [Projets](https://opencode.ai/docs/fr/ecosystem/#projets) ---------------------------------------------------------- | Nom | Description | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | Bot Discord pour contrôler les sessions OpenCode, construit sur le SDK | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Plugin Neovim pour des prompts conscients de l’éditeur, construit sur l’API | | [portal](https://github.com/hosenur/portal) | Interface Web mobile-first pour OpenCode via Tailscale/VPN | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Modèle pour créer des plugins OpenCode | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim pour opencode - un agent de codage IA basé sur terminal | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Fournisseur Vercel AI SDK pour utiliser OpenCode via @opencode-ai/sdk | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | Application Web / Bureau et extension VS Code pour OpenCode | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Plugin Obsidian qui intègre OpenCode dans l’interface d’Obsidian | | [OpenWork](https://github.com/different-ai/openwork) | Une alternative open-source à Claude Cowork, propulsée par OpenCode | | [ocx](https://github.com/kdcokenny/ocx) | Gestionnaire d’extensions OpenCode avec profils portables et isolés. | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Application client Bureau, Web, Mobile et Distante pour OpenCode | * * * [Agents](https://opencode.ai/docs/fr/ecosystem/#agents) -------------------------------------------------------- | Nom | Description | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | Agents IA modulaires et commandes pour un développement structuré | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Configs, prompts, agents et plugins pour des flux de travail améliorés | --- # Ekosistem | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/ecosystem/#_top) Ekosistem ========= OpenCode ile geliştirilen projeler ve entegrasyonlar. OpenCode üzerine inşa edilmiş topluluk projeleri koleksiyonu. Ayrıca ekosistemi ve topluluğu bir araya getiren [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) ve [opencode.cafe](https://opencode.cafe/) adreslerine de göz atabilirsiniz. * * * [Eklentiler](https://opencode.ai/docs/tr/ecosystem/#eklentiler) ---------------------------------------------------------------- | İsim | Açıklama | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | OpenCode oturumlarını, git senkronizasyonu ve canlı önizlemelerle izole Daytona sanal alanlarında otomatik olarak çalıştırın | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | İstek gruplaması için Helicone oturum başlıklarını otomatik olarak ekleyin | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Arama araçlarıyla TypeScript/Svelte türlerini dosya okumalarına otomatik olarak enjekte edin | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | API kredisi yerine ChatGPT Plus/Pro aboneliğinizi kullanın | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | API faturalandırması yerine mevcut Gemini planınızı kullanın | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | API faturalandırması yerine Antigravity’nin ücretsiz modellerini kullanın | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Sığ klonlar ve otomatik atanan portlarla çok dallı devcontainer izolasyonu | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Google Arama desteği ve daha sağlam API işleme özelliğiyle Google Antigravity OAuth Eklentisi | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Eski araç çıktılarını budayarak token kullanımını optimize edin | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | LLM çağrılarından önce sırları/kişisel verileri VibeGuard tarzı yer tutucularla gizleyin; yerel olarak geri yükleyin | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Desteklenen sağlayıcılar için Google kaynaklı stil ile yerel web araması desteği ekleyin | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Yapay zeka aracılarının bir PTY’de arka plan işlemlerini çalıştırmasına ve onlara etkileşimli girdi göndermesine olanak tanır | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Etkileşimli olmayan kabuk komutları için talimatlar - TTY bağımlı işlemlerden kaynaklanan takılmaları önler | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Wakatime ile OpenCode kullanımını takip edin | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | LLM’ler tarafından üretilen markdown tablolarını temizleyin | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | Fast Apply düzenleme, WarpGrep kod tabanı araması ve Morph ile bağlam sıkıştırma | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Arka plan aracıları, hazır LSP/AST/MCP araçları, seçilmiş aracılar, Claude Code uyumlu | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | OpenCode oturumları için masaüstü bildirimleri ve sesli uyarılar | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | İzin, tamamlanma ve hata olayları için masaüstü bildirimleri ve sesli uyarılar | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | OpenCode bağlamına dayalı yapay zeka destekli otomatik Zellij oturum isimlendirmesi | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | OpenCode aracılarının, beceri keşfi ve enjeksiyonu ile istemleri talep üzerine tembel yüklemesine (lazy load) izin verin | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Supermemory kullanarak oturumlar arası kalıcı hafıza | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Görsel not alma ve özel/çevrimdışı paylaşım ile etkileşimli plan incelemesi | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | opencode /commands komutlarını, ayrıntılı akış kontrolü ile güçlü bir orkestrasyon sistemine genişletin | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Launchd (Mac) veya systemd (Linux) kullanarak cron sözdizimi ile tekrarlayan işler planlayın | | [micode](https://github.com/vtemian/micode) | Oturum sürekliliği ile Yapılandırılmış Beyin Fırtınası → Planlama → Uygulama iş akışı | | [octto](https://github.com/vtemian/octto) | Çok sorulu formlarla yapay zeka beyin fırtınası için etkileşimli tarayıcı arayüzü | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Asenkron delegasyon ve bağlam kalıcılığına sahip Claude Code tarzı arka plan aracıları | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | OpenCode için yerel işletim sistemi bildirimleri – görevlerin ne zaman tamamlandığını bilin | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Paketlenmiş çoklu aracı orkestrasyon donanımı – 16 bileşen, tek kurulum | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | OpenCode için sıfır sürtünmeli git çalışma ağaçları (worktrees) | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | Sentry AI Monitoring ile yapay zeka aracılarınızı izleyin ve hatalarını ayıklayın | * * * [Projeler](https://opencode.ai/docs/tr/ecosystem/#projeler) ------------------------------------------------------------ | İsim | Açıklama | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | SDK üzerine inşa edilmiş, OpenCode oturumlarını kontrol eden Discord botu | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | API üzerine inşa edilmiş, editör farkındalıklı istemler için Neovim eklentisi | | [portal](https://github.com/hosenur/portal) | Tailscale/VPN üzerinden OpenCode için mobil öncelikli web arayüzü | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | OpenCode eklentileri oluşturmak için şablon | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | opencode için Neovim ön yüzü - terminal tabanlı bir yapay zeka kodlama aracısı | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | @opencode-ai/sdk aracılığıyla OpenCode kullanmak için Vercel AI SDK sağlayıcısı | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | OpenCode için Web / Masaüstü Uygulaması ve VS Code Uzantısı | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | OpenCode’u Obsidian arayüzüne gömen Obsidian eklentisi | | [OpenWork](https://github.com/different-ai/openwork) | OpenCode tarafından desteklenen, Claude Cowork’e açık kaynaklı bir alternatif | | [ocx](https://github.com/kdcokenny/ocx) | Taşınabilir, izole profillere sahip OpenCode eklenti yöneticisi | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | OpenCode için Masaüstü, Web, Mobil ve Uzak İstemci Uygulaması | * * * [Aracılar](https://opencode.ai/docs/tr/ecosystem/#arac%C4%B1lar) ----------------------------------------------------------------- | İsim | Açıklama | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | Yapılandırılmış geliştirme için modüler yapay zeka aracıları ve komutları | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Gelişmiş iş akışları için yapılandırmalar, istemler, aracılar ve eklentiler | --- # Server MCP | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/mcp-servers/#_top) Server MCP ========== Aggiungi strumenti MCP locali e remoti. Puoi aggiungere strumenti esterni a OpenCode usando il _Model Context Protocol_, o MCP. OpenCode supporta sia server locali sia remoti. Una volta aggiunti, gli strumenti MCP sono automaticamente disponibili all’LLM insieme agli strumenti integrati. * * * #### [Avvertenze](https://opencode.ai/docs/it/mcp-servers/#avvertenze) Quando usi un server MCP, aggiunge contenuto al contesto. Questo puo’ crescere rapidamente se hai molti strumenti. Per questo consigliamo di fare attenzione a quali server MCP abiliti. Alcuni server MCP, come il server MCP di GitHub, tendono ad aggiungere molti token e possono facilmente superare il limite di contesto. * * * [Abilita](https://opencode.ai/docs/it/mcp-servers/#abilita) ------------------------------------------------------------ Puoi definire server MCP nella tua [OpenCode Config](https://opencode.ai/docs/config/) sotto `mcp`. Aggiungi ogni MCP con un nome univoco. Puoi riferirti a quell’MCP per nome quando fai prompt all’LLM. { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} Puoi anche disabilitare un server impostando `enabled` a `false`. E’ utile se vuoi disabilitare temporaneamente un server senza rimuoverlo dalla configurazione. * * * ### [Sovrascrivere i default remoti](https://opencode.ai/docs/it/mcp-servers/#sovrascrivere-i-default-remoti) Le organizzazioni possono fornire server MCP predefiniti tramite l’endpoint `.well-known/opencode`. Questi server possono essere disabilitati di default, lasciando agli utenti la possibilita’ di fare opt-in su quelli necessari. Per abilitare un server specifico dalla configurazione remota dell’organizzazione, aggiungilo alla configurazione locale con `enabled: true`: { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} I valori della configurazione locale sovrascrivono i default remoti. Vedi [config precedence](https://opencode.ai/docs/config#precedence-order) per maggiori dettagli. * * * [Locali](https://opencode.ai/docs/it/mcp-servers/#locali) ---------------------------------------------------------- Aggiungi server MCP locali impostando `type` a `"local"` dentro l’oggetto `mcp`. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} Il comando e’ come viene avviato il server MCP locale. Puoi anche passare un elenco di variabili d’ambiente. Per esempio, ecco come aggiungere il server MCP di test [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) . { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} E per usarlo posso aggiungere `use the mcp_everything tool` ai miei prompt. use the mcp_everything tool to add the number 3 and 4 * * * #### [Opzioni](https://opencode.ai/docs/it/mcp-servers/#opzioni) Ecco tutte le opzioni per configurare un server MCP locale. | Opzione | Tipo | Richiesto | Descrizione | | --- | --- | --- | --- | | `type` | String | Y | Tipo di connessione del server MCP, deve essere `"local"`. | | `command` | Array | Y | Comando e argomenti per eseguire il server MCP. | | `environment` | Object | | Variabili d’ambiente da impostare quando si esegue il server. | | `enabled` | Boolean | | Abilita o disabilita il server MCP all’avvio. | | `timeout` | Number | | Timeout in ms per recuperare gli strumenti dal server MCP. Default 5000 (5 secondi). | * * * [Remoti](https://opencode.ai/docs/it/mcp-servers/#remoti) ---------------------------------------------------------- Aggiungi server MCP remoti impostando `type` a `"remote"`. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} `url` e’ l’URL del server MCP remoto e con l’opzione `headers` puoi passare un elenco di header. * * * #### [Opzioni](https://opencode.ai/docs/it/mcp-servers/#opzioni-1) | Opzione | Tipo | Richiesto | Descrizione | | --- | --- | --- | --- | | `type` | String | Y | Tipo di connessione del server MCP, deve essere `"remote"`. | | `url` | String | Y | URL del server MCP remoto. | | `enabled` | Boolean | | Abilita o disabilita il server MCP all’avvio. | | `headers` | Object | | Header da inviare con la richiesta. | | `oauth` | Object | | Configurazione autenticazione OAuth. Vedi sezione [OAuth](https://opencode.ai/docs/it/mcp-servers/#oauth)
sotto. | | `timeout` | Number | | Timeout in ms per recuperare gli strumenti dal server MCP. Default 5000 (5 secondi). | * * * [OAuth](https://opencode.ai/docs/it/mcp-servers/#oauth) -------------------------------------------------------- OpenCode gestisce automaticamente l’autenticazione OAuth per i server MCP remoti. Quando un server richiede autenticazione, OpenCode: 1. Rileva la risposta 401 e avvia il flusso OAuth 2. Usa **Dynamic Client Registration (RFC 7591)** se supportato dal server 3. Memorizza i token in modo sicuro per richieste future * * * ### [Automatico](https://opencode.ai/docs/it/mcp-servers/#automatico) Per la maggior parte dei server MCP con OAuth, non serve alcuna configurazione speciale. Basta configurare il server remoto: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} Se il server richiede autenticazione, OpenCode ti chiedera’ di autenticarti la prima volta che provi a usarlo. In caso contrario, puoi [attivare manualmente il flusso](https://opencode.ai/docs/it/mcp-servers/#authenticating) con `opencode mcp auth `. * * * ### [Pre-registrato](https://opencode.ai/docs/it/mcp-servers/#pre-registrato) Se hai credenziali client dal provider del server MCP, puoi configurarle: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [Autenticazione](https://opencode.ai/docs/it/mcp-servers/#autenticazione) Puoi avviare manualmente l’autenticazione o gestire le credenziali. Autentica con un server MCP specifico: opencode mcp auth my-oauth-server Elenca tutti i server MCP e il loro stato di autenticazione: opencode mcp list Rimuovi credenziali memorizzate: opencode mcp logout my-oauth-server Il comando `mcp auth` aprira’ il browser per l’autorizzazione. Dopo l’autorizzazione, OpenCode memorizzera’ i token in modo sicuro in `~/.local/share/opencode/mcp-auth.json`. * * * #### [Disabilitare OAuth](https://opencode.ai/docs/it/mcp-servers/#disabilitare-oauth) Se vuoi disabilitare l’OAuth automatico per un server (ad esempio per server che usano API key), imposta `oauth` a `false`: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [Opzioni OAuth](https://opencode.ai/docs/it/mcp-servers/#opzioni-oauth) | Opzione | Tipo | Descrizione | | --- | --- | --- | | `oauth` | Object \| false | Oggetto config OAuth, o `false` per disabilitare l’auto-detection di OAuth. | | `clientId` | String | OAuth client ID. Se non fornito, si prova la dynamic client registration. | | `clientSecret` | String | OAuth client secret, se richiesto dal server di autorizzazione. | | `scope` | String | Scope OAuth da richiedere durante l’autorizzazione. | #### [Debug](https://opencode.ai/docs/it/mcp-servers/#debug) Se un server MCP remoto non riesce ad autenticarsi, puoi diagnosticare i problemi con: # View auth status for all OAuth-capable serversopencode mcp auth list # Debug connection and OAuth flow for a specific serveropencode mcp debug my-oauth-server Il comando `mcp debug` mostra lo stato di autenticazione corrente, testa la connettivita’ HTTP e prova il flusso di discovery OAuth. * * * [Gestione](https://opencode.ai/docs/it/mcp-servers/#gestione) -------------------------------------------------------------- I tuoi MCP sono disponibili come strumenti in OpenCode insieme agli strumenti integrati. Quindi puoi gestirli tramite la configurazione OpenCode come qualunque altro strumento. * * * ### [Globale](https://opencode.ai/docs/it/mcp-servers/#globale) Questo significa che puoi abilitarli o disabilitarli globalmente. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} Possiamo anche usare un pattern glob per disabilitare tutti gli MCP corrispondenti. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} Qui stiamo usando il pattern glob `my-mcp*` per disabilitare tutti gli MCP. * * * ### [Per agente](https://opencode.ai/docs/it/mcp-servers/#per-agente) Se hai molti server MCP, potresti volerli abilitare solo per agente e disabilitarli globalmente. Per farlo: 1. Disabilitalo globalmente come strumento. 2. Nella tua [config dell’agente](https://opencode.ai/docs/agents#tools) , abilita il server MCP come strumento. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [Pattern glob](https://opencode.ai/docs/it/mcp-servers/#pattern-glob) Il pattern glob usa semplici regole di globbing: * `*` corrisponde a zero o piu’ caratteri qualsiasi (ad esempio `"my-mcp*"` corrisponde a `my-mcp_search`, `my-mcp_list`, ecc.) * `?` corrisponde esattamente a un carattere * Tutti gli altri caratteri corrispondono letteralmente * * * [Esempi](https://opencode.ai/docs/it/mcp-servers/#esempi) ---------------------------------------------------------- Qui sotto trovi esempi di alcuni server MCP comuni. Puoi inviare una PR se vuoi documentare altri server. * * * ### [Sentry](https://opencode.ai/docs/it/mcp-servers/#sentry) Aggiungi il [server MCP di Sentry](https://mcp.sentry.dev/) per interagire con i tuoi progetti e le issue di Sentry. { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} Dopo aver aggiunto la configurazione, autentica con Sentry: opencode mcp auth sentry Questo aprira’ una finestra del browser per completare il flusso OAuth e collegare OpenCode al tuo account Sentry. Una volta autenticato, puoi usare gli strumenti Sentry nei tuoi prompt per interrogare issue, progetti e dati sugli errori. Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/it/mcp-servers/#context7) Aggiungi il [server MCP Context7](https://github.com/upstash/context7) per cercare nella documentazione. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} Se ti sei registrato per un account gratuito, puoi usare la tua API key e ottenere rate limit piu’ alti. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} Qui assumiamo che tu abbia impostato la variabile d’ambiente `CONTEXT7_API_KEY`. Aggiungi `use context7` ai tuoi prompt per usare il server MCP Context7. Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 In alternativa, puoi aggiungere qualcosa del genere al tuo [AGENTS.md](https://opencode.ai/docs/rules/) . When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/it/mcp-servers/#grep-by-vercel) Aggiungi il server MCP [Grep by Vercel](https://grep.app/) per cercare snippet di codice su GitHub. { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} Dato che abbiamo chiamato il nostro server MCP `gh_grep`, puoi aggiungere `use the gh_grep tool` ai tuoi prompt per fare in modo che l’agente lo usi. What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool In alternativa, puoi aggiungere qualcosa del genere al tuo [AGENTS.md](https://opencode.ai/docs/rules/) . If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # GitHub | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/github/#_top) GitHub ====== Utilice OpenCode en problemas y solicitudes de extracción de GitHub. OpenCode se integra con su flujo de trabajo GitHub. Mencione `/opencode` o `/oc` en su comentario y OpenCode ejecutará tareas dentro de su corredor de acciones GitHub. * * * [Características](https://opencode.ai/docs/es/github/#caracter%C3%ADsticas) ---------------------------------------------------------------------------- * **Clasificación de problemas**: Pídele a OpenCode que investigue un problema y te lo explique. * **Reparar e implementar**: pídale a OpenCode que solucione un problema o implemente una función. Y funcionará en una nueva sucursal y enviará un PR con todos los cambios. * **Seguro**: OpenCode se ejecuta dentro de los corredores de tu GitHub. * * * [Instalación](https://opencode.ai/docs/es/github/#instalaci%C3%B3n) -------------------------------------------------------------------- Ejecute el siguiente comando en un proyecto que se encuentra en un repositorio GitHub: opencode github install Esto lo guiará a través de la instalación de la aplicación GitHub, la creación del flujo de trabajo y la configuración de secretos. * * * ### [Configuración manual](https://opencode.ai/docs/es/github/#configuraci%C3%B3n-manual) O puede configurarlo manualmente. 1. **Instale la aplicación GitHub** Dirígete a [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) . Asegúrese de que esté instalado en el repositorio de destino. 2. **Agregar el flujo de trabajo** Agregue el siguiente archivo de flujo de trabajo a `.github/workflows/opencode.yml` en su repositorio. Asegúrese de configurar las claves `model` apropiadas y API requeridas en `env`. name: opencode on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: opencode: if: | contains(github.event.comment.body, '/oc') || contains(github.event.comment.body, '/opencode') runs-on: ubuntu-latest permissions: id-token: write steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 1 persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 # share: true # github_token: xxxx 3. **Guarda las claves API en secretos** En la **configuración** de tu organización o proyecto, expande **Secretos y variables** a la izquierda y selecciona **Acciones**. Y agregue las claves API requeridas. * * * [Configuración](https://opencode.ai/docs/es/github/#configuraci%C3%B3n) ------------------------------------------------------------------------ * `model`: El modelo a usar con OpenCode. Toma el formato de `provider/model`. Esto es **obligatorio**. * `agent`: El agente a utilizar. Debe ser un agente primario. Vuelve a `default_agent` desde la configuración o `"build"` si no se encuentra. * `share`: si se comparte la sesión OpenCode. El valor predeterminado es **verdadero** para repositorios públicos. * `prompt`: mensaje personalizado opcional para anular el comportamiento predeterminado. Utilice esto para personalizar cómo OpenCode procesa las solicitudes. * `token`: token de acceso GitHub opcional para realizar operaciones como crear comentarios, confirmar cambios y abrir solicitudes de extracción. De forma predeterminada, OpenCode usa el token de acceso a la instalación de la aplicación OpenCode GitHub, por lo que las confirmaciones, los comentarios y las solicitudes de extracción aparecen como provenientes de la aplicación. Alternativamente, puede usar el GitHub Action Runner [`GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) incorporado sin instalar la aplicación OpenCode GitHub. Solo asegúrese de otorgar los permisos necesarios en su flujo de trabajo: permissions: id-token: write contents: write pull-requests: write issues: write También puede utilizar [tokens de acceso personal](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT) si lo prefiere. * * * [Eventos admitidos](https://opencode.ai/docs/es/github/#eventos-admitidos) --------------------------------------------------------------------------- OpenCode puede desencadenarse por los siguientes eventos GitHub: | Tipo de evento | Activado por | Detalles | | --- | --- | --- | | `issue_comment` | Comentar sobre un tema o PR | Mencione `/opencode` o `/oc` en su comentario. OpenCode lee el contexto y puede crear ramas, abrir relaciones públicas o responder. | | `pull_request_review_comment` | Comente líneas de código específicas en un PR | Mencione `/opencode` o `/oc` mientras revisa el código. OpenCode recibe la ruta del archivo, los números de línea y el contexto de diferencias. | | `issues` | Número abierto o editado | Activa automáticamente OpenCode cuando se crean o modifican problemas. Requiere entrada `prompt`. | | `pull_request` | PR abierto o actualizado | Activa automáticamente OpenCode cuando los PR se abren, sincronizan o vuelven a abrir. Útil para revisiones automatizadas. | | `schedule` | Programación basada en cron | Ejecute OpenCode según una programación. Requiere entrada `prompt`. La salida va a registros y relaciones públicas (no hay temas que comentar). | | `workflow_dispatch` | Activador manual desde GitHub UI | Active OpenCode a pedido a través de la pestaña Acciones. Requiere entrada `prompt`. La salida va a registros y relaciones públicas. | ### [Ejemplo de programación](https://opencode.ai/docs/es/github/#ejemplo-de-programaci%C3%B3n) Ejecute OpenCode según una programación para realizar tareas automatizadas: name: Scheduled OpenCode Task on: schedule: - cron: "0 9 * * 1" # Every Monday at 9am UTC jobs: opencode: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Checkout repository uses: actions/checkout@v6 with: persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review the codebase for any TODO comments and create a summary. If you find issues worth addressing, open an issue to track them. Para eventos programados, la entrada `prompt` es **obligatoria** ya que no hay comentarios del que extraer instrucciones. Los flujos de trabajo programados se ejecutan sin un contexto de usuario para verificar los permisos, por lo que el flujo de trabajo debe otorgar `contents: write` y `pull-requests: write` si espera que OpenCode cree ramas o PR. * * * ### [Ejemplo de solicitud de extracción](https://opencode.ai/docs/es/github/#ejemplo-de-solicitud-de-extracci%C3%B3n) Revisar automáticamente los PR cuando se abren o actualizan: name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: id-token: write contents: read pull-requests: read issues: read steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-4-20250514 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements Para los eventos `pull_request`, si no se proporciona `prompt`, OpenCode revisa de forma predeterminada la solicitud de extracción. * * * ### [Ejemplo de clasificación de problemas](https://opencode.ai/docs/es/github/#ejemplo-de-clasificaci%C3%B3n-de-problemas) Clasifique automáticamente nuevos problemas. Este ejemplo filtra cuentas con más de 30 días para reducir el spam: name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Check account age id: check uses: actions/github-script@v7 with: script: | const user = await github.rest.users.getByUsername({ username: context.payload.issue.user.login }); const created = new Date(user.data.created_at); const days = (Date.now() - created) / (1000 * 60 * 60 * 24); return days >= 30; result-encoding: string - uses: actions/checkout@v6 if: steps.check.outputs.result == 'true' with: persist-credentials: false - uses: anomalyco/opencode/github@latest if: steps.check.outputs.result == 'true' env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review this issue. If there's a clear fix or relevant docs: - Provide documentation links - Add error handling guidance for code examples Otherwise, do not comment. Para eventos `issues`, la entrada `prompt` es **obligatoria** ya que no hay ningún comentario del que extraer instrucciones. * * * [Indicaciones personalizadas](https://opencode.ai/docs/es/github/#indicaciones-personalizadas) ----------------------------------------------------------------------------------------------- Anule el mensaje predeterminado para personalizar el comportamiento de OpenCode para su flujo de trabajo. - uses: anomalyco/opencode/github@latest with: model: anthropic/claude-sonnet-4-5 prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements Esto es útil para hacer cumplir criterios de revisión específicos, estándares de codificación o áreas de enfoque relevantes para su proyecto. * * * [Ejemplos](https://opencode.ai/docs/es/github/#ejemplos) --------------------------------------------------------- A continuación se muestran algunos ejemplos de cómo puede utilizar OpenCode en GitHub. * **Explica un problema** Agregue este comentario en una edición GitHub. /opencode explain this issue OpenCode leerá el hilo completo, incluidos todos los comentarios, y responderá con una explicación clara. * **Solucionar un problema** En un problema GitHub, diga: /opencode fix this Y OpenCode creará una nueva rama, implementará los cambios y abrirá un PR con los cambios. * **Revisar relaciones públicas y realizar cambios** Deja el siguiente comentario en un GitHub PR. Delete the attachment from S3 when the note is removed /oc OpenCode implementará el cambio solicitado y lo comprometerá con el mismo PR. * **Revisar líneas de código específicas** Deje un comentario directamente en las líneas de código en la pestaña “Archivos” del PR. OpenCode detecta automáticamente el archivo, los números de línea y el contexto de diferencias para proporcionar respuestas precisas. [Comment on specific lines in Files tab]/oc add error handling here Al comentar líneas específicas, OpenCode recibe: * El archivo exacto que se está revisando. * Las líneas de código específicas. * El contexto diferencial circundante. * Información del número de línea Esto permite solicitudes más específicas sin necesidad de especificar rutas de archivo o números de línea manualmente. --- # GitHub | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/github/#_top) GitHub ====== Verwenden Sie OpenCode in GitHub-Problemen und Pull-Requests. OpenCode lässt sich in Ihren GitHub-Workflow integrieren. Erwähnen Sie `/opencode` oder `/oc` in Ihrem Kommentar, und OpenCode führt Aufgaben in Ihrem GitHub Actions-Runner aus. * * * [Funktionen](https://opencode.ai/docs/de/github/#funktionen) ------------------------------------------------------------- * **Issue Triage**: Bitten Sie OpenCode, ein Problem zu untersuchen und es Ihnen zu erklären. * **Reparieren und implementieren**: Bitten Sie OpenCode, ein Problem zu beheben oder eine Funktion zu implementieren. Und es funktioniert in einem neuen Branch und sendet ein PR mit allen Änderungen. * **Sicher**: OpenCode läuft in den Runners Ihres GitHub. * * * [Installation](https://opencode.ai/docs/de/github/#installation) ----------------------------------------------------------------- Führen Sie den folgenden Befehl in einem Projekt aus, das sich in einem GitHub-Repository befindet: opencode github install Dies führt Sie durch die Installation der GitHub-App, das Erstellen des Workflows und das Einrichten von Secrets. * * * ### [Manuelle Einrichtung](https://opencode.ai/docs/de/github/#manuelle-einrichtung) Oder Sie können es manuell einrichten. 1. **Installieren Sie die GitHub-App** Gehen Sie zu [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) . Stellen Sie sicher, dass es im Ziel-Repository installiert ist. 2. **Den Workflow hinzufügen** Fügen Sie die folgende Workflowdatei zu `.github/workflows/opencode.yml` in Ihrem Repository hinzu. Stellen Sie sicher, dass Sie in `env` die passenden Werte für `model` und `api_key` setzen. name: opencode on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: opencode: if: | contains(github.event.comment.body, '/oc') || contains(github.event.comment.body, '/opencode') runs-on: ubuntu-latest permissions: id-token: write steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 1 persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 # share: true # github_token: xxxx 3. **Speichern Sie die API-Schlüssel in Secrets** Erweitern Sie in den **Einstellungen** Ihrer Organisation oder Ihres Projekts links **Secrets und Variablen** und wählen Sie **Aktionen** aus. Und fügen Sie die erforderlichen API-Schlüssel hinzu. * * * [Konfiguration](https://opencode.ai/docs/de/github/#konfiguration) ------------------------------------------------------------------- * `model`: Das mit OpenCode zu verwendende Modell. Nimmt das Format `provider/model` an. Dies ist **erforderlich**. * `agent`: Der zu verwendende Agent. Muss ein Hauptagent sein. Fällt aus der Konfiguration auf `default_agent` oder `"build"` zurück, wenn es nicht gefunden wird. * `share`: Ob die OpenCode-Sitzung geteilt werden soll. Der Standardwert ist **true** für öffentliche Repositorys. * `prompt`: Optionale benutzerdefinierte Eingabeaufforderung zum Überschreiben des Standardverhaltens. Verwenden Sie dies, um anzupassen, wie OpenCode Anfragen verarbeitet. * `token`: Optionales GitHub-Zugriffstoken zum Ausführen von Vorgängen wie dem Erstellen von Kommentaren, dem Festschreiben von Änderungen und dem Öffnen von Pull Requests. Standardmäßig verwendet OpenCode das Installation Access Token der OpenCode GitHub-App, sodass Commits, Kommentare und Pull Requests so aussehen, als würden sie von der App kommen. Alternativ können Sie [built-in `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) des GitHub Action Runners verwenden, ohne die OpenCode GitHub App zu installieren. Stellen Sie einfach sicher, dass Sie in Ihrem Workflow die erforderlichen Berechtigungen erteilen: permissions: id-token: write contents: write pull-requests: write issues: write Sie können bei Bedarf auch einen [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT) verwenden. * * * [Unterstützte Events](https://opencode.ai/docs/de/github/#unterst%C3%BCtzte-events) ------------------------------------------------------------------------------------ OpenCode kann durch die folgenden GitHub-Events ausgelöst werden: | Ereignistyp | Ausgelöst durch | Einzelheiten | | --- | --- | --- | | `issue_comment` | Kommentieren Sie ein Problem oder PR | Erwähnen Sie `/opencode` oder `/oc` in Ihrem Kommentar. OpenCode liest den Kontext und kann Branches erstellen, PRs öffnen oder antworten. | | `pull_request_review_comment` | Kommentieren Sie bestimmte Codezeilen in einem PR | Erwähnen Sie `/opencode` oder `/oc` beim Überprüfen des Codes. OpenCode empfängt Dateipfad, Zeilennummern und Diff Context. | | `issues` | Problem geöffnet oder bearbeitet | Lösen Sie OpenCode automatisch aus, wenn Probleme erstellt oder geändert werden. Erfordert `prompt`\-Eingabe. | | `pull_request` | PR geöffnet oder aktualisiert | Lösen Sie OpenCode automatisch aus, wenn PRs geöffnet, synchronisiert oder erneut geöffnet werden. Nützlich für automatisierte Bewertungen. | | `schedule` | Cron-basierter Zeitplan | Führen Sie OpenCode nach einem Zeitplan aus. Erfordert `prompt`\-Eingabe. Die Ausgabe geht an Protokolle und PRs (kein Kommentar zu diesem Problem). | | `workflow_dispatch` | Manueller Trigger von GitHub UI | Lösen Sie OpenCode bei Bedarf über die Actions Tab aus. Erfordert `prompt`\-Eingabe. Die Ausgabe erfolgt an Protokolle und PRs. | ### [Beispiel für einen Zeitplan](https://opencode.ai/docs/de/github/#beispiel-f%C3%BCr-einen-zeitplan) Führen Sie OpenCode nach einem Zeitplan aus, um automatisierte Aufgaben auszuführen: name: Scheduled OpenCode Task on: schedule: - cron: "0 9 * * 1" # Every Monday at 9am UTC jobs: opencode: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Checkout repository uses: actions/checkout@v6 with: persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review the codebase for any TODO comments and create a summary. If you find issues worth addressing, open an issue to track them. Für geplante Ereignisse ist die Eingabe `prompt` **erforderlich**, da es keinen Kommentar gibt, aus dem Anweisungen extrahiert werden können. Geplante Workflows werden ohne Benutzerkontext zur Berechtigungsprüfung ausgeführt. Daher muss der Workflow `contents: write` und `pull-requests: write` gewähren, wenn Sie erwarten, dass OpenCode Branches oder PRs erstellt. * * * ### [Pull-Request-Beispiel](https://opencode.ai/docs/de/github/#pull-request-beispiel) Überprüfen Sie PRs automatisch, wenn sie geöffnet oder aktualisiert werden: name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: id-token: write contents: read pull-requests: read issues: read steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-4-20250514 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements Wenn für `pull_request`\-Ereignisse kein `prompt` bereitgestellt wird, überprüft OpenCode standardmäßig die Pull-Anfrage. * * * ### [Beispiel für eine Issue-Triage](https://opencode.ai/docs/de/github/#beispiel-f%C3%BCr-eine-issue-triage) Neue Probleme automatisch selektieren. In diesem Beispiel wird nach Konten gefiltert, die älter als 30 Tage sind, um Spam zu reduzieren: name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Check account age id: check uses: actions/github-script@v7 with: script: | const user = await github.rest.users.getByUsername({ username: context.payload.issue.user.login }); const created = new Date(user.data.created_at); const days = (Date.now() - created) / (1000 * 60 * 60 * 24); return days >= 30; result-encoding: string - uses: actions/checkout@v6 if: steps.check.outputs.result == 'true' with: persist-credentials: false - uses: anomalyco/opencode/github@latest if: steps.check.outputs.result == 'true' env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review this issue. If there's a clear fix or relevant docs: - Provide documentation links - Add error handling guidance for code examples Otherwise, do not comment. Für `issues`\-Ereignisse ist die Eingabe `prompt` **erforderlich**, da es keinen Kommentar gibt, aus dem Anweisungen extrahiert werden können. * * * [Benutzerdefinierte Prompts](https://opencode.ai/docs/de/github/#benutzerdefinierte-prompts) --------------------------------------------------------------------------------------------- Überschreiben Sie die Standardaufforderung, um das Verhalten von OpenCode für Ihren Workflow anzupassen. - uses: anomalyco/opencode/github@latest with: model: anthropic/claude-sonnet-4-5 prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements Dies ist nützlich, um bestimmte Prüfkriterien, Kodierungsstandards oder Schwerpunktbereiche durchzusetzen, die für Ihr Projekt relevant sind. * * * [Beispiele](https://opencode.ai/docs/de/github/#beispiele) ----------------------------------------------------------- Hier sind einige Beispiele, wie Sie OpenCode in GitHub verwenden können. * **Erklären Sie ein Problem** Fügen Sie diesen Kommentar in einer GitHub-Ausgabe hinzu. /opencode explain this issue OpenCode liest den gesamten Thread, einschließlich aller Kommentare, und antwortet mit einer klaren Erklärung. * **Ein Problem beheben** Sagen Sie in einer GitHub-Ausgabe: /opencode fix this Und OpenCode erstellt einen neuen Branch, implementiert die Änderungen und öffnet ein PR mit den Änderungen. * **PRs überprüfen und Änderungen vornehmen** Hinterlassen Sie den folgenden Kommentar auf einem GitHub PR. Delete the attachment from S3 when the note is removed /oc OpenCode implementiert die angeforderte Änderung und schreibt sie an denselben PR fest. * **Überprüfen Sie bestimmte Codezeilen** Hinterlassen Sie einen Kommentar direkt zu den Codezeilen auf der Files Tab von PR. OpenCode erkennt automatisch die Datei, Zeilennummern und den Diff Context, um präzise Antworten bereitzustellen. [Comment on specific lines in Files tab]/oc add error handling here Beim Kommentieren bestimmter Zeilen erhält OpenCode: * Die genaue Datei, die überprüft wird * Die spezifischen Codezeilen * Der umgebende Diff Context * Informationen zur Zeilennummer Dies ermöglicht gezieltere Anfragen, ohne dass Dateipfade oder Zeilennummern manuell angegeben werden müssen. --- # GitHub | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/github/#_top) GitHub ====== Usa OpenCode in issue e pull request su GitHub. OpenCode si integra nel tuo workflow GitHub. Menziona `/opencode` o `/oc` in un commento e OpenCode eseguira’ i task dentro il runner di GitHub Actions. * * * [Funzionalità](https://opencode.ai/docs/it/github/#funzionalit%C3%A0) ---------------------------------------------------------------------- * **Triage delle issue**: chiedi a OpenCode di indagare su una issue e spiegartela. * **Fix e implementazioni**: chiedi a OpenCode di risolvere una issue o implementare una feature. Lavorera’ su un nuovo branch e inviera’ una PR con tutte le modifiche. * **Sicuro**: OpenCode gira all’interno dei runner GitHub. * * * [Installazione](https://opencode.ai/docs/it/github/#installazione) ------------------------------------------------------------------- Esegui il comando seguente in un progetto che si trova in un repo GitHub: opencode github install Questo ti guidera’ nell’installazione della GitHub app, nella creazione del workflow e nella configurazione dei secret. * * * ### [Configurazione manuale](https://opencode.ai/docs/it/github/#configurazione-manuale) In alternativa, puoi configurarlo manualmente. 1. **Installa la GitHub app** Vai su [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) . Assicurati che sia installata sul repository di destinazione. 2. **Aggiungi il workflow** Aggiungi il seguente file workflow in `.github/workflows/opencode.yml` nel tuo repo. Assicurati di impostare il `model` appropriato e le API key richieste in `env`. name: opencode on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: opencode: if: | contains(github.event.comment.body, '/oc') || contains(github.event.comment.body, '/opencode') runs-on: ubuntu-latest permissions: id-token: write steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 1 persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 # share: true # github_token: xxxx 3. **Salva le API key nei secret** Nelle **impostazioni** della tua organizzazione o progetto, espandi **Secrets and variables** sulla sinistra e seleziona **Actions**. Poi aggiungi le API key richieste. * * * [Configurazione](https://opencode.ai/docs/it/github/#configurazione) --------------------------------------------------------------------- * `model`: il modello da usare con OpenCode. Usa il formato `provider/model`. E’ **obbligatorio**. * `agent`: l’agente da usare. Deve essere un agente primario. Se non trovato, usa `default_agent` dalla config o `"build"`. * `share`: se condividere la sessione OpenCode. Di default e’ **true** per repository pubblici. * `prompt`: prompt personalizzato opzionale per sovrascrivere il comportamento di default. Usalo per personalizzare come OpenCode processa le richieste. * `token`: token di accesso GitHub opzionale per eseguire operazioni come creare commenti, committare modifiche e aprire pull request. Di default, OpenCode usa l’installation access token della OpenCode GitHub App, quindi commit, commenti e pull request risultano provenire dalla app. In alternativa, puoi usare il [token integrato `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) del runner GitHub Actions senza installare la OpenCode GitHub App. Assicurati solo di concedere i permessi necessari nel workflow: permissions: id-token: write contents: write pull-requests: write issues: write Se preferisci, puoi anche usare un [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT). * * * [Eventi supportati](https://opencode.ai/docs/it/github/#eventi-supportati) --------------------------------------------------------------------------- OpenCode puo’ essere attivato dai seguenti eventi GitHub: | Tipo evento | Attivato da | Dettagli | | --- | --- | --- | | `issue_comment` | Commento su una issue o PR | Menziona `/opencode` o `/oc` nel commento. OpenCode legge il contesto e puo’ creare branch, aprire PR o rispondere. | | `pull_request_review_comment` | Commento su specifiche righe in una PR | Menziona `/opencode` o `/oc` durante una review. OpenCode riceve path file, numeri di riga e contesto del diff. | | `issues` | Issue aperta o modificata | Attiva automaticamente OpenCode quando le issue vengono create o modificate. Richiede l’input `prompt`. | | `pull_request` | PR aperta o aggiornata | Attiva automaticamente OpenCode quando le PR vengono aperte, sincronizzate o riaperte. Utile per review automatiche. | | `schedule` | Pianificazione basata su cron | Esegue OpenCode a pianificazione. Richiede l’input `prompt`. Output nei log e nelle PR (nessuna issue su cui commentare). | | `workflow_dispatch` | Trigger manuale dalla UI GitHub | Attiva OpenCode on-demand dalla tab Actions. Richiede l’input `prompt`. Output nei log e nelle PR. | ### [Esempio con schedule](https://opencode.ai/docs/it/github/#esempio-con-schedule) Esegui OpenCode a pianificazione per eseguire task automatizzati: name: Scheduled OpenCode Task on: schedule: - cron: "0 9 * * 1" # Every Monday at 9am UTC jobs: opencode: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Checkout repository uses: actions/checkout@v6 with: persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review the codebase for any TODO comments and create a summary. If you find issues worth addressing, open an issue to track them. Per gli eventi schedulati, l’input `prompt` e’ **obbligatorio** dato che non c’e’ un commento da cui estrarre le istruzioni. I workflow schedulati girano senza un contesto utente per i controlli di permesso, quindi il workflow deve concedere `contents: write` e `pull-requests: write` se ti aspetti che OpenCode crei branch o PR. * * * ### [Esempio di pull request](https://opencode.ai/docs/it/github/#esempio-di-pull-request) Review automatica delle PR quando vengono aperte o aggiornate: name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: id-token: write contents: read pull-requests: read issues: read steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-4-20250514 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements Per gli eventi `pull_request`, se non viene fornito alcun `prompt`, OpenCode fa di default la review della pull request. * * * ### [Esempio di triage delle issue](https://opencode.ai/docs/it/github/#esempio-di-triage-delle-issue) Triage automatico delle nuove issue. Questo esempio filtra gli account piu’ vecchi di 30 giorni per ridurre lo spam: name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Check account age id: check uses: actions/github-script@v7 with: script: | const user = await github.rest.users.getByUsername({ username: context.payload.issue.user.login }); const created = new Date(user.data.created_at); const days = (Date.now() - created) / (1000 * 60 * 60 * 24); return days >= 30; result-encoding: string - uses: actions/checkout@v6 if: steps.check.outputs.result == 'true' with: persist-credentials: false - uses: anomalyco/opencode/github@latest if: steps.check.outputs.result == 'true' env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review this issue. If there's a clear fix or relevant docs: - Provide documentation links - Add error handling guidance for code examples Otherwise, do not comment. Per gli eventi `issues`, l’input `prompt` e’ **obbligatorio** dato che non c’e’ un commento da cui estrarre le istruzioni. * * * [Prompt personalizzati](https://opencode.ai/docs/it/github/#prompt-personalizzati) ----------------------------------------------------------------------------------- Sovrascrivi il prompt di default per personalizzare il comportamento di OpenCode nel tuo workflow. - uses: anomalyco/opencode/github@latest with: model: anthropic/claude-sonnet-4-5 prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements E’ utile per imporre criteri specifici di review, standard di codice o aree di focus rilevanti per il progetto. * * * [Esempi](https://opencode.ai/docs/it/github/#esempi) ----------------------------------------------------- Ecco alcuni esempi di come puoi usare OpenCode su GitHub. * **Spiega una issue** Aggiungi questo commento in una issue GitHub. /opencode explain this issue OpenCode leggera’ l’intero thread, inclusi tutti i commenti, e rispondera’ con una spiegazione chiara. * **Risolvi una issue** In una issue GitHub, scrivi: /opencode fix this OpenCode creera’ un nuovo branch, implementera’ le modifiche e aprira’ una PR con i cambiamenti. * **Rivedi PR e fai modifiche** Lascia il seguente commento su una PR GitHub. Delete the attachment from S3 when the note is removed /oc OpenCode implementera’ la modifica richiesta e la committera’ nella stessa PR. * **Rivedi righe specifiche di codice** Lascia un commento direttamente sulle righe di codice nella tab “Files” della PR. OpenCode rileva automaticamente file, numeri di riga e contesto del diff per fornire risposte precise. [Comment on specific lines in Files tab]/oc add error handling here Quando commenti su righe specifiche, OpenCode riceve: * Il file esatto in review * Le righe di codice specifiche * Il contesto del diff circostante * Informazioni sul numero di riga Questo permette richieste piu’ mirate senza dover specificare manualmente path file o numeri di riga. --- # GitHub | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/github/#_top) GitHub ====== GitHub の問題とプルリクエストで OpenCode を使用します。 OpenCode は GitHub ワークフローと統合します。コメントで `/opencode` または `/oc` に言及すると、OpenCode が GitHub Actions ランナー内でタスクを実行します。 * * * [機能](https://opencode.ai/docs/ja/github/#%E6%A9%9F%E8%83%BD) ------------------------------------------------------------- * **問題のトリアージ**: OpenCode に問題を調べて説明してもらいます。 * **修正と実装**: OpenCode に問題の修正または機能の実装を依頼します。そして、新しいブランチで動作し、すべての変更を含む PR を送信します。 * **安全**: OpenCode は GitHub のランナー内で実行されます。 * * * [インストール](https://opencode.ai/docs/ja/github/#%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB) ----------------------------------------------------------------------------------------------------- GitHub リポジトリにあるプロジェクトで次のコマンドを実行します。 opencode github install ここでは、GitHub アプリのインストール、ワークフローの作成、シークレットの設定について説明します。 * * * ### [手動セットアップ](https://opencode.ai/docs/ja/github/#%E6%89%8B%E5%8B%95%E3%82%BB%E3%83%83%E3%83%88%E3%82%A2%E3%83%83%E3%83%97) または、手動で設定することもできます。 1. **GitHub アプリをインストールします** [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) にアクセスしてください。ターゲットリポジトリにインストールされていることを確認してください。 2. **ワークフローを追加** 次のワークフローファイルをリポジトリの `.github/workflows/opencode.yml` に追加します。適切な `model` と必要な API キーを `env` に設定してください。 name: opencode on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: opencode: if: | contains(github.event.comment.body, '/oc') || contains(github.event.comment.body, '/opencode') runs-on: ubuntu-latest permissions: id-token: write steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 1 persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 # share: true # github_token: xxxx 3. **API キーをシークレットに保存する** 組織またはプロジェクトの**設定**で、左側の**シークレットと変数**を展開し、**アクション**を選択します。そして、必要な API キーを追加します。 * * * [設定](https://opencode.ai/docs/ja/github/#%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------- * `model`: OpenCode で使用するモデル。 `provider/model` の形式をとります。これは**必須**です。 * `agent`: 使用するエージェント。プライマリエージェントである必要があります。見つからない場合は、設定から `default_agent` にフォールバックするか、`"build"` にフォールバックします。 * `share`: OpenCode セッションを共有するかどうか。パブリックリポジトリのデフォルトは **true** です。 * `prompt`: デフォルトの動作をオーバーライドするためのオプションのカスタムプロンプト。これを使用して、OpenCode がリクエストを処理する方法をカスタマイズします。 * `token`: コメントの作成、変更のコミット、プルリクエストのオープンなどの操作を実行するためのオプションの GitHub アクセストークン。デフォルトでは、OpenCode は OpenCode GitHub アプリからのインストールアクセストークンを使用するため、コミット、コメント、プルリクエストはアプリからのものとして表示されます。 あるいは、OpenCode GitHub アプリをインストールせずに、GitHub Action ランナーの [組み込み `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) を使用することもできます。ワークフローで必要な権限を必ず付与してください。 permissions: id-token: write contents: write pull-requests: write issues: write 必要に応じて、[パーソナルアクセストークン](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT) を使用することもできます。 * * * [サポートされているイベント](https://opencode.ai/docs/ja/github/#%E3%82%B5%E3%83%9D%E3%83%BC%E3%83%88%E3%81%95%E3%82%8C%E3%81%A6%E3%81%84%E3%82%8B%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode は、次の GitHub イベントによってトリガーできます。 | イベントの種類 | トリガー | 詳細 | | --- | --- | --- | | `issue_comment` | 問題または PR についてコメントする | コメントで `/opencode` または `/oc` について言及してください。 OpenCode はコンテキストを読み取り、ブランチを作成したり、PR を開いたり、返信したりできます。 | | `pull_request_review_comment` | PR 内の特定のコード行にコメントする | コードをレビューするときに、`/opencode` または `/oc` について言及します。 OpenCode は、ファイルパス、行番号、および diff コンテキストを受け取ります。 | | `issues` | 問題がオープンまたは編集されました | 問題が作成または変更されると、OpenCode が自動的にトリガーされます。 `prompt` 入力が必要です。 | | `pull_request` | PR がオープンまたは更新されました | PR が開かれる、同期される、または再度開かれるときに、OpenCode を自動的にトリガーします。自動レビューに役立ちます。 | | `schedule` | Cron ベースのスケジュール | スケジュールに従って OpenCode を実行します。 `prompt` 入力が必要です。出力はログと PR に送られます (コメントする問題はありません)。 | | `workflow_dispatch` | GitHub UI からの手動トリガー | \[アクション\] タブから OpenCode をオンデマンドでトリガーします。 `prompt` 入力が必要です。出力はログと PR に送られます。 | ### [スケジュールの例](https://opencode.ai/docs/ja/github/#%E3%82%B9%E3%82%B1%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AE%E4%BE%8B) スケジュールに従って OpenCode を実行し、自動化されたタスクを実行します。 name: Scheduled OpenCode Task on: schedule: - cron: "0 9 * * 1" # Every Monday at 9am UTC jobs: opencode: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Checkout repository uses: actions/checkout@v6 with: persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review the codebase for any TODO comments and create a summary. If you find issues worth addressing, open an issue to track them. スケジュールされたイベントの場合、指示を抽出するためのコメントがないため、`prompt` 入力は **必須** です。スケジュールされたワークフローは、権限チェックのためのユーザーコンテキストなしで実行されるため、OpenCode がブランチまたは PR を作成することが予想される場合、ワークフローは `contents: write` および `pull-requests: write` を付与する必要があります。 * * * ### [プルリクエストの例](https://opencode.ai/docs/ja/github/#%E3%83%97%E3%83%AB%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%81%AE%E4%BE%8B) PR が開かれるか更新されるときに、PR を自動的にレビューします。 name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: id-token: write contents: read pull-requests: read issues: read steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-4-20250514 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements `pull_request` イベントの場合、`prompt` が指定されていない場合、OpenCode はデフォルトでプルリクエストをレビューします。 * * * ### [Issueのトリアージの例](https://opencode.ai/docs/ja/github/#issue%E3%81%AE%E3%83%88%E3%83%AA%E3%82%A2%E3%83%BC%E3%82%B8%E3%81%AE%E4%BE%8B) 新しい問題を自動的に優先順位付けします。この例では、スパムを減らすために 30 日より古いアカウントにフィルターを適用します。 name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Check account age id: check uses: actions/github-script@v7 with: script: | const user = await github.rest.users.getByUsername({ username: context.payload.issue.user.login }); const created = new Date(user.data.created_at); const days = (Date.now() - created) / (1000 * 60 * 60 * 24); return days >= 30; result-encoding: string - uses: actions/checkout@v6 if: steps.check.outputs.result == 'true' with: persist-credentials: false - uses: anomalyco/opencode/github@latest if: steps.check.outputs.result == 'true' env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review this issue. If there's a clear fix or relevant docs: - Provide documentation links - Add error handling guidance for code examples Otherwise, do not comment. `issues` イベントの場合、指示を抽出するためのコメントがないため、`prompt` 入力は **必須** です。 * * * [カスタムプロンプト](https://opencode.ai/docs/ja/github/#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%97%E3%83%AD%E3%83%B3%E3%83%97%E3%83%88) ----------------------------------------------------------------------------------------------------------------------------------- デフォルトのプロンプトをオーバーライドして、ワークフローに合わせて OpenCode の動作をカスタマイズします。 - uses: anomalyco/opencode/github@latest with: model: anthropic/claude-sonnet-4-5 prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements これは、プロジェクトに関連する特定のレビュー基準、コーディング標準、または重点分野を強制するのに役立ちます。 * * * [例](https://opencode.ai/docs/ja/github/#%E4%BE%8B) --------------------------------------------------- GitHub で OpenCode を使用する方法の例をいくつか示します。 * **Issueの説明** このコメントを GitHub の問題に追加します。 /opencode explain this issue OpenCode は、すべてのコメントを含むスレッド全体を読み取り、明確な説明を返信します。 * **Issueの修正** GitHub の問題で次のように言います。 /opencode fix this そして、OpenCode は新しいブランチを作成し、変更を実装し、変更を含む PR を開きます。 * **PR をレビューして変更を加える** GitHub PR に次のコメントを残してください。 Delete the attachment from S3 when the note is removed /oc OpenCode は要求された変更を実装し、同じ PR にコミットします。 * **特定のコード行のレビュー** PR の「ファイル」タブのコード行に直接コメントを残します。 OpenCode は、ファイル、行番号、および diff コンテキストを自動的に検出して、正確な応答を提供します。 [Comment on specific lines in Files tab] /oc add error handling here 特定の行にコメントすると、OpenCode は以下を受け取ります。 * レビューされている正確なファイル * コードの特定の行 * 周囲の差分コンテキスト * 行番号情報 これにより、ファイルパスや行番号を手動で指定する必要がなく、よりターゲットを絞ったリクエストが可能になります。 --- # GitHub | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/github/#_top) GitHub ====== Используйте opencode в задачах и пул-реквестах GitHub. opencode интегрируется с вашим рабочим процессом GitHub. Упомяните `/opencode` или `/oc` в своем комментарии, и opencode выполнит задачи в вашем средстве выполнения действий GitHub. * * * [Возможности](https://opencode.ai/docs/ru/github/#%D0%B2%D0%BE%D0%B7%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%D1%81%D1%82%D0%B8) ---------------------------------------------------------------------------------------------------------------------- * **Триаж задач (Issue Triage)**. Попросите opencode разобраться в проблеме и объяснить ее вам. * **Исправление и реализация**. Попросите opencode исправить проблему или реализовать функцию. Он будет работать в новой ветке и создаст PR со всеми изменениями. * **Безопасность**: opencode запускается внутри ваших GitHub Runners. * * * [Установка](https://opencode.ai/docs/ru/github/#%D1%83%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0) -------------------------------------------------------------------------------------------------------- Запустите следующую команду в проекте, который находится в репозитории GitHub: opencode github install Это поможет вам установить приложение GitHub, создать рабочий процесс и настроить secrets (секреты). * * * ### [Ручная настройка](https://opencode.ai/docs/ru/github/#%D1%80%D1%83%D1%87%D0%BD%D0%B0%D1%8F-%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0) Или вы можете настроить его вручную. 1. **Установите приложение GitHub** Перейдите на [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) . Убедитесь, что он установлен в целевом репозитории. 2. **Добавьте рабочий процесс** Добавьте следующий файл рабочего процесса в `.github/workflows/opencode.yml` в своем репозитории. Обязательно установите соответствующий `model` и необходимые ключи API в `env`. name: opencode on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: opencode: if: | contains(github.event.comment.body, '/oc') || contains(github.event.comment.body, '/opencode') runs-on: ubuntu-latest permissions: id-token: write steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 1 persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 # share: true # github_token: xxxx 3. **Храните ключи API в секрете** В **настройках** вашей организации или проекта разверните **Секреты и переменные** слева и выберите **Действия**. И добавьте необходимые ключи API. * * * [Настройка](https://opencode.ai/docs/ru/github/#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0) -------------------------------------------------------------------------------------------------------- * `model`: модель для использования с opencode. Принимает формат `provider/model`. Это **обязательно**. * `agent`: используемый агент. Должен быть основным агентом. Возвращается к `default_agent` из конфигурации или к `"build"`, если не найден. * `share`: следует ли предоставлять общий доступ к сеансу opencode. По умолчанию **true** для общедоступных репозиториев. * `prompt`: дополнительный настраиваемый запрос для переопределения поведения по умолчанию. Используйте это, чтобы настроить обработку запросов opencode. * `token`: дополнительный токен доступа GitHub для выполнения таких операций, как создание комментариев, фиксация изменений и открытие запросов на включение. По умолчанию opencode использует токен доступа к установке из приложения opencode GitHub, поэтому фиксации, комментарии и запросы на включение отображаются как исходящие из приложения. Кроме того, вы можете использовать [встроенный `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) средства запуска действий GitHub без установки приложения opencode GitHub. Просто не забудьте предоставить необходимые разрешения в вашем рабочем процессе: permissions: id-token: write contents: write pull-requests: write issues: write Вы также можете использовать [токены личного доступа](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT), если предпочитаете. * * * [Поддерживаемые события](https://opencode.ai/docs/ru/github/#%D0%BF%D0%BE%D0%B4%D0%B4%D0%B5%D1%80%D0%B6%D0%B8%D0%B2%D0%B0%D0%B5%D0%BC%D1%8B%D0%B5-%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D1%8F) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- opencode может быть запущен следующими событиями GitHub: | Тип события | Инициировано | Подробности | | --- | --- | --- | | `issue_comment` | Комментарий к проблеме или PR | Упомяните `/opencode` или `/oc` в своем комментарии. opencode считывает контекст и может создавать ветки, открывать PR или отвечать. | | `pull_request_review_comment` | Комментируйте конкретные строки кода в PR. | Упоминайте `/opencode` или `/oc` при просмотре кода. opencode получает путь к файлу, номера строк и контекст сравнения. | | `issues` | Issue открыт или изменен | Автоматически запускать opencode при создании или изменении проблем. Требуется ввод `prompt`. | | `pull_request` | PR открыт или обновлен | Автоматически запускать opencode при открытии, синхронизации или повторном открытии PR. Полезно для автоматических обзоров. | | `schedule` | Расписание на основе Cron | Запускайте opencode по расписанию. Требуется ввод `prompt`. Вывод поступает в журналы и PR (комментариев нет). | | `workflow_dispatch` | Ручной триггер из пользовательского интерфейса GitHub | Запускайте opencode по требованию на вкладке «Действия». Требуется ввод `prompt`. Вывод идет в логи и PR. | ### [Пример: Расписание](https://opencode.ai/docs/ru/github/#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80-%D1%80%D0%B0%D1%81%D0%BF%D0%B8%D1%81%D0%B0%D0%BD%D0%B8%D0%B5) Запускайте opencode по расписанию для выполнения автоматизированных задач: name: Scheduled OpenCode Task on: schedule: - cron: "0 9 * * 1" # Every Monday at 9am UTC jobs: opencode: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Checkout repository uses: actions/checkout@v6 with: persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review the codebase for any TODO comments and create a summary. If you find issues worth addressing, open an issue to track them. Для запланированных событий вход `prompt` **обязателен**, поскольку нет комментария, из которого можно было бы извлечь инструкции. Запланированные рабочие процессы выполняются без пользовательского контекста для проверки разрешений, поэтому рабочий процесс должен предоставлять `contents: write` и `pull-requests: write`, если вы ожидаете, что opencode будет создавать ветки или PR. * * * ### [Пример: Pull Request](https://opencode.ai/docs/ru/github/#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80-pull-request) Автоматически просматривать PR при их открытии или обновлении: name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: id-token: write contents: read pull-requests: read issues: read steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-4-20250514 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements Если для событий `pull_request` не указан `prompt`, opencode по умолчанию проверяет запрос на включение. * * * ### [Пример: Сортировка Issue](https://opencode.ai/docs/ru/github/#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80-%D1%81%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B0-issue) Автоматически сортируйте новые проблемы. В этом примере фильтруется аккаунты, созданные более 30 дней назад, чтобы уменьшить количество спама: name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Check account age id: check uses: actions/github-script@v7 with: script: | const user = await github.rest.users.getByUsername({ username: context.payload.issue.user.login }); const created = new Date(user.data.created_at); const days = (Date.now() - created) / (1000 * 60 * 60 * 24); return days >= 30; result-encoding: string - uses: actions/checkout@v6 if: steps.check.outputs.result == 'true' with: persist-credentials: false - uses: anomalyco/opencode/github@latest if: steps.check.outputs.result == 'true' env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review this issue. If there's a clear fix or relevant docs: - Provide documentation links - Add error handling guidance for code examples Otherwise, do not comment. Для событий `issues` вход `prompt` **обязателен**, поскольку нет комментария, из которого можно было бы извлечь инструкции. * * * [Пользовательские промпты](https://opencode.ai/docs/ru/github/#%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%BF%D1%80%D0%BE%D0%BC%D0%BF%D1%82%D1%8B) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Переопределите приглашение по умолчанию, чтобы настроить поведение opencode для вашего рабочего процесса. - uses: anomalyco/opencode/github@latest with: model: anthropic/claude-sonnet-4-5 prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements Это полезно для обеспечения соблюдения конкретных критериев проверки, стандартов кодирования или приоритетных областей, имеющих отношение к вашему проекту. * * * [Примеры](https://opencode.ai/docs/ru/github/#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B) ------------------------------------------------------------------------------------------ Вот несколько примеров того, как вы можете использовать opencode в GitHub. * **Объяснение проблемы** Добавьте этот комментарий в выпуск GitHub. /opencode explain this issue opencode прочитает всю ветку, включая все комментарии, и ответит с четким объяснением. * **Исправление проблемы** В выпуске GitHub скажите: /opencode fix this А opencode создаст новую ветку, внедрит изменения и откроет PR с изменениями. * **Проверка Pull Request и внесение изменений** Оставьте следующий комментарий к PR на GitHub. Delete the attachment from S3 when the note is removed /oc opencode внедрит запрошенное изменение и зафиксирует его в том же PR. * **Проверка отдельных строк кода** Оставляйте комментарии непосредственно к строкам кода на вкладке «Файлы» PR. opencode автоматически определяет файл, номера строк и контекст различий, чтобы предоставить точные ответы. [Comment on specific lines in Files tab]/oc add error handling here При комментировании определенных строк opencode получает: * Точный файл, который просматривается * Конкретные строки кода * Окружающий контекст различий * Информация о номере строки Это позволяет выполнять более целевые запросы без необходимости вручную указывать пути к файлам или номера строк. --- # MCP-servere | OpenCode [Gå til indhold](https://opencode.ai/docs/da/mcp-servers/#_top) MCP-servere =========== Tilføj lokale og eksterne MCP værktøjer. Du kan tilføje eksterne værktøjer til OpenCode ved hjælp af _Model Context Protocol_ eller MCP. OpenCode understøtter både lokale og eksterne servere. Når de er tilføjet, er MCP automatisk tilgængelig for LLM sammen med indbyggede værktøjer. * * * #### [Forbehold](https://opencode.ai/docs/da/mcp-servers/#forbehold) Når du bruger en MCP-server, føjes den til konteksten. Dette kan hurtigt stige, hvis du har mange værktøjer. Så vi anbefaler at være forsigtig med hvilke MCP-servere du bruger. Visse MCP-servere, som GitHub MCP-servere, har en tendens til at tilføje mange tokens og kan nemt overskride kontekstgrænsen. * * * [Aktivering](https://opencode.ai/docs/da/mcp-servers/#aktivering) ------------------------------------------------------------------ Du kan definere MCP-servere i din [OpenCode Config](https://opencode.ai/docs/config/) under `mcp`. Tilføj hver MCP med et unikt navn. Du kan henvise til denne MCP ved navn, når du spørger LLM. { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} Du kan også deaktivere en server ved at indstille `enabled` til `false`. Dette er nyttigt, hvis du midlertidigt vil deaktivere en server uden at fjerne den fra din konfiguration. * * * ### [Tilsidesættelse af eksterne standarder](https://opencode.ai/docs/da/mcp-servers/#tilsides%C3%A6ttelse-af-eksterne-standarder) Organisationer kan levere standard MCP-servere via deres `.well-known/opencode`\-slutpunkt. Disse servere kan være deaktiveret som standard, hvilket giver brugerne mulighed for at tilmelde sig dem, de har brug for. For at aktivere en specifik server fra din organisationers fjernkonfiguration skal du tilføje den til din lokale konfiguration med `enabled: true`: { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} Dine lokale konfigurationsværdier tilsidesætter fjernstandarderne. Se [config precedence](https://opencode.ai/docs/config#precedence-order) for flere detaljer. * * * [Lokal](https://opencode.ai/docs/da/mcp-servers/#lokal) -------------------------------------------------------- Tilføj lokale MCP-servere ved hjælp af `type` til `"local"` i MCP-objektet. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} Kommandoen er, hvordan den lokale MCP-server starter. Du kan også sende en liste over miljøvariabler ind. For eksempel kan du tilføje test-MCP-serveren [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) . { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} Og for at bruge det kan jeg tilføje `use the mcp_everything tool` til mine prompter. use the mcp_everything tool to add the number 3 and 4 * * * #### [Indstillinger](https://opencode.ai/docs/da/mcp-servers/#indstillinger) Her er alle muligheder for at konfigurere en lokal MCP-server. | Mulighed | Skriv | Påkrævet | Beskrivelse | | --- | --- | --- | --- | | `type` | String | Y | Type MCP serverforbindelse, skal være `"local"`. | | `command` | Array | Y | Kommando og argumenter til at køre MCP-serveren. | | `environment` | Object | | Miljøvariabler, der skal indstilles, når serveren kører. | | `enabled` | Boolean | | Aktiver eller deaktiver MCP-serveren ved opstart. | | `timeout` | Nummer | | Timeout i ms for at hente værktøjer fra MCP-serveren. Standard er 5000 (5 sekunder). | * * * [Ekstern](https://opencode.ai/docs/da/mcp-servers/#ekstern) ------------------------------------------------------------ Tilføj ekstern MCP-server ved at indstille `type` til `"remote"`. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} `url` er URL for den eksterne MCP server, og med indstillingen `headers` kan du sende en liste over overskrifter ind. * * * #### [Indstillinger](https://opencode.ai/docs/da/mcp-servers/#indstillinger-1) | Mulighed | Skriv | Påkrævet | Beskrivelse | | --- | --- | --- | --- | | `type` | String | Y | Type MCP serverforbindelse, skal være `"remote"`. | | `url` | String | Y | URL af den eksterne MCP-server. | | `enabled` | Boolean | | Aktiver eller deaktiver MCP-serveren ved opstart. | | `headers` | Object | | Overskrifter til at sende med anmodningen. | | `oauth` | Object | | OAuth-godkendelseskonfiguration. Se afsnittet [OAuth](https://opencode.ai/docs/da/mcp-servers/#oauth)
nedenfor. | | `timeout` | Nummer | | Timeout i ms for at hente værktøjer fra MCP-serveren. Standard er 5000 (5 sekunder). | * * * [OAuth](https://opencode.ai/docs/da/mcp-servers/#oauth) -------------------------------------------------------- OpenCode håndterer automatisk OAuth-godkendelse for eksterne MCP-servere. Når en server kræver godkendelse, vil OpenCode: 1. Registrer 401-svaret, og start OAuth-flowet 2. Brug **Dynamic Client Registration (RFC 7591)**, hvis det understøtter af serveren 3. Opbevar tokens sikkert til fremtidige anmodninger * * * ### [Automatisk](https://opencode.ai/docs/da/mcp-servers/#automatisk) For de fleste OAuth-aktiverede MCP-servere kræver ingen speciel konfiguration. Bare konfigureret fjernserver: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} Hvis serveren kræver godkendelse, vil OpenCode bede dig om at godkende, når du prøver at bruge den første gang. Hvis ikke, kan du [manually trigger the flow](https://opencode.ai/docs/da/mcp-servers/#authenticating) med `opencode mcp auth `. * * * ### [Forhåndsregistreret](https://opencode.ai/docs/da/mcp-servers/#forh%C3%A5ndsregistreret) Hvis du har klientlegitimationsoplysninger fra MCP-serverudbyderen, kan du konfigurere dem: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [Godkendelse](https://opencode.ai/docs/da/mcp-servers/#godkendelse) Du kan manuelt udløse godkendelse eller administrere legitimationsoplysninger. Godkendt med en specifik MCP-server: opencode mcp auth my-oauth-server Liste over alle MCP-servere og deres godkendelsesstatus: opencode mcp list Fjern gemte legitimationsoplysninger: opencode mcp logout my-oauth-server Kommandoen `mcp auth` åbner din browser for godkendelse. Når du har godkendt, vil OpenCode opbevare tokens sikkert i `~/.local/share/opencode/mcp-auth.json`. * * * #### [Deaktivering af OAuth](https://opencode.ai/docs/da/mcp-servers/#deaktivering-af-oauth) Hvis du vil deaktivere automatisk OAuth for en server (f.eks. for servere, der bruger API-nøgler i stedet), skal du indstille `oauth` til `false`: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [OAuth-indstillinger](https://opencode.ai/docs/da/mcp-servers/#oauth-indstillinger) | Mulighed | Skriv | Beskrivelse | | --- | --- | --- | | `oauth` | Object \| false | OAuth-konfigurationsobjekt eller `false` for at deaktivere OAuth-auto-detektion. | | `clientId` | String | OAuth-klient-id. Hvis det ikke er angivet, vil dynamisk klientregistrering blive forsøgt. | | `clientSecret` | String | OAuth-klienthemmelighed, hvis det kræves af autorisationsserveren. | | `scope` | String | OAuth-omfang at anmode om under godkendelse. | #### [Fejlfinding](https://opencode.ai/docs/da/mcp-servers/#fejlfinding) Hvis en ekstern MCP-server ikke kan godkendes, kan du diagnosticere problemer med: # View auth status for all OAuth-capable serversopencode mcp auth list # Debug connection and OAuth flow for a specific serveropencode mcp debug my-oauth-server Kommandoen `mcp debug` viser den aktuelle godkendelsesstatus, tester HTTP-forbindelse og forsøger OAuth-opdagelsesflowet. * * * [Administration](https://opencode.ai/docs/da/mcp-servers/#administration) -------------------------------------------------------------------------- Dine MCPs er tilgængelige som værktøjer i **TK\_** sammen med indbyggede værktøjer. Så du kan administrere dem gennem OpenCode-konfigurationen som ethvert andet værktøj. * * * ### [Global](https://opencode.ai/docs/da/mcp-servers/#global) Det betyder, at du kan aktivere eller deaktivere dem globalt. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} Vi kan også bruge et globmønster til at deaktivere alle matchende MCPs. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} Her bruger vi globmønsteret `my-mcp*` til at deaktivere alle MCPs. * * * ### [Per agent](https://opencode.ai/docs/da/mcp-servers/#per-agent) Hvis du har et stort antal MCP-servere, vil du måske kun aktivere dem pr. agent og deaktivere dem globalt. Sådan gør du: 1. Deaktiver det som et værktøj globalt. 2. Aktiver MCP-serveren som et værktøj i din [agent config](https://opencode.ai/docs/agents#tools) . { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [Glob-mønstre](https://opencode.ai/docs/da/mcp-servers/#glob-m%C3%B8nstre) Glob-mønsteret bruger simple regex-globing-mønstre: * `*` matcher nul eller flere af ethvert tegn (f.eks. `"my-mcp*"` matcher `my-mcp_search`, `my-mcp_list` osv.) * `?` matcher nøjagtigt ét tegn * Alle andre karakterer matcher bogstaveligt talt * * * [Eksempler](https://opencode.ai/docs/da/mcp-servers/#eksempler) ---------------------------------------------------------------- Nedenfor er eksempler på nogle almindelige MCP-servere. Du kan indsende en PR, hvis du vil dokumentere andre servere. * * * ### [Sentry](https://opencode.ai/docs/da/mcp-servers/#sentry) Tilføj [Sentry MCP server](https://mcp.sentry.dev/) for at interagere med dine Sentry-projekter og -problemer. { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} Efter tilføjelse af konfigurationen skal du godkende med Sentry: opencode mcp auth sentry Dette åbner et browservindue for at fuldføre OAuth-flowet og forbinde OpenCode til din Sentry-konto. Når du er godkendt, kan du bruge Sentry-værktøjer i dine prompter til at forespørge om problemer, projekter og fejldata. Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/da/mcp-servers/#context7) Tilføj [Context7 MCP server](https://github.com/upstash/context7) for at søge i dokumenter. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} Hvis du har tilmeldt dig en gratis konto, kan du bruge din API-nøgle og få højere satsgrænser. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} Her antager vi, at du har sat miljøvariablen `CONTEXT7_API_KEY`. Føj `use context7` til dine prompter for at bruge Context7 MCP server. Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 Alternativt kan du tilføje noget som dette til din [AGENTS.md](https://opencode.ai/docs/rules/) . When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/da/mcp-servers/#grep-by-vercel) Tilføj serveren [Grep by Vercel](https://grep.app/) MCP for at søge gennem kodestykker på GitHub. { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} Da vi navngav vores MCP-server `gh_grep`, kan du tilføje `use the gh_grep tool` til dine prompter for at få agenten til at bruge den. What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool Alternativt kan du tilføje noget som dette til din [AGENTS.md](https://opencode.ai/docs/rules/) . If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # Serwery MCP | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/mcp-servers/#_top) Serwery MCP =========== Dodaj lokalne i zdalne narzędzie MCP. Możesz dodać dodatkowe informacje do opencode za pomocą _Model Context Protocol_, w skrócie MCP. opencode obsługuje zarówno serwery lokalne, jak i zdalne. Po dodaniu narzędzi MCP są automatycznie dostępne dla LLM wraz z narzędziami narzędziowymi. * * * #### [Zastrzeżenia](https://opencode.ai/docs/pl/mcp-servers/#zastrze%C5%BCenia) Kiedy używasz serwera MCP, zmieniając kontekst. Może szybko się sumować, jeśli masz dużo narzędzia. Zalecamy ostrożność, z jakich serwerów MCP korzystasz. Niektóre serwery MCP, takie jak serwer MCP GitHub, mają szerokie możliwości dodawania wielu tokenów i mogą łatwo przekraczać limit kontekstu. * * * [Włączać](https://opencode.ai/docs/pl/mcp-servers/#w%C5%82%C4%85cza%C4%87) --------------------------------------------------------------------------- Dostępny serwery MCP w [opencode Config](https://opencode.ai/docs/config/) w `mcp`. Dodaj każdy MCP z unikalną nazwą. Możesz zgłosić się do tego MCP po nazwie, pytając LLM. { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} Możesz także wyłączyć serwer, ustawiając `enabled` na `false`. Jest to urządzenie, które jest urządzeniem biologicznym, bez usuwania z urządzenia. * * * ### [Zastępowanie zdalnych ustawień domyślnych](https://opencode.ai/docs/pl/mcp-servers/#zast%C4%99powanie-zdalnych-ustawie%C5%84-domy%C5%9Blnych) Organizacje mogą udostępniać serwery MCP za pośrednictwem punktu końcowego `.well-known/opencode`. Serwer może być podłączony, dzięki czemu użytkownicy mogą wybrać te, których. Aby włączyć serwer ze zdalnej konfiguracji organizacji, dodaj go do wyłączenia za pomocą `enabled: true`: { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} Lokalne wartości konfiguracyjne za występujące zdalne wartości. Aby uzyskać więcej informacji, zobacz [pierwszeństwo konfiguracji](https://opencode.ai/docs/config#precedence-order) . * * * [Lokalny](https://opencode.ai/docs/pl/mcp-servers/#lokalny) ------------------------------------------------------------ Dodaj lokalne serwery MCP za pomocą `type` do `"local"` w obiekcie MCP. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} Polecenie sposobu uruchamiania lokalnego serwera MCP. Można także zainstalować listę konfiguracyjną. Oto przykładowy sposób dodania testowego serwera MCP [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) . { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} Aby z niego skorzystać, można dodać `use the mcp_everything tool` do moich podpowiedzi. use the mcp_everything tool to add the number 3 and 4 * * * #### [Opcje](https://opencode.ai/docs/pl/mcp-servers/#opcje) Oto wszystkie opcje lokalnego serwera MCP. | Opcja | Wpisz | Wymagane | Opis | | --- | --- | --- | --- | | `type` | String | Y | Typ połączenia z serwerem MCP musi być `"local"`. | | `command` | Array | Y | Polecenie i argumenty uruchamiające serwer MCP. | | `environment` | Object | | Zmienne ustawienia podczas uruchamiania serwera. | | `enabled` | Boolean | | Włącz lub wyłącz serwer MCP podczas uruchamiania. | | `timeout` | Number | | Limit czasu w ms na pobieranie narzędzia z serwera MCP. Wartość domyślna do 5000 (5 sekund). | * * * [Zdalny](https://opencode.ai/docs/pl/mcp-servers/#zdalny) ---------------------------------------------------------- Dodaj zdalne serwery MCP, ustawiając `type` na `"remote"`. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} `url` na adres URL zdalnego serwera MCP i za pomocą opcji `headers` można znaleźć listę nagłówków. * * * #### [Opcje](https://opencode.ai/docs/pl/mcp-servers/#opcje-1) | Opcja | Wpisz | Wymagane | Opis | | --- | --- | --- | --- | | `type` | String | Y | Typ połączenia z serwerem MCP musi być `"remote"`. | | `url` | String | Y | Adres URL zdalnego serwera MCP. | | `enabled` | Boolean | | Włącz lub wyłącz serwer MCP podczas uruchamiania. | | `headers` | Object | | Nagłówki do wysłania z wprowadzenia. | | `oauth` | Object | | Konfiguracja uwierzytelniania OAuth. Zobacz sekcję [OAuth](https://opencode.ai/docs/pl/mcp-servers/#oauth)
poniżej. | | `timeout` | Number | | Limit czasu w ms na pobieranie narzędzia z serwera MCP. Wartość domyślna do 5000 (5 sekund). | * * * [OAuth](https://opencode.ai/docs/pl/mcp-servers/#oauth) -------------------------------------------------------- opencode automatyczne uwierzytelnianie OAuth dla zdalnych serwerów MCP. Gdy serwer wymaga uwierzytelnienia, opencode: 1. Wykryj odpowiedź 401 i zainijuj przepływ OAuth 2. używa **Dynamicznej rejestracji klienta (RFC 7591)**, jeśli jest obsługiwana przez serwer 3. Bezpiecznie przechowuj tokeny na wypadek ewentualnego zastosowania * * * ### [Automatyczny](https://opencode.ai/docs/pl/mcp-servers/#automatyczny) W innym serwerze MCP z włączoną funkcją OAuth nie jest wymagana specjalna funkcja. Dostępny serwer bezprzewodowy: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} Jeśli serwer wymaga uwierzytelnienia, opencode poprosi Cię o uwierzytelnienie przy próbie jego użycia. Jeśli nie, możesz \[ręcznie podłączyć przepływ\] (#authenticating) za pomocą `opencode mcp auth `. * * * ### [Wstępnie zarejestrowany](https://opencode.ai/docs/pl/mcp-servers/#wst%C4%99pnie-zarejestrowany) Jeśli posiadasz dostęp do klienta od dostawcy serwera MCP, możesz je udostępnić: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [Uwierzytelnianie](https://opencode.ai/docs/pl/mcp-servers/#uwierzytelnianie) Możesz podać potwierdzenie lub potwierdzenie poświadczenia. Uwierzytelnij się za pomocą standardowego serwera MCP: opencode mcp auth my-oauth-server Lista wszystkich serwerów MCP i ich status uwierzytelnienia: opencode mcp list Usuń zapisane dane uwierzytelniające: opencode mcp logout my-oauth-server Komenda `mcp auth` została udostępniona w celu autoryzacji. Po autoryzacji opencode bezpieczne przechowa tokeny w `~/.local/share/opencode/mcp-auth.json`. * * * #### [Wyłączanie OAuth](https://opencode.ai/docs/pl/mcp-servers/#wy%C5%82%C4%85czanie-oauth) Jeśli chcesz włączyć automatyczne OAuth dla serwera (np. dla serwerów, które zamiast tego używać kluczy API), ustaw `oauth` na `false`: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [Opcje OAuth](https://opencode.ai/docs/pl/mcp-servers/#opcje-oauth) | Opcja | Wpisz | Opis | | --- | --- | --- | | `oauth` | Object \| false | Obiekt konfiguracyjny OAuth lub `false`, aby wyłączyć automatyczne wykrywanie OAuth. | | `clientId` | String | Identyfikator klienta OAuth. Jeżeli nie zostanie podany, zostanie podjęta próba dynamicznej rejestracji klienta. | | `clientSecret` | String | Sekret klienta OAuth, plik jest wymagany przez serwer autoryzacji. | | `scope` | String | Zakresy protokołu OAuth, których należy żądać podczas autoryzacji. | #### [Debugowanie](https://opencode.ai/docs/pl/mcp-servers/#debugowanie) Jeśli serwer MCP nie może zostać uwierzytelniony, możesz zdiagnozować problemy z: # View auth status for all OAuth-capable serversopencode mcp auth list # Debug connection and OAuth flow for a specific serveropencode mcp debug my-oauth-server Komenda `mcp debug` wyświetlanie stanu uwierzytelniania, testuje sprawdzanie protokołu HTTP i sprawdzenie sprawdzenia procesu OAuth. * * * [Zarządzać](https://opencode.ai/docs/pl/mcp-servers/#zarz%C4%85dza%C4%87) -------------------------------------------------------------------------- Twoje MCP są dostępne jako narzędzie w opencode, obok narzędzi dodatkowych. Można to zrobić poprzez podłączenie opencode, jak również w innym przypadku. * * * ### [Światowy](https://opencode.ai/docs/pl/mcp-servers/#%C5%9Bwiatowy) Możesz to włączyć lub wyłączyć globalnie. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} Dostępne są również wzorca globu, aby wyłączyć wszystkie dyski MCP. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} Tutaj znajdziesz wzorca globalnego `my-mcp*`, aby wyłączyć wszystkie MCP. * * * ### [Na agenta](https://opencode.ai/docs/pl/mcp-servers/#na-agenta) Jeśli masz największe serwery MCP, możesz włączyć je tylko dla poszczególnych agentów i być globalnie. Aby to zrobić: 1. Wyłącz go jako narzędzie globalnie. 2. W [konfiguracji agenta](https://opencode.ai/docs/agents#tools) włącz serwer MCP jako narzędzie. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [Wzory globusów](https://opencode.ai/docs/pl/mcp-servers/#wzory-globus%C3%B3w) Wzorzec glob wykorzystuje proste wzorce globowania regularnych: * `*` dopasowuje zero lub więcej dowolnego znaku (np. `"my-mcp*"` dopasowuje `my-mcp_search`, `my-mcp_list` itd.) * `?` odpowiada dokładnie jednemu znakowi * Wszystkie pozostałe znaki pasują dosłownie * * * [Przykłady](https://opencode.ai/docs/pl/mcp-servers/#przyk%C5%82ady) --------------------------------------------------------------------- Poniżej znajdują się przykłady niektórych serwerów MCP. Twój prywatny PR, udostępniany przez inne serwery. * * * ### [Sentry](https://opencode.ai/docs/pl/mcp-servers/#sentry) Dodaj [serwer Sentry MCP](https://mcp.sentry.dev/) , aby móc wejść w interakcję z projektem i udostępnić Sentry. { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} Po dodaniu konfiguracji uwierzytelnij się za pomocą Sentry: opencode mcp auth sentry Spowoduje otwarcie okna konfiguracji, w którym można zakończyć proces OAuth i połączyć opencode z kontem Sentry. Po uwierzytelnieniu oprogramowania Sentry w swoich monitach, aby rozprzestrzeniać zagrożenia, dane i błędy. Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/pl/mcp-servers/#context7) Dodaj [serwer Context7 MCP](https://github.com/upstash/context7) , aby przeszukać dokumenty. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} Jeśli założyłeś darmowe konto, możesz użyć klucza API i uzyskać wyższy limit stawek. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} Załóż tutaj, że masz ustawioną zmienną środowiskową `CONTEXT7_API_KEY`. Dodaj `use context7` do swoich podpowiedzi, aby skorzystać z serwera Context7 MCP. Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 Alternatywnie możesz zadać coś takiego do pliku [AGENTS.md](https://opencode.ai/docs/rules/) . When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/pl/mcp-servers/#grep-by-vercel) Dodaj serwer MCP [Grep by Vercel](https://grep.app/) , aby przeszukać fragmenty kodu w serwisie GitHub. { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} Nazwaliśmy nasz serwer MCP `gh_grep`, możesz dodać `use the gh_grep tool` do swoich podpowiedzi, aby agent mógł z niego korzystać. What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool Alternatywnie możesz zadać coś takiego do pliku [AGENTS.md](https://opencode.ai/docs/rules/) . If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # Ekosystem | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/ecosystem/#_top) Ekosystem ========= Projekty i integracje zbudowane przy użyciu OpenCode. Zbiór projektów społeczności zbudowanych na OpenCode. Możesz również sprawdzić [awesome-opencode](https://github.com/awesome-opencode/awesome-opencode) oraz [opencode.cafe](https://opencode.cafe/) , społeczność agregującą ekosystem i społeczność. * * * [Wtyczki](https://opencode.ai/docs/pl/ecosystem/#wtyczki) ---------------------------------------------------------- | Nazwa | Opis | | --- | --- | | [opencode-daytona](https://github.com/daytonaio/daytona/tree/main/libs/opencode-plugin) | Automatyczne uruchamianie sesji OpenCode w izolowanych piaskownicach Daytona z synchronizacją git i podglądem na żywo | | [opencode-helicone-session](https://github.com/H2Shami/opencode-helicone-session) | Automatyczne wstrzykiwanie nagłówków sesji Helicone do grupowania żądań | | [opencode-type-inject](https://github.com/nick-vi/opencode-type-inject) | Automatyczne wstrzykiwanie typów TypeScript/Svelte do odczytów plików za pomocą narzędzi wyszukiwania | | [opencode-openai-codex-auth](https://github.com/numman-ali/opencode-openai-codex-auth) | Użyj subskrypcji ChatGPT Plus/Pro zamiast kredytów API | | [opencode-gemini-auth](https://github.com/jenslys/opencode-gemini-auth) | Użyj istniejącego planu Gemini zamiast płatności za API | | [opencode-antigravity-auth](https://github.com/NoeFabris/opencode-antigravity-auth) | Użyj darmowych modeli Antigravity zamiast płatności za API | | [opencode-devcontainers](https://github.com/athal7/opencode-devcontainers) | Izolacja kontenerów deweloperskich dla wielu gałęzi z płytkim klonowaniem i automatycznie przypisywanymi portami | | [opencode-google-antigravity-auth](https://github.com/shekohex/opencode-google-antigravity-auth) | Wtyczka Google Antigravity OAuth ze wsparciem dla wyszukiwarki Google i bardziej niezawodną obsługą API | | [opencode-dynamic-context-pruning](https://github.com/Tarquinen/opencode-dynamic-context-pruning) | Optymalizacja zużycia tokenów poprzez usuwanie przestarzałych wyników narzędzi | | [opencode-vibeguard](https://github.com/inkdust2021/opencode-vibeguard) | Redagowanie sekretów/danych osobowych do placeholderów w stylu VibeGuard przed wywołaniem LLM; przywracanie lokalnie | | [opencode-websearch-cited](https://github.com/ghoulr/opencode-websearch-cited.git) | Dodaj natywną obsługę wyszukiwania w sieci dla wspieranych dostawców w stylu Google grounded | | [opencode-pty](https://github.com/shekohex/opencode-pty.git) | Umożliwia agentom AI uruchamianie procesów w tle w PTY i wysyłanie do nich interaktywnych danych wejściowych. | | [opencode-shell-strategy](https://github.com/JRedeker/opencode-shell-strategy) | Instrukcje dla nieinteraktywnych poleceń powłoki - zapobiega zawieszeniom operacji zależnych od TTY | | [opencode-wakatime](https://github.com/angristan/opencode-wakatime) | Śledź użycie OpenCode za pomocą Wakatime | | [opencode-md-table-formatter](https://github.com/franlol/opencode-md-table-formatter/tree/main) | Oczyść tabele markdown generowane przez LLM | | [opencode-morph-plugin](https://github.com/morphllm/opencode-morph-plugin) | Edycja Fast Apply, wyszukiwanie kodu WarpGrep i kompaktowanie kontekstu przez Morph | | [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) | Agenci w tle, wbudowane narzędzia LSP/AST/MCP, wyselekcjonowani agenci, kompatybilność z Claude Code | | [opencode-notificator](https://github.com/panta82/opencode-notificator) | Powiadomienia na pulpicie i alerty dźwiękowe dla sesji OpenCode | | [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Powiadomienia na pulpicie i alerty dźwiękowe dla uprawnień, zakończeń zadań i błędów | | [opencode-zellij-namer](https://github.com/24601/opencode-zellij-namer) | Automatyczne nazywanie sesji Zellij oparte na AI w oparciu o kontekst OpenCode | | [opencode-skillful](https://github.com/zenobi-us/opencode-skillful) | Pozwól agentom OpenCode na leniwe ładowanie promptów na żądanie z odkrywaniem umiejętności i wstrzykiwaniem | | [opencode-supermemory](https://github.com/supermemoryai/opencode-supermemory) | Trwała pamięć między sesjami przy użyciu Supermemory | | [@plannotator/opencode](https://github.com/backnotprop/plannotator/tree/main/apps/opencode-plugin) | Interaktywny przegląd planów z wizualnymi adnotacjami i prywatnym/offline udostępnianiem | | [@openspoon/subtask2](https://github.com/spoons-and-mirrors/subtask2) | Rozszerz komendy /commands OpenCode w potężny system orkiestracji ze szczegółową kontrolą przepływu | | [opencode-scheduler](https://github.com/different-ai/opencode-scheduler) | Planuj cykliczne zadania używając launchd (Mac) lub systemd (Linux) ze składnią cron | | [micode](https://github.com/vtemian/micode) | Ustrukturyzowany przepływ pracy Burza mózgów → Plan → Implementacja z ciągłością sesji | | [octto](https://github.com/vtemian/octto) | Interaktywny interfejs przeglądarkowy do burzy mózgów AI z formularzami wielopytaniowymi | | [opencode-background-agents](https://github.com/kdcokenny/opencode-background-agents) | Agenci w tle w stylu Claude Code z asynchronicznym delegowaniem i trwałością kontekstu | | [opencode-notify](https://github.com/kdcokenny/opencode-notify) | Natywne powiadomienia systemowe dla OpenCode – wiedz, kiedy zadania się zakończą | | [opencode-workspace](https://github.com/kdcokenny/opencode-workspace) | Zestaw orkiestracji wieloagentowej – 16 komponentów, jedna instalacja | | [opencode-worktree](https://github.com/kdcokenny/opencode-worktree) | Bezproblemowe drzewa robocze git dla OpenCode | | [opencode-sentry-monitor](https://github.com/stolinski/opencode-sentry-monitor) | Śledź i debuguj swoich agentów AI za pomocą Sentry AI Monitoring | * * * [Projekty](https://opencode.ai/docs/pl/ecosystem/#projekty) ------------------------------------------------------------ | Nazwa | Opis | | --- | --- | | [kimaki](https://github.com/remorses/kimaki) | Bot Discord do sterowania sesjami OpenCode, zbudowany na SDK | | [opencode.nvim](https://github.com/NickvanDyke/opencode.nvim) | Wtyczka Neovim dla promptów świadomych edytora, zbudowana na API | | [portal](https://github.com/hosenur/portal) | Interfejs webowy mobile-first dla OpenCode przez Tailscale/VPN | | [opencode plugin template](https://github.com/zenobi-us/opencode-plugin-template/) | Szablon do tworzenia wtyczek OpenCode | | [opencode.nvim](https://github.com/sudo-tee/opencode.nvim) | Frontend Neovim dla OpenCode - terminalowy agent kodujący AI | | [ai-sdk-provider-opencode-sdk](https://github.com/ben-vargas/ai-sdk-provider-opencode-sdk) | Dostawca Vercel AI SDK do używania OpenCode przez @opencode-ai/sdk | | [OpenChamber](https://github.com/btriapitsyn/openchamber) | Aplikacja Web / Desktop i rozszerzenie VS Code dla OpenCode | | [OpenCode-Obsidian](https://github.com/mtymek/opencode-obsidian) | Wtyczka Obsidian osadzająca OpenCode w interfejsie Obsidian | | [OpenWork](https://github.com/different-ai/openwork) | Otwartoźródłowa alternatywa dla Claude Cowork, napędzana przez OpenCode | | [ocx](https://github.com/kdcokenny/ocx) | Menedżer rozszerzeń OpenCode z przenośnymi, izolowanymi profilami. | | [CodeNomad](https://github.com/NeuralNomadsAI/CodeNomad) | Aplikacja kliencka Desktop, Web, Mobile i Remote dla OpenCode | * * * [Agenci](https://opencode.ai/docs/pl/ecosystem/#agenci) -------------------------------------------------------- | Nazwa | Opis | | --- | --- | | [Agentic](https://github.com/Cluster444/agentic) | Modułowi agenci AI i komendy do strukturalnego rozwoju | | [opencode-agents](https://github.com/darrenhinde/opencode-agents) | Konfiguracje, prompty, agenci i wtyczki dla ulepszonych przepływów pracy | --- # MCP 伺服器 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/mcp-servers/#_top) MCP 伺服器 ======= 新增本地和遠端 MCP 工具。 您可以透過 _Model Context Protocol_(MCP)為 OpenCode 新增外部工具。OpenCode 同時支援本地和遠端伺服器。 新增後,MCP 工具會自動與內建工具一起提供給 LLM 使用。 * * * #### [注意事項](https://opencode.ai/docs/zh-tw/mcp-servers/#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A0%85) 使用 MCP 伺服器時,它會佔用上下文空間。如果您啟用了大量工具,上下文消耗會迅速增加。因此,我們建議謹慎選擇要使用的 MCP 伺服器。 某些 MCP 伺服器(例如 GitHub MCP 伺服器)往往會消耗大量 Token,很容易超出上下文限制。 * * * [啟用](https://opencode.ai/docs/zh-tw/mcp-servers/#%E5%95%9F%E7%94%A8) --------------------------------------------------------------------- 您可以在 [OpenCode 設定](https://opencode.ai/docs/config/) 的 `mcp` 欄位下定義 MCP 伺服器。為每個 MCP 指定一個唯一的名稱,在提示詞中可以透過該名稱來參照對應的 MCP。 { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} 您也可以將 `enabled` 設定為 `false` 來停用某個伺服器。當您想臨時停用某個伺服器而不將其從設定中移除時,這個選項非常有用。 * * * ### [覆寫遠端預設值](https://opencode.ai/docs/zh-tw/mcp-servers/#%E8%A6%86%E5%AF%AB%E9%81%A0%E7%AB%AF%E9%A0%90%E8%A8%AD%E5%80%BC) 組織可以透過其 `.well-known/opencode` 端點提供預設的 MCP 伺服器。這些伺服器可能預設處於停用狀態,允許使用者按需啟用。 要啟用組織遠端設定中的某個伺服器,請在本地設定中新增該伺服器並設定 `enabled: true`: { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} 本地設定值會覆寫遠端預設值。詳情請參閱[設定優先順序](https://opencode.ai/docs/config#precedence-order) 。 * * * [本地](https://opencode.ai/docs/zh-tw/mcp-servers/#%E6%9C%AC%E5%9C%B0) --------------------------------------------------------------------- 透過在 MCP 物件中將 `type` 設定為 `"local"` 來新增本地 MCP 伺服器。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} `command` 用於指定本地 MCP 伺服器的啟動指令。您還可以傳入一組環境變數。 例如,以下是新增測試用的 [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP 伺服器的方法。 { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} 要使用它,可以在提示詞中新增 `use the mcp_everything tool`。 use the mcp_everything tool to add the number 3 and 4 * * * #### [選項](https://opencode.ai/docs/zh-tw/mcp-servers/#%E9%81%B8%E9%A0%85) 以下是設定本地 MCP 伺服器的所有選項。 | 選項 | 類型 | 必填 | 描述 | | --- | --- | --- | --- | | `type` | 字串 | 是 | MCP 伺服器連線類型,必須為 `"local"`。 | | `command` | 陣列 | 是 | 執行 MCP 伺服器的指令及參數。 | | `environment` | 物件 | | 執行伺服器時設定的環境變數。 | | `enabled` | 布林值 | | 啟動時啟用或停用該 MCP 伺服器。 | | `timeout` | 數字 | | 從 MCP 伺服器取得工具的逾時時間(毫秒)。預設為 5000(即 5 秒)。 | * * * [遠端](https://opencode.ai/docs/zh-tw/mcp-servers/#%E9%81%A0%E7%AB%AF) --------------------------------------------------------------------- 透過將 `type` 設定為 `"remote"` 來新增遠端 MCP 伺服器。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} `url` 是遠端 MCP 伺服器的位址,透過 `headers` 選項可以傳入一組請求標頭。 * * * #### [選項](https://opencode.ai/docs/zh-tw/mcp-servers/#%E9%81%B8%E9%A0%85-1) | 選項 | 類型 | 必填 | 描述 | | --- | --- | --- | --- | | `type` | 字串 | 是 | MCP 伺服器連線類型,必須為 `"remote"`。 | | `url` | 字串 | 是 | 遠端 MCP 伺服器的 URL。 | | `enabled` | 布林值 | | 啟動時啟用或停用該 MCP 伺服器。 | | `headers` | 物件 | | 隨請求傳送的請求標頭。 | | `oauth` | 物件 | | OAuth 身分驗證設定。詳見下方 [OAuth](https://opencode.ai/docs/zh-tw/mcp-servers/#oauth)
部分。 | | `timeout` | 數字 | | 從 MCP 伺服器取得工具的逾時時間(毫秒)。預設為 5000(即 5 秒)。 | * * * [OAuth](https://opencode.ai/docs/zh-tw/mcp-servers/#oauth) ----------------------------------------------------------- OpenCode 會自動處理遠端 MCP 伺服器的 OAuth 身分驗證。當伺服器需要身分驗證時,OpenCode 將: 1. 偵測 401 回應並啟動 OAuth 流程 2. 在伺服器支援的情況下使用**動態用戶端註冊(RFC 7591)** 3. 安全地儲存 Token 以供後續請求使用 * * * ### [自動認證](https://opencode.ai/docs/zh-tw/mcp-servers/#%E8%87%AA%E5%8B%95%E8%AA%8D%E8%AD%89) 對於大多數支援 OAuth 的 MCP 伺服器,無需特殊設定。只需設定遠端伺服器即可: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} 如果伺服器需要身分驗證,OpenCode 會在您首次使用時提示您進行認證。您也可以使用 `opencode mcp auth ` [手動觸發認證流程](https://opencode.ai/docs/zh-tw/mcp-servers/#authenticating) 。 * * * ### [預先註冊](https://opencode.ai/docs/zh-tw/mcp-servers/#%E9%A0%90%E5%85%88%E8%A8%BB%E5%86%8A) 如果您已經從 MCP 伺服器提供商處取得了用戶端憑證,可以直接設定: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [身分驗證](https://opencode.ai/docs/zh-tw/mcp-servers/#%E8%BA%AB%E5%88%86%E9%A9%97%E8%AD%89) 您可以手動觸發身分驗證或管理憑證。 對特定 MCP 伺服器進行身分驗證: opencode mcp auth my-oauth-server 列出所有 MCP 伺服器及其認證狀態: opencode mcp list 刪除已儲存的憑證: opencode mcp logout my-oauth-server `mcp auth` 指令會開啟瀏覽器進行授權。授權完成後,OpenCode 會將 Token 安全地儲存在 `~/.local/share/opencode/mcp-auth.json` 中。 * * * #### [停用 OAuth](https://opencode.ai/docs/zh-tw/mcp-servers/#%E5%81%9C%E7%94%A8-oauth) 如果您想為某個伺服器停用自動 OAuth(例如,該伺服器使用 API 金鑰而非 OAuth),可以將 `oauth` 設定為 `false`: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [OAuth 選項](https://opencode.ai/docs/zh-tw/mcp-servers/#oauth-%E9%81%B8%E9%A0%85) | 選項 | 類型 | 描述 | | --- | --- | --- | | `oauth` | 物件 \| `false` | OAuth 設定物件,或設為 `false` 以停用 OAuth 自動偵測。 | | `clientId` | 字串 | OAuth 用戶端 ID。如果未提供,將嘗試動態用戶端註冊。 | | `clientSecret` | 字串 | OAuth 用戶端密鑰(如果授權伺服器要求提供)。 | | `scope` | 字串 | 授權時請求的 OAuth 作用域。 | #### [偵錯](https://opencode.ai/docs/zh-tw/mcp-servers/#%E5%81%B5%E9%8C%AF) 如果遠端 MCP 伺服器身分驗證失敗,您可以透過以下方式診斷問題: # 查看所有支援 OAuth 的伺服器的認證狀態opencode mcp auth list # 偵錯特定伺服器的連線和 OAuth 流程opencode mcp debug my-oauth-server `mcp debug` 指令會顯示當前認證狀態、測試 HTTP 連線,並嘗試執行 OAuth 發現流程。 * * * [管理](https://opencode.ai/docs/zh-tw/mcp-servers/#%E7%AE%A1%E7%90%86) --------------------------------------------------------------------- 您的 MCP 在 OpenCode 中作為工具使用,與內建工具並列。因此,您可以像管理其他工具一樣,透過 OpenCode 設定來管理它們。 * * * ### [全域](https://opencode.ai/docs/zh-tw/mcp-servers/#%E5%85%A8%E5%9F%9F) 您可以全域啟用或停用 MCP 工具。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} 也可以使用 glob 模式來停用所有符合條件的 MCP。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} 這裡使用 glob 模式 `my-mcp*` 來停用所有 MCP。 * * * ### [按代理設定](https://opencode.ai/docs/zh-tw/mcp-servers/#%E6%8C%89%E4%BB%A3%E7%90%86%E8%A8%AD%E5%AE%9A) 如果您有大量 MCP 伺服器,可以選擇全域停用它們,然後僅在特定代理中啟用。具體做法: 1. 全域停用該工具。 2. 在[代理設定](https://opencode.ai/docs/agents#tools) 中,將 MCP 伺服器作為工具啟用。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [Glob 模式](https://opencode.ai/docs/zh-tw/mcp-servers/#glob-%E6%A8%A1%E5%BC%8F) glob 模式使用簡單的正規表示式萬用字元規則: * `*` 比對零個或多個任意字元(例如,`"my-mcp*"` 比對 `my-mcp_search`、`my-mcp_list` 等) * `?` 比對恰好一個字元 * 其他字元按字面值比對 * * * [範例](https://opencode.ai/docs/zh-tw/mcp-servers/#%E7%AF%84%E4%BE%8B) --------------------------------------------------------------------- 以下是一些常見 MCP 伺服器的設定範例。如果您想記錄其他伺服器的用法,歡迎提交 PR。 * * * ### [Sentry](https://opencode.ai/docs/zh-tw/mcp-servers/#sentry) 新增 [Sentry MCP 伺服器](https://mcp.sentry.dev/) 以與您的 Sentry 專案和問題進行互動。 { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} 新增設定後,使用 Sentry 進行身分驗證: opencode mcp auth sentry 這會開啟瀏覽器視窗完成 OAuth 流程,將 OpenCode 連結到您的 Sentry 帳號。 認證完成後,您可以在提示詞中使用 Sentry 工具來查詢問題、專案和錯誤資料。 Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/zh-tw/mcp-servers/#context7) 新增 [Context7 MCP 伺服器](https://github.com/upstash/context7) 以搜尋文件。 { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} 如果您註冊了免費帳號,可以使用 API 金鑰來取得更高的速率限制。 { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} 這裡假設您已經設定了 `CONTEXT7_API_KEY` 環境變數。 在提示詞中新增 `use context7` 即可使用 Context7 MCP 伺服器。 Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 您也可以在 [AGENTS.md](https://opencode.ai/docs/rules/) 中新增類似的規則。 When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/zh-tw/mcp-servers/#grep-by-vercel) 新增 [Grep by Vercel](https://grep.app/) MCP 伺服器以搜尋 GitHub 上的程式碼片段。 { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} 由於我們將 MCP 伺服器命名為 `gh_grep`,您可以在提示詞中新增 `use the gh_grep tool` 來讓代理使用它。 What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool 您也可以在 [AGENTS.md](https://opencode.ai/docs/rules/) 中新增類似的規則。 If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # GitHub | OpenCode [Skip to content](https://opencode.ai/docs/th/github/#_top) GitHub ====== ใช้ OpenCode ในปัญหา GitHub และคำขอแบบดึง OpenCode ผสานรวมกับเวิร์กโฟลว์ GitHub ของคุณ พูดถึง `/opencode` หรือ `/oc` ในความคิดเห็นของคุณ แล้ว OpenCode จะดำเนินการงานภายใน GitHub Actions runner ของคุณ * * * [คุณสมบัติ](https://opencode.ai/docs/th/github/#%E0%B8%84%E0%B8%B8%E0%B8%93%E0%B8%AA%E0%B8%A1%E0%B8%9A%E0%B8%B1%E0%B8%95%E0%B8%B4) ----------------------------------------------------------------------------------------------------------------------------------- * **Issue Triage**: ขอให้ OpenCode ตรวจสอบปัญหาและอธิบายให้คุณทราบ * **แก้ไขและนำไปใช้**: ขอให้ OpenCode แก้ไขปัญหาหรือใช้ฟีเจอร์ และมันจะทำงานในสาขาใหม่และส่ง PR พร้อมการเปลี่ยนแปลงทั้งหมด * **ปลอดภัย**: OpenCode ทำงานภายในรันเนอร์ของ GitHub ของคุณ * * * [การติดตั้ง](https://opencode.ai/docs/th/github/#%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) --------------------------------------------------------------------------------------------------------------------------------------------- รันคำสั่งต่อไปนี้ในโปรเจ็กต์ที่อยู่ใน repo GitHub: opencode github install ขั้นตอนนี้จะแนะนำคุณตลอดขั้นตอนการติดตั้งแอป GitHub การสร้างเวิร์กโฟลว์ และการตั้งค่าความลับ * * * ### [การตั้งค่าด้วยตนเอง](https://opencode.ai/docs/th/github/#%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%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) หรือคุณสามารถตั้งค่าได้ด้วยตนเอง 1. **ติดตั้งแอป GitHub** ไปที่ [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) ตรวจสอบให้แน่ใจว่าได้ติดตั้งบนที่เก็บเป้าหมายแล้ว 2. **เพิ่มขั้นตอนการทำงาน** เพิ่มไฟล์เวิร์กโฟลว์ต่อไปนี้ไปที่ `.github/workflows/opencode.yml` ใน repo ของคุณ ตรวจสอบให้แน่ใจว่าได้ตั้งค่า `model` ที่เหมาะสมและคีย์ API ที่จำเป็นใน `env` name: opencode on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: opencode: if: | contains(github.event.comment.body, '/oc') || contains(github.event.comment.body, '/opencode') runs-on: ubuntu-latest permissions: id-token: write steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 1 persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 # share: true # github_token: xxxx 3. **เก็บคีย์ API เป็นความลับ** ในองค์กรหรือโครงการ **การตั้งค่า** ให้ขยาย **ความลับและตัวแปร** ทางด้านซ้าย แล้วเลือก **การดำเนินการ** และเพิ่มคีย์ API ที่จำเป็น * * * [การกำหนดค่า](https://opencode.ai/docs/th/github/#%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) ------------------------------------------------------------------------------------------------------------------------------------------------------- * `model`: โมเดลที่จะใช้กับ OpenCode ใช้รูปแบบของ `provider/model` นี่คือ **จำเป็น** * `agent`: ตัวแทนที่จะใช้ จะต้องเป็นตัวแทนหลัก ย้อนกลับไปที่ `default_agent` จาก config หรือ `"build"` หากไม่พบ * `share`: ไม่ว่าจะแชร์เซสชัน OpenCode หรือไม่ ค่าเริ่มต้นเป็น **จริง** สำหรับที่เก็บข้อมูลสาธารณะ * `prompt`: ตัวเลือกที่กำหนดเองพร้อมท์เพื่อแทนที่การทำงานเริ่มต้น ใช้สิ่งนี้เพื่อปรับแต่งวิธีที่ OpenCode ประมวลผลคำขอ * `token`: GitHub Access Token เสริมสำหรับการดำเนินการ เช่น การสร้างความคิดเห็น การยอมรับการเปลี่ยนแปลง และการเปิดคำขอดึง ตามค่าเริ่มต้น OpenCode จะใช้โทเค็นการเข้าถึงการติดตั้งจาก OpenCode GitHub App ดังนั้นคอมมิต แสดงความคิดเห็น และคำขอดึงข้อมูลจะปรากฏว่ามาจากแอป หรือคุณสามารถใช้ [ในตัว `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) ของ GitHub Action runner ได้โดยไม่ต้องติดตั้งแอป OpenCode GitHub เพียงตรวจสอบให้แน่ใจว่าได้ให้สิทธิ์ที่จำเป็นในขั้นตอนการทำงานของคุณ: permissions: id-token: write contents: write pull-requests: write issues: write คุณยังสามารถใช้ [Personal Access Token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT) ได้หากต้องการ * * * [กิจกรรมที่รองรับ](https://opencode.ai/docs/th/github/#%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%81%E0%B8%A3%E0%B8%A3%E0%B8%A1%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- OpenCode สามารถทริกเกอร์ได้โดยเหตุการณ์ GitHub ต่อไปนี้: | ประเภทเหตุการณ์ | กระตุ้นโดย | รายละเอียด | | --- | --- | --- | | `issue_comment` | แสดงความคิดเห็นในประเด็นหรือประชาสัมพันธ์ | พูดถึง `/opencode` หรือ `/oc` ในความคิดเห็นของคุณ OpenCode อ่านบริบทและสามารถสร้างสาขา เปิด PR หรือตอบกลับได้ | | `pull_request_review_comment` | แสดงความคิดเห็นเกี่ยวกับบรรทัดรหัสเฉพาะในการประชาสัมพันธ์ | พูดถึง `/opencode` หรือ `/oc` ในขณะที่ตรวจสอบโค้ด OpenCode รับเส้นทางไฟล์ หมายเลขบรรทัด และบริบทที่แตกต่าง | | `issues` | ปัญหาเปิดหรือแก้ไข | ทริกเกอร์ OpenCode โดยอัตโนมัติเมื่อมีการสร้างหรือแก้ไขปัญหา ต้องป้อนข้อมูล `prompt` | | `pull_request` | PR เปิดหรืออัปเดตแล้ว | ทริกเกอร์ OpenCode โดยอัตโนมัติเมื่อมีการเปิด ซิงโครไนซ์ หรือเปิด PR อีกครั้ง มีประโยชน์สำหรับการตรวจสอบอัตโนมัติ | | `schedule` | กำหนดการตาม Cron | เรียกใช้ OpenCode ตามกำหนดเวลา ต้องป้อนข้อมูล `prompt` เอาต์พุตไปที่บันทึกและ PR (ไม่มีปัญหาในการแสดงความคิดเห็น) | | `workflow_dispatch` | ทริกเกอร์ด้วยตนเองจาก GitHub UI | ทริกเกอร์ OpenCode ตามความต้องการผ่านแท็บการดำเนินการ ต้องป้อนข้อมูล `prompt` เอาต์พุตไปที่บันทึกและ PR | ### [ตัวอย่างกำหนดการ](https://opencode.ai/docs/th/github/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3) เรียกใช้ OpenCode ตามกำหนดเวลาเพื่อทำงานอัตโนมัติ: name: Scheduled OpenCode Task on: schedule: - cron: "0 9 * * 1" # Every Monday at 9am UTC jobs: opencode: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Checkout repository uses: actions/checkout@v6 with: persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review the codebase for any TODO comments and create a summary. If you find issues worth addressing, open an issue to track them. สำหรับกิจกรรมที่กำหนดเวลาไว้ อินพุต `prompt` เป็นสิ่งที่จำเป็น\*\* เนื่องจากไม่มีความคิดเห็นที่จะดึงคำแนะนำออกมา เวิร์กโฟลว์ตามกำหนดการทำงานโดยไม่มีบริบทผู้ใช้ในการตรวจสอบสิทธิ์ ดังนั้นเวิร์กโฟลว์จะต้องให้สิทธิ์ `contents: write` และ `pull-requests: write` หากคุณคาดหวังให้ OpenCode สร้างสาขาหรือ PR * * * ### [ตัวอย่างคำขอดึง](https://opencode.ai/docs/th/github/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B8%84%E0%B8%B3%E0%B8%82%E0%B8%AD%E0%B8%94%E0%B8%B6%E0%B8%87) ตรวจสอบ PR โดยอัตโนมัติเมื่อมีการเปิดหรืออัปเดต: name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: id-token: write contents: read pull-requests: read issues: read steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-4-20250514 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements สำหรับกิจกรรม `pull_request` หากไม่มีการระบุ `prompt` OpenCode จะใช้ค่าเริ่มต้นในการตรวจสอบคำขอดึง * * * ### [ตัวอย่าง Triage ปัญหา](https://opencode.ai/docs/th/github/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87-triage-%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2) คัดแยกปัญหาใหม่โดยอัตโนมัติ ตัวอย่างนี้กรองไปยังบัญชีที่มีอายุมากกว่า 30 วันเพื่อลดสแปม: name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Check account age id: check uses: actions/github-script@v7 with: script: | const user = await github.rest.users.getByUsername({ username: context.payload.issue.user.login }); const created = new Date(user.data.created_at); const days = (Date.now() - created) / (1000 * 60 * 60 * 24); return days >= 30; result-encoding: string - uses: actions/checkout@v6 if: steps.check.outputs.result == 'true' with: persist-credentials: false - uses: anomalyco/opencode/github@latest if: steps.check.outputs.result == 'true' env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review this issue. If there's a clear fix or relevant docs: - Provide documentation links - Add error handling guidance for code examples Otherwise, do not comment. สำหรับเหตุการณ์ `issues` อินพุต `prompt` นั้น **จำเป็น** เนื่องจากไม่มีความคิดเห็นที่จะดึงคำแนะนำออกมา * * * [ข้อความแจ้งที่กำหนดเอง](https://opencode.ai/docs/th/github/#%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B9%81%E0%B8%88%E0%B9%89%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 สำหรับเวิร์กโฟลว์ของคุณ - uses: anomalyco/opencode/github@latest with: model: anthropic/claude-sonnet-4-5 prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements สิ่งนี้มีประโยชน์สำหรับการบังคับใช้เกณฑ์การตรวจสอบเฉพาะ มาตรฐานการเขียนโค้ด หรือประเด็นมุ่งเน้นที่เกี่ยวข้องกับโครงการของคุณ * * * [ตัวอย่าง](https://opencode.ai/docs/th/github/#%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 ใน GitHub * **อธิบายปัญหา** เพิ่มความคิดเห็นนี้ในปัญหา GitHub /opencode explain this issue OpenCode จะอ่านกระทู้ทั้งหมด รวมถึงความคิดเห็นทั้งหมด และตอบกลับพร้อมคำอธิบายที่ชัดเจน * **แก้ไขปัญหา** ในปัญหา GitHub ให้พูดว่า: /opencode fix this และ OpenCode จะสร้างสาขาใหม่ ดำเนินการเปลี่ยนแปลง และเปิด PR ที่มีการเปลี่ยนแปลง * **ตรวจสอบ PR และทำการเปลี่ยนแปลง** แสดงความคิดเห็นต่อไปนี้ใน GitHub PR Delete the attachment from S3 when the note is removed /oc OpenCode จะดำเนินการเปลี่ยนแปลงที่ร้องขอและส่งมอบให้กับ PR เดียวกัน * **ตรวจสอบบรรทัดรหัสเฉพาะ** แสดงความคิดเห็นโดยตรงบนบรรทัดโค้ดในแท็บ “ไฟล์” ของ PR OpenCode จะตรวจจับไฟล์ หมายเลขบรรทัด และบริบทต่างโดยอัตโนมัติเพื่อให้การตอบสนองที่แม่นยำ [Comment on specific lines in Files tab]/oc add error handling here เมื่อแสดงความคิดเห็นในบรรทัดใดบรรทัดหนึ่ง OpenCode จะได้รับ: * กำลังตรวจสอบไฟล์ที่แน่นอน * บรรทัดโค้ดเฉพาะ * บริบทที่แตกต่างโดยรอบ * ข้อมูลหมายเลขบรรทัด ซึ่งช่วยให้สามารถร้องขอที่ตรงเป้าหมายมากขึ้นโดยไม่จำเป็นต้องระบุเส้นทางไฟล์หรือหมายเลขบรรทัดด้วยตนเอง --- # 主題 | OpenCode [跳到內容](https://opencode.ai/docs/zh-tw/themes/#_top) 主題 == 選擇內建主題或定義您自己的主題。 透過 OpenCode,您可以從多個內建主題中進行選擇,使用能自動適配終端機主題的主題,或者定義您自己的自訂主題。 預設情況下,OpenCode 使用我們自己的 `opencode` 主題。 * * * [終端機要求](https://opencode.ai/docs/zh-tw/themes/#%E7%B5%82%E7%AB%AF%E6%A9%9F%E8%A6%81%E6%B1%82) ---------------------------------------------------------------------------------------------- 為了使主題能夠正確顯示完整的調色盤,您的終端機必須支援**真彩色**(24 位元色)。大多數現代終端機預設支援此功能,但您可能需要手動啟用: * **檢查支援情況**:執行 `echo $COLORTERM` — 輸出應為 `truecolor` 或 `24bit` * **啟用真彩色**:在您的 shell 設定檔中設定環境變數 `COLORTERM=truecolor` * **終端機相容性**:確保您的終端機模擬器支援 24 位元色(大多數現代終端機如 iTerm2、Alacritty、Kitty、Windows Terminal 以及較新版本的 GNOME Terminal 均已支援) 如果沒有真彩色支援,主題可能會出現色彩精度下降的情況,或者回退到最接近的 256 色近似值。 * * * [內建主題](https://opencode.ai/docs/zh-tw/themes/#%E5%85%A7%E5%BB%BA%E4%B8%BB%E9%A1%8C) ------------------------------------------------------------------------------------ OpenCode 自帶多個內建主題。 | 名稱 | 描述 | | --- | --- | | `system` | 自動適配終端機的背景顏色 | | `tokyonight` | 基於 [Tokyonight](https://github.com/folke/tokyonight.nvim)
主題 | | `everforest` | 基於 [Everforest](https://github.com/sainnhe/everforest)
主題 | | `ayu` | 基於 [Ayu](https://github.com/ayu-theme)
暗色主題 | | `catppuccin` | 基於 [Catppuccin](https://github.com/catppuccin)
主題 | | `catppuccin-macchiato` | 基於 [Catppuccin](https://github.com/catppuccin)
主題 | | `gruvbox` | 基於 [Gruvbox](https://github.com/morhetz/gruvbox)
主題 | | `kanagawa` | 基於 [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
主題 | | `nord` | 基於 [Nord](https://github.com/nordtheme/nord)
主題 | | `matrix` | 駭客風格的黑底綠字主題 | | `one-dark` | 基於 [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark 主題 | 我們還在不斷新增更多主題。 * * * [系統主題](https://opencode.ai/docs/zh-tw/themes/#%E7%B3%BB%E7%B5%B1%E4%B8%BB%E9%A1%8C) ------------------------------------------------------------------------------------ `system` 主題旨在自動適配您終端機的配色方案。與使用固定顏色的傳統主題不同,_system_ 主題具有以下特點: * **產生灰階色階**:根據終端機的背景顏色建立自訂灰階色階,確保最佳對比度。 * **使用 ANSI 顏色**:利用標準 ANSI 顏色(0-15)進行語法高亮和 UI 元素渲染,遵循終端機的調色盤設定。 * **保留終端機預設值**:將文字和背景顏色設為 `none`,以保持終端機的原生外觀。 系統主題適合以下使用者: * 希望 OpenCode 與終端機的外觀保持一致 * 使用了自訂終端機配色方案 * 偏好所有終端機應用程式擁有統一的視覺風格 * * * [使用主題](https://opencode.ai/docs/zh-tw/themes/#%E4%BD%BF%E7%94%A8%E4%B8%BB%E9%A1%8C) ------------------------------------------------------------------------------------ 您可以透過 `/theme` 指令調出主題選擇介面來選擇主題,也可以在 `tui.json` 中直接指定。 { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [自訂主題](https://opencode.ai/docs/zh-tw/themes/#%E8%87%AA%E8%A8%82%E4%B8%BB%E9%A1%8C) ------------------------------------------------------------------------------------ OpenCode 支援靈活的基於 JSON 的主題系統,讓使用者可以輕鬆建立和自訂主題。 * * * ### [層級優先順序](https://opencode.ai/docs/zh-tw/themes/#%E5%B1%A4%E7%B4%9A%E5%84%AA%E5%85%88%E9%A0%86%E5%BA%8F) 主題按以下順序從多個目錄載入,後面的目錄會覆蓋前面的目錄: 1. **內建主題** — 嵌入在二進位檔案中 2. **使用者設定目錄** — 定義在 `~/.config/opencode/themes/*.json` 或 `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **專案根目錄** — 定義在 `/.opencode/themes/*.json` 4. **當前工作目錄** — 定義在 `./.opencode/themes/*.json` 如果多個目錄包含同名主題,將使用優先順序較高的目錄中的主題。 * * * ### [建立主題](https://opencode.ai/docs/zh-tw/themes/#%E5%BB%BA%E7%AB%8B%E4%B8%BB%E9%A1%8C) 要建立自訂主題,請在上述任一主題目錄中建立一個 JSON 檔案。 建立使用者級主題: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json 建立專案級主題: mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON 格式](https://opencode.ai/docs/zh-tw/themes/#json-%E6%A0%BC%E5%BC%8F) 主題使用靈活的 JSON 格式,支援以下特性: * **十六進位顏色**:`"#ffffff"` * **ANSI 顏色**:`3`(0-255) * **顏色參考**:`"primary"` 或自訂定義的顏色名 * **深色/淺色變體**:`{"dark": "#000", "light": "#fff"}` * **無顏色**:`"none"` — 使用終端機的預設顏色或透明背景 * * * ### [顏色定義](https://opencode.ai/docs/zh-tw/themes/#%E9%A1%8F%E8%89%B2%E5%AE%9A%E7%BE%A9) `defs` 部分是選填的,它允許您定義可在主題中重複引用的可重複使用顏色。 * * * ### [終端機預設值](https://opencode.ai/docs/zh-tw/themes/#%E7%B5%82%E7%AB%AF%E6%A9%9F%E9%A0%90%E8%A8%AD%E5%80%BC) 特殊值 `"none"` 可用於任何顏色屬性,以繼承終端機的預設顏色。這在建立需要與終端機配色方案無縫融合的主題時特別有用: * `"text": "none"` — 使用終端機的預設前景色 * `"background": "none"` — 使用終端機的預設背景色 * * * ### [範例](https://opencode.ai/docs/zh-tw/themes/#%E7%AF%84%E4%BE%8B) 以下是一個自訂主題的完整範例: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Thèmes | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/themes/#_top) Thèmes ====== Sélectionnez un thème intégré ou définissez le vôtre. Avec OpenCode, vous pouvez choisir parmi plusieurs thèmes intégrés, utiliser un thème qui s’adapte au thème de votre terminal ou définir votre propre thème personnalisé. Par défaut, OpenCode utilise notre propre thème `opencode`. * * * [Exigences des terminaux](https://opencode.ai/docs/fr/themes/#exigences-des-terminaux) --------------------------------------------------------------------------------------- Pour que les thèmes s’affichent correctement avec leur palette de couleurs complète, votre terminal doit prendre en charge **truecolor** (couleur 24 bits). La plupart des terminaux modernes le prennent en charge par défaut, mais vous devrez peut-être l’activer : * **Vérifiez le support** : Exécutez `echo $COLORTERM` - il devrait afficher `truecolor` ou `24bit` * **Activer truecolor** : définissez la variable d’environnement `COLORTERM=truecolor` dans votre profil shell * **Compatibilité des terminaux** : assurez-vous que votre émulateur de terminal prend en charge les couleurs 24 bits (la plupart des terminaux modernes comme iTerm2, Alacritty, Kitty, Windows Terminal et les versions récentes de GNOME Terminal le font) Sans la prise en charge de TrueColor, les thèmes peuvent apparaître avec une précision des couleurs réduite ou revenir à l’approximation de 256 couleurs la plus proche. * * * [Thèmes intégrés](https://opencode.ai/docs/fr/themes/#th%C3%A8mes-int%C3%A9gr%C3%A9s) -------------------------------------------------------------------------------------- OpenCode est livré avec plusieurs thèmes intégrés. | Nom | Descriptif | | --- | --- | | `system` | S’adapte à la couleur de fond de votre terminal | | `tokyonight` | Basé sur le thème [Tokyonight](https://github.com/folke/tokyonight.nvim) | | `everforest` | Basé sur le thème [Everforest](https://github.com/sainnhe/everforest) | | `ayu` | Basé sur le thème sombre [Ayu](https://github.com/ayu-theme) | | `catppuccin` | Basé sur le thème [Catppuccin](https://github.com/catppuccin) | | `catppuccin-macchiato` | Basé sur le thème [Catppuccin](https://github.com/catppuccin) | | `gruvbox` | Basé sur le thème [Gruvbox](https://github.com/morhetz/gruvbox) | | `kanagawa` | Basé sur le thème [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | | `nord` | Basé sur le thème [Nord](https://github.com/nordtheme/nord) | | `matrix` | Vert style hacker sur thème noir | | `one-dark` | Basé sur le thème [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark | De plus, nous ajoutons constamment de nouveaux thèmes. * * * [Thème système](https://opencode.ai/docs/fr/themes/#th%C3%A8me-syst%C3%A8me) ----------------------------------------------------------------------------- Le thème `system` est conçu pour s’adapter automatiquement à la palette de couleurs de votre terminal. Contrairement aux thèmes traditionnels qui utilisent des couleurs fixes, le thème _system_ : * **Génère une échelle de gris** : crée une échelle de gris personnalisée basée sur la couleur d’arrière-plan de votre terminal, garantissant un contraste optimal. * **Utilise les couleurs ANSI** : exploite les couleurs ANSI standard (0-15) pour la coloration syntaxique et les éléments de l’interface utilisateur, qui respectent la palette de couleurs de votre terminal. * **Préserve les paramètres par défaut du terminal** : utilise `none` pour les couleurs du texte et de l’arrière-plan afin de conserver l’apparence native de votre terminal. Le thème système est destiné aux utilisateurs qui : * Vous souhaitez que OpenCode corresponde à l’apparence de leur terminal * Utiliser des schémas de couleurs de terminal personnalisés * Préférez une apparence cohérente sur toutes les applications de terminal * * * [Utiliser un thème](https://opencode.ai/docs/fr/themes/#utiliser-un-th%C3%A8me) -------------------------------------------------------------------------------- Vous pouvez sélectionner un thème en affichant la sélection de thème avec la commande `/theme`. Ou vous pouvez le spécifier dans `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Thèmes personnalisés](https://opencode.ai/docs/fr/themes/#th%C3%A8mes-personnalis%C3%A9s) ------------------------------------------------------------------------------------------- OpenCode prend en charge un système de thèmes flexible basé sur JSON qui permet aux utilisateurs de créer et de personnaliser facilement des thèmes. * * * ### [Hiérarchie](https://opencode.ai/docs/fr/themes/#hi%C3%A9rarchie) Les thèmes sont chargés à partir de plusieurs répertoires dans l’ordre suivant, les répertoires ultérieurs remplaçant les précédents : 1. **Thèmes intégrés** - Ceux-ci sont intégrés au binaire 2. **Répertoire de configuration utilisateur** - Défini dans `~/.config/opencode/themes/*.json` ou `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Répertoire racine du projet** - Défini dans `/.opencode/themes/*.json` 4. **Répertoire de travail actuel** - Défini dans `./.opencode/themes/*.json` Si plusieurs répertoires contiennent un thème portant le même nom, le thème du répertoire ayant la priorité la plus élevée sera utilisé. * * * ### [Création d’un thème](https://opencode.ai/docs/fr/themes/#cr%C3%A9ation-dun-th%C3%A8me) Pour créer un thème personnalisé, créez un fichier JSON dans l’un des répertoires de thème. Pour les thèmes à l’échelle de l’utilisateur : mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json Et pour des thèmes spécifiques au projet. mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [Format JSON](https://opencode.ai/docs/fr/themes/#format-json) Les thèmes utilisent un format JSON flexible avec prise en charge de : * **Couleurs hexadécimales** : `"#ffffff"` * **Couleurs ANSI** : `3` (0-255) * **Références de couleurs** : `"primary"` ou définitions personnalisées * **Variantes sombre/clair** : `{"dark": "#000", "light": "#fff"}` * **Aucune couleur** : `"none"` - Utilise la couleur par défaut du terminal ou le transparent * * * ### [Définitions des couleurs](https://opencode.ai/docs/fr/themes/#d%C3%A9finitions-des-couleurs) La section `defs` est facultative et elle permet de définir des couleurs réutilisables pouvant être référencées dans le thème. * * * ### [Paramètres par défaut du terminal](https://opencode.ai/docs/fr/themes/#param%C3%A8tres-par-d%C3%A9faut-du-terminal) La valeur spéciale `"none"` peut être utilisée pour n’importe quelle couleur afin d’hériter de la couleur par défaut du terminal. Ceci est particulièrement utile pour créer des thèmes qui se fondent parfaitement dans la palette de couleurs de votre terminal : * `"text": "none"` - Utilise la couleur de premier plan par défaut du terminal * `"background": "none"` - Utilise la couleur d’arrière-plan par défaut du terminal * * * ### [Exemple](https://opencode.ai/docs/fr/themes/#exemple) Voici un exemple de thème personnalisé : { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Temalar | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/themes/#_top) Temalar ======= Yerleşik bir tema seçin veya kendiniz oluşturun. opencode ile birden fazla yerleşik tema arasından seçim yapabilir, terminal temanıza uyum sağlayan bir tema kullanabilir veya kendi özel temanızı tanımlayabilirsiniz. Varsayılan olarak opencode kendi `opencode` temasını kullanır. * * * [Terminal gereksinimleri](https://opencode.ai/docs/tr/themes/#terminal-gereksinimleri) --------------------------------------------------------------------------------------- Temaların tüm renk paletiyle doğru görünmesi için terminalinizin **truecolor** (24-bit renk) desteklemesi gerekir. Çoğu modern terminal bunu varsayılan olarak destekler, ancak gerekirse etkinleştirmeniz gerekebilir: * **Desteği kontrol edin**: `echo $COLORTERM` çalıştırın - çıktı `truecolor` veya `24bit` olmalıdır * **Truecolor etkinleştirin**: kabuk profilinizde `COLORTERM=truecolor` ortam değişkenini ayarlayın * **Terminal uyumluluğu**: terminal emülatörünüzün 24-bit rengi desteklediğinden emin olun (iTerm2, Alacritty, Kitty, Windows Terminal ve GNOME Terminal’in yeni sürümleri gibi modern terminaller genelde destekler) Truecolor desteği yoksa temalar daha düşük renk doğruluğu ile görünebilir veya en yakın 256 renk yaklaşımına düşebilir. * * * [Yerleşik temalar](https://opencode.ai/docs/tr/themes/#yerle%C5%9Fik-temalar) ------------------------------------------------------------------------------ opencode birden fazla yerleşik temayla gelir. | Ad | Açıklama | | --- | --- | | `system` | Terminalinizin arka plan rengine uyum sağlar | | `tokyonight` | [tokyonight](https://github.com/folke/tokyonight.nvim)
temasını temel alır | | `everforest` | [Everforest](https://github.com/sainnhe/everforest)
temasını temel alır | | `ayu` | [Ayu](https://github.com/ayu-theme)
koyu temasını temel alır | | `catppuccin` | [Catppuccin](https://github.com/catppuccin)
temasını temel alır | | `catppuccin-macchiato` | [Catppuccin](https://github.com/catppuccin)
temasını temel alır | | `gruvbox` | [Gruvbox](https://github.com/morhetz/gruvbox)
temasını temel alır | | `kanagawa` | [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
temasını temel alır | | `nord` | [Nord](https://github.com/nordtheme/nord)
temasını temel alır | | `matrix` | Hacker tarzı yeşil üzerine siyah tema | | `one-dark` | [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark temasını temel alır | Ve daha fazlası; sürekli yeni temalar ekliyoruz. * * * [Sistem teması](https://opencode.ai/docs/tr/themes/#sistem-temas%C4%B1) ------------------------------------------------------------------------ `system` teması, terminalinizin renk düzenine otomatik uyum sağlamak için tasarlanmıştır. Sabit renk kullanan klasik temalardan farklı olarak _system_ teması: * **Gri ölçeği üretir**: En iyi kontrast için terminal arka planına göre özel gri tonları oluşturur * **ANSI renkleri kullanır**: 0-15 arası standart ANSI renklerini syntax highlighting ve UI öğelerinde kullanır, böylece terminal paletinize uyar * **Terminal varsayılanlarını korur**: Metin ve arka plan renklerinde `none` kullanarak terminalin yerel görünümünü korur Sistem teması şu kullanıcılar için idealdir: * opencode’un terminal görünümüyle birebir uyumlu olmasını isteyenler * Özel terminal renk şemaları kullananlar * Tüm terminal uygulamalarında tutarlı bir görünüm tercih edenler * * * [Tema kullanımı](https://opencode.ai/docs/tr/themes/#tema-kullan%C4%B1m%C4%B1) ------------------------------------------------------------------------------- `/theme` komutuyla tema seçicisini açıp tema seçebilirsiniz. İsterseniz `tui.json` içinde de belirtebilirsiniz. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Özel temalar](https://opencode.ai/docs/tr/themes/#%C3%B6zel-temalar) ---------------------------------------------------------------------- opencode, kullanıcıların kolayca tema oluşturup özelleştirebilmesi için esnek bir JSON tabanlı tema sistemi sunar. * * * ### [Hiyerarşi](https://opencode.ai/docs/tr/themes/#hiyerar%C5%9Fi) Temalar birden fazla dizinden şu sırayla yüklenir; daha sonra gelen dizin öncekini ezer: 1. **Yerleşik temalar** - Binary içine gömülüdür 2. **Kullanıcı yapılandırma dizini** - `~/.config/opencode/themes/*.json` veya `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Proje kök dizini** - `/.opencode/themes/*.json` 4. **Geçerli çalışma dizini** - `./.opencode/themes/*.json` Birden fazla dizinde aynı adlı tema varsa, önceliği daha yüksek dizindeki tema kullanılır. * * * ### [Tema oluşturma](https://opencode.ai/docs/tr/themes/#tema-olu%C5%9Fturma) Özel tema oluşturmak için tema dizinlerinden birinde bir JSON dosyası oluşturun. Kullanıcı geneli temalar için: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json Proje özel temalar için: mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON formatı](https://opencode.ai/docs/tr/themes/#json-format%C4%B1) Temalar aşağıdaki özellikleri destekleyen esnek bir JSON formatı kullanır: * **Hex renkler**: `"#ffffff"` * **ANSI renkler**: `3` (0-255) * **Renk referansları**: `"primary"` veya özel tanımlar * **Koyu/açık varyantlar**: `{"dark": "#000", "light": "#fff"}` * **Renk yok**: `"none"` - Terminal varsayılan rengi veya şeffaflık kullanılır * * * ### [Renk tanımları](https://opencode.ai/docs/tr/themes/#renk-tan%C4%B1mlar%C4%B1) `defs` bölümü isteğe bağlıdır ve tema içinde tekrar kullanılabilir renkler tanımlamanızı sağlar. * * * ### [Terminal varsayılanları](https://opencode.ai/docs/tr/themes/#terminal-varsay%C4%B1lanlar%C4%B1) Özel `"none"` değeri, terminalin varsayılan rengini miras almak için herhangi bir renkte kullanılabilir. Bu, terminalinizin renk şemasıyla doğal şekilde bütünleşen temalar oluştururken özellikle faydalıdır: * `"text": "none"` - Terminalin varsayılan ön plan rengini kullanır * `"background": "none"` - Terminalin varsayılan arka plan rengini kullanır * * * ### [Örnek](https://opencode.ai/docs/tr/themes/#%C3%B6rnek) Aşağıda özel bir tema örneği var: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Temas | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/themes/#_top) Temas ===== Selecione um tema embutido ou defina o seu próprio. Com o opencode, você pode selecionar um dos vários temas embutidos, usar um tema que se adapta ao tema do seu terminal ou definir seu próprio tema personalizado. Por padrão, o opencode usa nosso próprio tema `opencode`. * * * [Requisitos do terminal](https://opencode.ai/docs/pt-br/themes/#requisitos-do-terminal) ---------------------------------------------------------------------------------------- Para que os temas sejam exibidos corretamente com sua paleta de cores completa, seu terminal deve suportar **truecolor** (cor de 24 bits). A maioria dos terminais modernos suporta isso por padrão, mas você pode precisar habilitar: * **Verificar suporte**: Execute `echo $COLORTERM` - deve retornar `truecolor` ou `24bit` * **Habilitar truecolor**: Defina a variável de ambiente `COLORTERM=truecolor` no seu perfil de shell * **Compatibilidade do terminal**: Certifique-se de que seu emulador de terminal suporta cores de 24 bits (a maioria dos terminais modernos, como iTerm2, Alacritty, Kitty, Windows Terminal e versões recentes do GNOME Terminal, suportam) Sem suporte a truecolor, os temas podem aparecer com precisão de cor reduzida ou voltar para a aproximação de 256 cores mais próxima. * * * [Temas embutidos](https://opencode.ai/docs/pt-br/themes/#temas-embutidos) -------------------------------------------------------------------------- O opencode vem com vários temas embutidos. | Nome | Descrição | | --- | --- | | `system` | Adapta-se à cor de fundo do seu terminal | | `tokyonight` | Baseado no tema [Tokyonight](https://github.com/folke/tokyonight.nvim) | | `everforest` | Baseado no tema [Everforest](https://github.com/sainnhe/everforest) | | `ayu` | Baseado no tema escuro [Ayu](https://github.com/ayu-theme) | | `catppuccin` | Baseado no tema [Catppuccin](https://github.com/catppuccin) | | `catppuccin-macchiato` | Baseado no tema [Catppuccin](https://github.com/catppuccin) | | `gruvbox` | Baseado no tema [Gruvbox](https://github.com/morhetz/gruvbox) | | `kanagawa` | Baseado no tema [Kanagawa](https://github.com/rebelot/kanagawa.nvim) | | `nord` | Baseado no tema [Nord](https://github.com/nordtheme/nord) | | `matrix` | Tema verde estilo hacker sobre fundo preto | | `one-dark` | Baseado no tema escuro [Atom One](https://github.com/Th3Whit3Wolf/one-nvim) | E mais, estamos constantemente adicionando novos temas. * * * [Tema do sistema](https://opencode.ai/docs/pt-br/themes/#tema-do-sistema) -------------------------------------------------------------------------- O tema `system` é projetado para se adaptar automaticamente ao esquema de cores do seu terminal. Ao contrário dos temas tradicionais que usam cores fixas, o tema _system_: * **Gera escala de cinza**: Cria uma escala de cinza personalizada com base na cor de fundo do seu terminal, garantindo contraste ideal. * **Usa cores ANSI**: Aproveita as cores ANSI padrão (0-15) para destaque de sintaxe e elementos da interface, que respeitam a paleta de cores do seu terminal. * **Preserva padrões do terminal**: Usa `none` para cores de texto e fundo para manter a aparência nativa do seu terminal. O tema do sistema é para usuários que: * Querem que o opencode corresponda à aparência do seu terminal * Usam esquemas de cores de terminal personalizados * Preferem uma aparência consistente em todos os aplicativos de terminal * * * [Usando um tema](https://opencode.ai/docs/pt-br/themes/#usando-um-tema) ------------------------------------------------------------------------ Você pode selecionar um tema chamando a seleção de tema com o comando `/theme`. Ou você pode especificá-lo em `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Temas personalizados](https://opencode.ai/docs/pt-br/themes/#temas-personalizados) ------------------------------------------------------------------------------------ O opencode suporta um sistema de temas flexível baseado em JSON que permite aos usuários criar e personalizar temas facilmente. * * * ### [Hierarquia](https://opencode.ai/docs/pt-br/themes/#hierarquia) Os temas são carregados de vários diretórios na seguinte ordem, onde diretórios posteriores substituem os anteriores: 1. **Temas embutidos** - Estes estão incorporados no binário 2. **Diretório de configuração do usuário** - Definido em `~/.config/opencode/themes/*.json` ou `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Diretório raiz do projeto** - Definido em `/.opencode/themes/*.json` 4. **Diretório de trabalho atual** - Definido em `./.opencode/themes/*.json` Se vários diretórios contiverem um tema com o mesmo nome, o tema do diretório com maior prioridade será usado. * * * ### [Criando um tema](https://opencode.ai/docs/pt-br/themes/#criando-um-tema) Para criar um tema personalizado, crie um arquivo JSON em um dos diretórios de tema. Para temas de usuário: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json E para temas específicos do projeto. mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [Formato JSON](https://opencode.ai/docs/pt-br/themes/#formato-json) Os temas usam um formato JSON flexível com suporte para: * **Cores Hex**: `"#ffffff"` * **Cores ANSI**: `3` (0-255) * **Referências de cor**: `"primary"` ou definições personalizadas * **Variantes escuras/claras**: `{"dark": "#000", "light": "#fff"}` * **Sem cor**: `"none"` - Usa a cor padrão do terminal ou transparente * * * ### [Definições de cor](https://opencode.ai/docs/pt-br/themes/#defini%C3%A7%C3%B5es-de-cor) A seção `defs` é opcional e permite que você defina cores reutilizáveis que podem ser referenciadas no tema. * * * ### [Padrões do terminal](https://opencode.ai/docs/pt-br/themes/#padr%C3%B5es-do-terminal) O valor especial `"none"` pode ser usado para qualquer cor para herdar a cor padrão do terminal. Isso é particularmente útil para criar temas que se misturam perfeitamente com o esquema de cores do seu terminal: * `"text": "none"` - Usa a cor de primeiro plano padrão do terminal * `"background": "none"` - Usa a cor de fundo padrão do terminal * * * ### [Exemplo](https://opencode.ai/docs/pt-br/themes/#exemplo) Aqui está um exemplo de um tema personalizado: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Soporte ACP | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/acp/#_top) Soporte ACP =========== Utilice OpenCode en cualquier editor compatible con ACP. OpenCode admite el [Agent Client Protocol](https://agentclientprotocol.com/) o (ACP), lo que le permite usarlo directamente en editores e IDE compatibles. ACP es un protocolo abierto que estandariza la comunicación entre editores de código y agentes de codificación de IA. * * * [Configuración](https://opencode.ai/docs/es/acp/#configuraci%C3%B3n) --------------------------------------------------------------------- Para usar OpenCode a través de ACP, configure su editor para ejecutar el comando `opencode acp`. El comando inicia OpenCode como un subproceso compatible con ACP que se comunica con su editor a través de JSON-RPC a través de stdio. A continuación se muestran ejemplos de editores populares que admiten ACP. * * * ### [Zed](https://opencode.ai/docs/es/acp/#zed) Agregue a su configuración [Zed](https://zed.dev/) (`~/.config/zed/settings.json`): { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} Para abrirlo, use la acción `agent: new thread` en la **Paleta de comandos**. También puedes vincular un atajo de teclado editando tu `keymap.json`: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/es/acp/#jetbrains-ides) Agregue a su [JetBrains IDE](https://www.jetbrains.com/) acp.json de acuerdo con la [documentación](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} Para abrirlo, use el nuevo agente ‘OpenCode’ en el selector de agentes de AI Chat. * * * ### [Avante.nvim](https://opencode.ai/docs/es/acp/#avantenvim) Agregue a su configuración [Avante.nvim](https://github.com/yetone/avante.nvim) : { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} Si necesita pasar variables de entorno: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/es/acp/#codecompanionnvim) Para usar OpenCode como agente ACP en [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) , agregue lo siguiente a su configuración de Neovim: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) Esta configuración configura CodeCompanion para usar OpenCode como agente ACP para el chat. Si necesita pasar variables de entorno (como `OPENCODE_API_KEY`), consulte [Configuración de adaptadores: variables de entorno](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) en la documentación de CodeCompanion.nvim para obtener detalles completos. [Soporte](https://opencode.ai/docs/es/acp/#soporte) ---------------------------------------------------- OpenCode funciona igual a través de ACP que en la terminal. Todas las funciones son compatibles: * Herramientas integradas (operaciones de archivos, comandos de terminal, etc.) * Herramientas personalizadas y comandos de barra * Servidores MCP configurados en su configuración OpenCode * Reglas específicas del proyecto de `AGENTS.md` * Formateadores y linters personalizados * Sistema de agentes y permisos. --- # Serveurs MCP | OpenCode [Aller au contenu](https://opencode.ai/docs/fr/mcp-servers/#_top) Serveurs MCP ============ Ajoutez des outils MCP locaux et distants. Vous pouvez ajouter des outils externes à OpenCode à l’aide du _Model Context Protocol_ ou MCP. OpenCode prend en charge les serveurs locaux et distants. Une fois ajoutés, les outils MCP sont automatiquement disponibles pour le LLM aux côtés des outils intégrés. * * * #### [Mises en garde](https://opencode.ai/docs/fr/mcp-servers/#mises-en-garde) Lorsque vous utilisez un serveur MCP, cela ajoute au contexte. Cela peut vite s’additionner si vous disposez de beaucoup d’outils. Nous vous recommandons donc de faire attention aux serveurs MCP que vous utilisez. Certains serveurs MCP, comme le serveur GitHub MCP, ont tendance à ajouter beaucoup de jetons et peuvent facilement dépasser la limite de contexte. * * * [Activation](https://opencode.ai/docs/fr/mcp-servers/#activation) ------------------------------------------------------------------ Vous pouvez définir des serveurs MCP dans votre [OpenCode Config](https://opencode.ai/docs/config/) sous `mcp`. Ajoutez chaque MCP avec un nom unique. Vous pouvez faire référence à ce MCP par son nom lorsque vous demandez le LLM. { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} Vous pouvez également désactiver un serveur en définissant `enabled` sur `false`. Ceci est utile si vous souhaitez désactiver temporairement un serveur sans le supprimer de votre configuration. * * * ### [Remplacement des valeurs par défaut distantes](https://opencode.ai/docs/fr/mcp-servers/#remplacement-des-valeurs-par-d%C3%A9faut-distantes) Les organisations peuvent fournir des serveurs MCP par défaut via leur point de terminaison `.well-known/opencode`. Ces serveurs peuvent être désactivés par défaut, permettant aux utilisateurs de choisir ceux dont ils ont besoin. Pour activer un serveur spécifique à partir de la configuration distante de votre organisation, ajoutez-le à votre configuration locale avec `enabled: true` : { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} Vos valeurs de configuration locales remplacent les valeurs par défaut distantes. Voir [config precedence](https://opencode.ai/docs/config#precedence-order) pour plus de détails. * * * [Local](https://opencode.ai/docs/fr/mcp-servers/#local) -------------------------------------------------------- Ajoutez des serveurs MCP locaux en définissant `type` sur `"local"` dans l’objet MCP. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} La commande indique comment le serveur MCP local est démarré. Vous pouvez également transmettre une liste de variables d’environnement. Par exemple, voici comment ajouter le serveur de test [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP. { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} Et pour l’utiliser, je peux ajouter `use the mcp_everything tool` à mes prompts. use the mcp_everything tool to add the number 3 and 4 * * * #### [Options](https://opencode.ai/docs/fr/mcp-servers/#options) Voici toutes les options pour configurer un serveur MCP local. | Options | Type | Obligatoire | Description | | --- | --- | --- | --- | | `type` | Chaîne | Oui | Le type de connexion au serveur MCP doit être `"local"`. | | `command` | Tableau | Oui | Commande et arguments pour exécuter le serveur MCP. | | `environment` | Objet | | Variables d’environnement à définir lors de l’exécution du serveur. | | `enabled` | Booléen | | Activez ou désactivez le serveur MCP au démarrage. | | `timeout` | Numéro | | Délai d’expiration en ms pour la récupération des outils depuis le serveur MCP. La valeur par défaut est 5 000 (5 secondes). | * * * [Distant](https://opencode.ai/docs/fr/mcp-servers/#distant) ------------------------------------------------------------ Ajoutez des serveurs MCP distants en définissant `type` sur `"remote"`. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} Le champ `url` est l’URL du serveur MCP distant et l’option `headers` vous permet de transmettre des en-têtes. * * * #### [Options](https://opencode.ai/docs/fr/mcp-servers/#options-1) | Options | Type | Obligatoire | Description | | --- | --- | --- | --- | | `type` | Chaîne | Oui | Le type de connexion au serveur MCP doit être `"remote"`. | | `url` | Chaîne | Oui | URL du serveur MCP distant. | | `enabled` | Booléen | | Activez ou désactivez le serveur MCP au démarrage. | | `headers` | Objet | | En-têtes à envoyer avec la demande. | | `oauth` | Objet | | Configuration de l’authentification OAuth. Voir la section [OAuth](https://opencode.ai/docs/fr/mcp-servers/#oauth)
ci-dessous. | | `timeout` | Numéro | | Délai d’expiration en ms pour la récupération des outils depuis le serveur MCP. La valeur par défaut est 5 000 (5 secondes). | * * * [OAuth](https://opencode.ai/docs/fr/mcp-servers/#oauth) -------------------------------------------------------- OpenCode gère automatiquement l’authentification OAuth pour les serveurs MCP distants. Lorsqu’un serveur nécessite une authentification, OpenCode : 1. Détecte la réponse 401 et lance le flux OAuth 2. Utilise **Enregistrement client dynamique (RFC 7591)** s’il est pris en charge par le serveur. 3. Stocke les jetons en toute sécurité pour les demandes futures * * * ### [Automatique](https://opencode.ai/docs/fr/mcp-servers/#automatique) Pour la plupart des serveurs MCP compatibles OAuth, aucune configuration particulière n’est nécessaire. Configurez simplement le serveur distant : { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} Si le serveur nécessite une authentification, OpenCode vous demandera de vous authentifier lorsque vous essayez de l’utiliser pour la première fois. Sinon, vous pouvez [déclencher manuellement le flux](https://opencode.ai/docs/fr/mcp-servers/#authenticating) avec `opencode mcp auth `. * * * ### [Pré-enregistré](https://opencode.ai/docs/fr/mcp-servers/#pr%C3%A9-enregistr%C3%A9) Si vous disposez des informations d’identification client du fournisseur de serveur MCP, vous pouvez les configurer : { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [Authentification](https://opencode.ai/docs/fr/mcp-servers/#authentification) Vous pouvez déclencher manuellement l’authentification ou gérer les informations d’identification. Authentifiez-vous auprès d’un serveur MCP spécifique : opencode mcp auth my-oauth-server Répertoriez tous les serveurs MCP et leur statut d’authentification : opencode mcp list Supprimez les informations d’identification stockées : opencode mcp logout my-oauth-server La commande `mcp auth` ouvrira votre navigateur pour autorisation. Après votre autorisation, OpenCode stockera les jetons en toute sécurité dans `~/.local/share/opencode/mcp-auth.json`. * * * #### [Désactivation d’OAuth](https://opencode.ai/docs/fr/mcp-servers/#d%C3%A9sactivation-doauth) Si vous souhaitez désactiver le OAuth automatique pour un serveur (par exemple, pour les serveurs qui utilisent les clés API à la place), définissez `oauth` sur `false` : { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [Options OAuth](https://opencode.ai/docs/fr/mcp-servers/#options-oauth) | Options | Type | Description | | --- | --- | --- | | `oauth` | Objet \| faux | Objet de configuration OAuth, ou `false` pour désactiver la détection automatique OAuth. | | `clientId` | Chaîne | ID client OAuth. S’il n’est pas fourni, l’enregistrement dynamique du client sera tenté. | | `clientSecret` | Chaîne | OAuth secret client, si requis par le serveur d’autorisation. | | `scope` | Chaîne | OAuth scopes à demander lors de l’autorisation. | #### [Débogage](https://opencode.ai/docs/fr/mcp-servers/#d%C3%A9bogage) Si un serveur MCP distant ne parvient pas à s’authentifier, vous pouvez diagnostiquer les problèmes avec : # View auth status for all OAuth-capable serversopencode mcp auth list # Debug connection and OAuth flow for a specific serveropencode mcp debug my-oauth-server La commande `mcp debug` affiche l’état d’authentification actuel, teste la connectivité HTTP et tente le flux de découverte OAuth. * * * [Gestion](https://opencode.ai/docs/fr/mcp-servers/#gestion) ------------------------------------------------------------ Vos MCP sont disponibles sous forme d’outils dans OpenCode, aux côtés des outils intégrés. Vous pouvez donc les gérer via la configuration OpenCode comme n’importe quel autre outil. * * * ### [Global](https://opencode.ai/docs/fr/mcp-servers/#global) Cela signifie que vous pouvez les activer ou les désactiver globalement. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} Nous pouvons également utiliser un modèle global pour désactiver tous les MCP correspondants. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} Ici, nous utilisons le modèle global `my-mcp*` pour désactiver tous les MCP. * * * ### [Par agent](https://opencode.ai/docs/fr/mcp-servers/#par-agent) Si vous disposez d’un grand nombre de serveurs MCP, vous souhaiterez peut-être les activer uniquement par agent et les désactiver globalement. Pour ce faire : 1. Désactivez-le en tant qu’outil à l’échelle mondiale. 2. Dans votre [agent config](https://opencode.ai/docs/agents#tools) , activez le serveur MCP en tant qu’outil. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [Modèles globaux](https://opencode.ai/docs/fr/mcp-servers/#mod%C3%A8les-globaux) Le modèle glob utilise des modèles de globbing regex simples : * `*` correspond à zéro ou plusieurs caractères (par exemple, `"my-mcp*"` correspond à `my-mcp_search`, `my-mcp_list`, etc.) * `?` correspond exactement à un caractère * Tous les autres caractères correspondent littéralement * * * [Exemples](https://opencode.ai/docs/fr/mcp-servers/#exemples) -------------------------------------------------------------- Vous trouverez ci-dessous des exemples de serveurs MCP courants. Vous pouvez soumettre un PR si vous souhaitez documenter d’autres serveurs. * * * ### [Sentry](https://opencode.ai/docs/fr/mcp-servers/#sentry) Ajoutez le [serveur Sentry MCP](https://mcp.sentry.dev/) pour interagir avec vos projets et problèmes Sentry. { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} Après avoir ajouté la configuration, authentifiez-vous auprès de Sentry : opencode mcp auth sentry Cela ouvrira une fenêtre de navigateur pour terminer le flux OAuth et connecter OpenCode à votre compte Sentry. Une fois authentifié, vous pouvez utiliser les outils Sentry dans vos prompts pour interroger les problèmes, les projets et les données d’erreur. Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/fr/mcp-servers/#context7) Ajoutez le [Context7 MCP server](https://github.com/upstash/context7) pour effectuer une recherche dans les documents. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} Si vous avez créé un compte gratuit, vous pouvez utiliser votre clé API et obtenir des limites de débit plus élevées. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} Ici, nous supposons que la variable d’environnement `CONTEXT7_API_KEY` est définie. Ajoutez `use context7` à vos prompts pour utiliser le serveur Context7 MCP. Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 Alternativement, vous pouvez ajouter quelque chose comme ceci à votre [AGENTS.md](https://opencode.ai/docs/rules/) . When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/fr/mcp-servers/#grep-by-vercel) Ajoutez le serveur [Grep by Vercel](https://grep.app/) MCP pour rechercher des extraits de code sur GitHub. { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} Puisque nous avons nommé notre serveur MCP `gh_grep`, vous pouvez ajouter `use the gh_grep tool` à vos prompts pour que l’agent l’utilise. What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool Alternativement, vous pouvez ajouter quelque chose comme ceci à votre [AGENTS.md](https://opencode.ai/docs/rules/) . If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # MCP เซิร์ฟเวอร์ | OpenCode [Skip to content](https://opencode.ai/docs/th/mcp-servers/#_top) MCP เซิร์ฟเวอร์ =============== เพิ่มเครื่องมือ MCP ในพื้นที่และระยะไกล คุณสามารถเพิ่มเครื่องมือภายนอกให้กับ OpenCode ได้โดยใช้ _Model Context Protocol_ หรือ MCP OpenCode รองรับทั้งเซิร์ฟเวอร์ภายในและเซิร์ฟเวอร์ระยะไกล เมื่อเพิ่มแล้ว เครื่องมือ MCP จะพร้อมใช้งานโดยอัตโนมัติสำหรับ LLM ควบคู่ไปกับเครื่องมือในตัว * * * #### [คำเตือน](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%84%E0%B8%B3%E0%B9%80%E0%B8%95%E0%B8%B7%E0%B8%AD%E0%B8%99) เมื่อคุณใช้เซิร์ฟเวอร์ MCP เซิร์ฟเวอร์ดังกล่าวจะเพิ่มบริบท สิ่งนี้สามารถเพิ่มขึ้นได้อย่างรวดเร็วหากคุณมีเครื่องมือมากมาย ดังนั้นเราขอแนะนำให้ระมัดระวังเซิร์ฟเวอร์ MCP ที่คุณใช้ เซิร์ฟเวอร์ MCP บางตัว เช่น เซิร์ฟเวอร์ GitHub MCP มีแนวโน้มที่จะเพิ่มโทเค็นจำนวนมากและอาจเกินขีดจำกัดบริบทได้อย่างง่ายดาย * * * [เปิดใช้งาน](https://opencode.ai/docs/th/mcp-servers/#%E0%B9%80%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99) -------------------------------------------------------------------------------------------------------------------------------------------------- คุณสามารถกำหนดเซิร์ฟเวอร์ MCP ได้ใน [OpenCode Config](https://opencode.ai/docs/config/) ภายใต้ `mcp` เพิ่ม MCP แต่ละรายการด้วยชื่อที่ไม่ซ้ำใคร คุณสามารถอ้างอิงถึง MCP ด้วยชื่อได้เมื่อแจ้ง LLM { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} คุณยังสามารถปิดการใช้งานเซิร์ฟเวอร์ได้โดยการตั้งค่า `enabled` เป็น `false` สิ่งนี้มีประโยชน์หากคุณต้องการปิดการใช้งานเซิร์ฟเวอร์ชั่วคราวโดยไม่ต้องลบออกจากการกำหนดค่าของคุณ * * * ### [การเอาชนะค่าเริ่มต้นระยะไกล](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%AD%E0%B8%B2%E0%B8%8A%E0%B8%99%E0%B8%B0%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%E0%B8%A3%E0%B8%B0%E0%B8%A2%E0%B8%B0%E0%B9%84%E0%B8%81%E0%B8%A5) องค์กรสามารถจัดเตรียมเซิร์ฟเวอร์ MCP เริ่มต้นผ่านทางจุดสิ้นสุด `.well-known/opencode` เซิร์ฟเวอร์เหล่านี้อาจถูกปิดใช้งานตามค่าเริ่มต้น ทำให้ผู้ใช้สามารถเลือกใช้เซิร์ฟเวอร์ที่ต้องการได้ หากต้องการเปิดใช้งานเซิร์ฟเวอร์เฉพาะจากการกำหนดค่าระยะไกลขององค์กรของคุณ ให้เพิ่มเซิร์ฟเวอร์ดังกล่าวลงในการกำหนดค่าภายในเครื่องของคุณด้วย `enabled: true`: { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} ค่าการกำหนดค่าในเครื่องของคุณจะแทนที่ค่าเริ่มต้นระยะไกล ดู [config ลำดับความสำคัญ](https://opencode.ai/docs/config#precedence-order) สำหรับรายละเอียดเพิ่มเติม * * * [ท้องถิ่น](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%97%E0%B9%89%E0%B8%AD%E0%B8%87%E0%B8%96%E0%B8%B4%E0%B9%88%E0%B8%99) ------------------------------------------------------------------------------------------------------------------------------ เพิ่มเซิร์ฟเวอร์ท้องถิ่น MCP โดยใช้ `type` ไปยัง `"local"` ภายในวัตถุ MCP { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} คำสั่งคือวิธีที่เซิร์ฟเวอร์ MCP ท้องถิ่นเริ่มทำงาน คุณยังสามารถส่งผ่านรายการตัวแปรสภาพแวดล้อมได้เช่นกัน ตัวอย่างเช่น นี่คือวิธีที่คุณสามารถเพิ่มการทดสอบเซิร์ฟเวอร์ [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP เซิร์ฟเวอร์ { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} และหากต้องการใช้งาน ฉันสามารถเพิ่ม `use the mcp_everything tool` ในข้อความแจ้งของฉันได้ use the mcp_everything tool to add the number 3 and 4 * * * #### [ตัวเลือก](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81) นี่คือตัวเลือกทั้งหมดสำหรับการกำหนดค่าเซิร์ฟเวอร์ MCP ภายในเครื่อง | ตัวเลือก | พิมพ์ | ที่จำเป็น | คำอธิบาย | | --- | --- | --- | --- | | `type` | สตริง | ย | ประเภทของการเชื่อมต่อเซิร์ฟเวอร์ MCP ต้องเป็น `"local"` | | `command` | อาร์เรย์ | ย | คำสั่งและอาร์กิวเมนต์เพื่อรันเซิร์ฟเวอร์ MCP | | `environment` | วัตถุ | | ตัวแปรสภาพแวดล้อมที่จะตั้งค่าเมื่อรันเซิร์ฟเวอร์ | | `enabled` | บูลีน | | เปิดหรือปิดใช้งานเซิร์ฟเวอร์ MCP เมื่อเริ่มต้นระบบ | | `timeout` | ตัวเลข | | หมดเวลาเป็น ms สำหรับการดึงเครื่องมือจากเซิร์ฟเวอร์ MCP ค่าเริ่มต้นคือ 5,000 (5 วินาที) | * * * [ระยะไกล](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%A3%E0%B8%B0%E0%B8%A2%E0%B8%B0%E0%B9%84%E0%B8%81%E0%B8%A5) -------------------------------------------------------------------------------------------------------------------- เพิ่มเซิร์ฟเวอร์ระยะไกล MCP โดยตั้งค่า `type` เป็น `"remote"` { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} `url` คือ URL ของเซิร์ฟเวอร์ MCP ระยะไกล และด้วยตัวเลือก `headers` คุณสามารถส่งผ่านรายการส่วนหัวได้ * * * #### [ตัวเลือก](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81-1) | ตัวเลือก | พิมพ์ | ที่จำเป็น | คำอธิบาย | | --- | --- | --- | --- | | `type` | สตริง | ย | ประเภทของการเชื่อมต่อเซิร์ฟเวอร์ MCP ต้องเป็น `"remote"` | | `url` | สตริง | ย | URL ของเซิร์ฟเวอร์ MCP ระยะไกล | | `enabled` | บูลีน | | เปิดหรือปิดใช้งานเซิร์ฟเวอร์ MCP เมื่อเริ่มต้นระบบ | | `headers` | วัตถุ | | ส่วนหัวที่จะส่งพร้อมกับคำขอ | | `oauth` | วัตถุ | | การกำหนดค่าการตรวจสอบสิทธิ์ OAuth ดูส่วน [OAuth](https://opencode.ai/docs/th/mcp-servers/#oauth)
ด้านล่าง | | `timeout` | ตัวเลข | | หมดเวลาเป็น ms สำหรับการดึงเครื่องมือจากเซิร์ฟเวอร์ MCP ค่าเริ่มต้นคือ 5,000 (5 วินาที) | * * * [OAuth](https://opencode.ai/docs/th/mcp-servers/#oauth) -------------------------------------------------------- OpenCode จะจัดการการตรวจสอบสิทธิ์ OAuth สำหรับเซิร์ฟเวอร์ MCP ระยะไกลโดยอัตโนมัติ เมื่อเซิร์ฟเวอร์ต้องการการรับรองความถูกต้อง OpenCode จะ: 1. ตรวจหาการตอบสนอง 401 และเริ่มโฟลว์ OAuth 2. ใช้ **การลงทะเบียนไคลเอ็นต์แบบไดนามิก (RFC 7591)** หากเซิร์ฟเวอร์รองรับ 3. จัดเก็บโทเค็นอย่างปลอดภัยสำหรับคำขอในอนาคต * * * ### [อัตโนมัติ](https://opencode.ai/docs/th/mcp-servers/#%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) สำหรับเซิร์ฟเวอร์ MCP ที่เปิดใช้งาน OAuth ส่วนใหญ่ ไม่จำเป็นต้องมีการกำหนดค่าพิเศษ เพียงกำหนดค่าเซิร์ฟเวอร์ระยะไกล: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} หากเซิร์ฟเวอร์ต้องมีการตรวจสอบสิทธิ์ OpenCode จะแจ้งให้คุณตรวจสอบความถูกต้องเมื่อคุณพยายามใช้งานครั้งแรก หากไม่เป็นเช่นนั้น คุณสามารถ[ทริกเกอร์โฟลว์ด้วยตนเอง](https://opencode.ai/docs/th/mcp-servers/#%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%AA%E0%B8%B4%E0%B8%97%E0%B8%98%E0%B8%B4%E0%B9%8C) ด้วย `opencode mcp auth ` * * * ### [ลงทะเบียนล่วงหน้า](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%A5%E0%B8%87%E0%B8%97%E0%B8%B0%E0%B9%80%E0%B8%9A%E0%B8%B5%E0%B8%A2%E0%B8%99%E0%B8%A5%E0%B9%88%E0%B8%A7%E0%B8%87%E0%B8%AB%E0%B8%99%E0%B9%89%E0%B8%B2) หากคุณมีข้อมูลประจำตัวไคลเอ็นต์จากผู้ให้บริการเซิร์ฟเวอร์ MCP คุณสามารถกำหนดค่าได้: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [กำลังตรวจสอบสิทธิ์](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%81%E0%B8%B3%E0%B8%A5%E0%B8%B1%E0%B8%87%E0%B8%95%E0%B8%A3%E0%B8%A7%E0%B8%88%E0%B8%AA%E0%B8%AD%E0%B8%9A%E0%B8%AA%E0%B8%B4%E0%B8%97%E0%B8%98%E0%B8%B4%E0%B9%8C) คุณสามารถทริกเกอร์การตรวจสอบสิทธิ์หรือจัดการข้อมูลประจำตัวได้ด้วยตนเอง ตรวจสอบสิทธิ์กับเซิร์ฟเวอร์ MCP เฉพาะ: opencode mcp auth my-oauth-server แสดงรายการเซิร์ฟเวอร์ MCP ทั้งหมดและสถานะการตรวจสอบสิทธิ์: opencode mcp list ลบข้อมูลรับรองที่เก็บไว้: opencode mcp logout my-oauth-server คำสั่ง `mcp auth` จะเปิดเบราว์เซอร์ของคุณเพื่อขออนุญาต หลังจากที่คุณอนุญาตแล้ว OpenCode จะจัดเก็บโทเค็นอย่างปลอดภัยใน `~/.local/share/opencode/mcp-auth.json` * * * #### [ปิดการใช้งาน OAuth](https://opencode.ai/docs/th/mcp-servers/#%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-oauth) หากคุณต้องการปิดการใช้งาน OAuth อัตโนมัติสำหรับเซิร์ฟเวอร์ (เช่น สำหรับเซิร์ฟเวอร์ที่ใช้คีย์ API แทน) ให้ตั้งค่า `oauth` เป็น `false`: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [ตัวเลือก OAuth](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81-oauth) | ตัวเลือก | พิมพ์ | คำอธิบาย | | --- | --- | --- | | `oauth` | วัตถุ \| เท็จ | ออบเจ็กต์การกำหนดค่า OAuth หรือ `false` เพื่อปิดใช้การตรวจจับอัตโนมัติของ OAuth | | `clientId` | สตริง | รหัสไคลเอ็นต์ OAuth หากไม่ได้ระบุไว้ จะพยายามลงทะเบียนไคลเอ็นต์แบบไดนามิก | | `clientSecret` | สตริง | ข้อมูลลับไคลเอ็นต์ OAuth หากเซิร์ฟเวอร์การให้สิทธิ์กำหนดไว้ | | `scope` | สตริง | ขอบเขต OAuth ที่จะขอระหว่างการให้สิทธิ์ | #### [การดีบัก](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%94%E0%B8%B5%E0%B8%9A%E0%B8%B1%E0%B8%81) หากเซิร์ฟเวอร์ MCP ระยะไกลไม่สามารถตรวจสอบสิทธิ์ได้ คุณสามารถวินิจฉัยปัญหาด้วย: # View auth status for all OAuth-capable serversopencode mcp auth list # Debug connection and OAuth flow for a specific serveropencode mcp debug my-oauth-server คำสั่ง `mcp debug` แสดงสถานะการตรวจสอบสิทธิ์ปัจจุบัน ทดสอบการเชื่อมต่อ HTTP และพยายามใช้ขั้นตอนการค้นหา OAuth * * * [จัดการ](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%88%E0%B8%B1%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3) ---------------------------------------------------------------------------------------------------------- MCP ของคุณพร้อมใช้งานในฐานะเครื่องมือใน OpenCode ควบคู่ไปกับเครื่องมือในตัว คุณจึงสามารถจัดการผ่านการกำหนดค่า OpenCode ได้เหมือนกับเครื่องมืออื่นๆ * * * ### [ทั่วโลก](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%97%E0%B8%B1%E0%B9%88%E0%B8%A7%E0%B9%82%E0%B8%A5%E0%B8%81) ซึ่งหมายความว่าคุณสามารถเปิดหรือปิดใช้งานได้ทั่วโลก { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} นอกจากนี้เรายังสามารถใช้รูปแบบ glob เพื่อปิดใช้งาน MCP ที่ตรงกันทั้งหมดได้ { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} ที่นี่เราใช้รูปแบบ glob `my-mcp*` เพื่อปิดการใช้งาน MCP ทั้งหมด * * * ### [ต่อตัวแทน](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%81%E0%B8%97%E0%B8%99) หากคุณมีเซิร์ฟเวอร์ MCP จำนวนมาก คุณอาจต้องการเปิดใช้งานเซิร์ฟเวอร์เหล่านี้ต่อตัวแทนเท่านั้น และปิดใช้งานเซิร์ฟเวอร์เหล่านั้นทั่วโลก เมื่อต้องการทำสิ่งนี้: 1. ปิดการใช้งานเป็นเครื่องมือทั่วโลก 2. ใน [agent config](https://opencode.ai/docs/agents#tools) ให้เปิดใช้งานเซิร์ฟเวอร์ MCP เป็นเครื่องมือ { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [รูปแบบ Glob](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B9%81%E0%B8%9A%E0%B8%9A-glob) รูปแบบ glob ใช้รูปแบบ globbing regex แบบง่าย: * `*` ตรงกับอักขระใดๆ ตั้งแต่ศูนย์ขึ้นไป (เช่น `"my-mcp*"` ตรงกับ `my-mcp_search`, `my-mcp_list` ฯลฯ) * `?` ตรงกับอักขระหนึ่งตัวเท่านั้น * อักขระอื่นๆ ทั้งหมดตรงกันอย่างแท้จริง * * * [ตัวอย่าง](https://opencode.ai/docs/th/mcp-servers/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87) ------------------------------------------------------------------------------------------------------------------------------ ด้านล่างนี้เป็นตัวอย่างของเซิร์ฟเวอร์ MCP ทั่วไปบางส่วน คุณสามารถส่ง PR ได้ถ้าคุณต้องการจัดทำเอกสารเซิร์ฟเวอร์อื่น * * * ### [Sentry](https://opencode.ai/docs/th/mcp-servers/#sentry) เพิ่ม [เซิร์ฟเวอร์ Sentry MCP](https://mcp.sentry.dev/) เพื่อโต้ตอบกับโครงการและปัญหา Sentry ของคุณ { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} หลังจากเพิ่มการกำหนดค่าแล้ว ให้ตรวจสอบสิทธิ์กับ Sentry: opencode mcp auth sentry ซึ่งจะเป็นการเปิดหน้าต่างเบราว์เซอร์เพื่อดำเนินการโฟลว์ OAuth ให้เสร็จสมบูรณ์ และเชื่อมต่อ OpenCode กับบัญชี Sentry ของคุณ เมื่อตรวจสอบสิทธิ์แล้ว คุณจะใช้เครื่องมือ Sentry ในข้อความแจ้งเพื่อค้นหาปัญหา โปรเจ็กต์ และข้อมูลข้อผิดพลาดได้ Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/th/mcp-servers/#context7) เพิ่ม [Context7 MCP server](https://github.com/upstash/context7) เพื่อค้นหาในเอกสาร { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} หากคุณได้ลงทะเบียนสำหรับบัญชีฟรี คุณสามารถใช้รหัส API ของคุณและรับขีดจำกัดอัตราที่สูงขึ้น { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} ที่นี่เราสมมติว่าคุณมีชุดตัวแปรสภาพแวดล้อม `CONTEXT7_API_KEY` เพิ่ม `use context7` ในข้อความแจ้งของคุณเพื่อใช้เซิร์ฟเวอร์ Context7 MCP Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 หรือคุณสามารถเพิ่มสิ่งนี้ลงใน [AGENTS.md](https://opencode.ai/docs/rules/) ของคุณได้ When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/th/mcp-servers/#grep-by-vercel) เพิ่มเซิร์ฟเวอร์ [Grep by Vercel](https://grep.app/) MCP เพื่อค้นหาผ่านข้อมูลโค้ดบน GitHub { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} เนื่องจากเราตั้งชื่อเซิร์ฟเวอร์ MCP `gh_grep` คุณสามารถเพิ่ม `use the gh_grep tool` ในข้อความแจ้งของคุณเพื่อให้ตัวแทนใช้งานได้ What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool หรือคุณสามารถเพิ่มสิ่งนี้ลงใน [AGENTS.md](https://opencode.ai/docs/rules/) ของคุณได้ If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # Regler | OpenCode [Gå til indhold](https://opencode.ai/docs/da/rules/#_top) Regler ====== Angiv tilpassede instruktioner til opencode. Du kan gi tilpassede instruksjoner for at OpenCode ved at oprete en `AGENTS.md`\-fil. Dette ligner på Cursors regler. Den inneholder instruksjoner som vil bli inkludert i LLMs kontekst for at tilpasse oppførselen til ditt spesifikke prosjekt. * * * [Initialisering](https://opencode.ai/docs/da/rules/#initialisering) -------------------------------------------------------------------- For at lage en ny `AGENTS.md` fil, kan du kjøre kommandoen `/init` i opencode. Dette vil skanne prosjektet og alt dets innhold for at forstå hva prosjektet handler om og generere en `AGENTS.md`\-fil med det. Dette hjelper opencode at navigere i prosjektet bedre. Hvis du har en eksisterende `AGENTS.md`\-fil, vil denne prøve at tilføje til den. * * * [Eksempel](https://opencode.ai/docs/da/rules/#eksempel) -------------------------------------------------------- Du kan også bare lage denne filen manuelt. Her er et eksempel på nogle ting du kan tilføje inn i en `AGENTS.md`\-fil. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` Vi tilføjer til prosjektspesifikke instruksjoner her, og dette vil bli delt på tvers av teamet ditt. * * * [Typer](https://opencode.ai/docs/da/rules/#typer) -------------------------------------------------- opencode støtter også lesing av `AGENTS.md`\-filen fra flere steder. Og dette tjener forskjellige formål. ### [Projekt](https://opencode.ai/docs/da/rules/#projekt) Plasser en `AGENTS.md` i prosjektroten for prosjektspesifikke regler. Disse gjelder kun når du arbeider i denne katalogen eller dens underkataloger. ### [Globalt](https://opencode.ai/docs/da/rules/#globalt) Du kan også ha globale regler i en `~/.config/opencode/AGENTS.md`\-fil. Dette blir brugt på alle opencode-sessioner. Siden dette ikke er forpliktet til Git eller delt med teamet ditt, anbefaler vi at bruge dette til at spesifisere eventuelle personlige regler som LLM bør følge. ### [Claude Code-kompatibilitet](https://opencode.ai/docs/da/rules/#claude-code-kompatibilitet) For brugere som migrerer fra Claude Code, støtter OpenCode Claude Codes filkonvensjoner som fallbacks: * **Prosjektregler**: `CLAUDE.md` i prosjektkatalogen din (bruges hvis ingen `AGENTS.md` eksisterer) * **Globale regler**: `~/.claude/CLAUDE.md` (bruges hvis ingen `~/.config/opencode/AGENTS.md` eksisterer) * **Skills**: `~/.claude/skills/` — se [Agent Skills](https://opencode.ai/docs/skills/) for detaljer For at deaktivere Claude Code-kompatibilitet, sett en av disse miljøvariablene: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [Prioritet](https://opencode.ai/docs/da/rules/#prioritet) ---------------------------------------------------------- Når opencode starter, ser den etter regelfiler i denne rekkefølgen: 1. **Lokale filer** ved at gå opp fra nuværende katalog (`AGENTS.md`, `CLAUDE.md`) 2. **Global fil** på `~/.config/opencode/AGENTS.md` 3. **Claude Code-fil** på `~/.claude/CLAUDE.md` (med mindre de er deaktivert) Den første matchende filen vinner i hver kategori. For eksempel, hvis du har både `AGENTS.md` og `CLAUDE.md`, bruges bare `AGENTS.md`. På samme måte har `~/.config/opencode/AGENTS.md` forrang over `~/.claude/CLAUDE.md`. * * * [Brugerdefinerede instruktioner](https://opencode.ai/docs/da/rules/#brugerdefinerede-instruktioner) ---------------------------------------------------------------------------------------------------- Du kan spesifisere egendefinerte instruksjonsfiler i din `opencode.json` eller den globale `~/.config/opencode/opencode.json`. Dette lar deg og teamet ditt gjenbruge eksisterende regler i stedet for at måtte duplisere dem til AGENTS.md. Eksempel: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Du kan også bruge eksterne URL-er for at laste instruksjoner fra nettet. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} Fjerninstruksjoner hentes med 5 sekunders tidsavbrudd. Alle instruksjonsfilene er kombinert med `AGENTS.md`\-filene dine. * * * [Reference til eksterne filer](https://opencode.ai/docs/da/rules/#reference-til-eksterne-filer) ------------------------------------------------------------------------------------------------ Selv om opencode ikke automatisk analyserer filreferanser i `AGENTS.md`, kan du oppnå lignende funksjonalitet på to måter: ### [Brug af opencode.json](https://opencode.ai/docs/da/rules/#brug-af-opencodejson) Den anbefalte tilnærmingen er at bruge feltet `instructions` i `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [Manuelle instruktioner i AGENTS.md](https://opencode.ai/docs/da/rules/#manuelle-instruktioner-i-agentsmd) Du kan lære opencode at lese eksterne filer ved at gi eksplisitte instruksjoner i `AGENTS.md`. Her er et praktisk eksempel: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. Denne tilnærmingen lar deg: * Lag modulære, gjenbrugbare regelfiler * Del regler på tvers av prosjekter via symbolkoblinger eller git-undermoduler * Hold AGENTS.md kortfattet mens du refererer til detaljerte retningslinjer * Sørg for at opencode laster filer kun når det er nødvendig for den spesifikke oppgaven --- # Regeln | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/rules/#_top) Regeln ====== Lege eigene Anweisungen fuer opencode fest. Du kannst opencode ueber eine `AGENTS.md`\-Datei mit eigenen Anweisungen steuern. Das ist aehnlich zu den Regeln in Cursor und wird direkt in den LLM-Kontext geladen. * * * [Initialisierung](https://opencode.ai/docs/de/rules/#initialisierung) ---------------------------------------------------------------------- Um eine neue `AGENTS.md` zu erstellen, fuehre in opencode den Befehl `/init` aus. Der Befehl scannt dein Projekt und erzeugt daraus eine passende `AGENTS.md`. So kann opencode sich in deinem Code besser orientieren. Wenn bereits eine `AGENTS.md` existiert, versucht opencode sie zu erweitern. * * * [Beispiel](https://opencode.ai/docs/de/rules/#beispiel) -------------------------------------------------------- Du kannst die Datei auch manuell anlegen. Hier ist ein Beispiel, was in einer `AGENTS.md` stehen kann. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` Hier hinterlegst du projektspezifische Regeln, die dein Team gemeinsam nutzt. * * * [Typen](https://opencode.ai/docs/de/rules/#typen) -------------------------------------------------- opencode kann `AGENTS.md` aus mehreren Orten lesen. Die Orte haben unterschiedliche Zwecke. ### [Projekt](https://opencode.ai/docs/de/rules/#projekt) Lege eine `AGENTS.md` im Projekt-Root ab, um projektspezifische Regeln zu definieren. Diese gelten nur in diesem Verzeichnis und seinen Unterordnern. ### [Global](https://opencode.ai/docs/de/rules/#global) Du kannst auch globale Regeln in `~/.config/opencode/AGENTS.md` speichern. Diese gelten in allen opencode-Sitzungen. Da diese Datei nicht in Git landet und nicht mit dem Team geteilt wird, eignet sie sich fuer persoenliche Regeln. ### [Claude Code-Kompatibilität](https://opencode.ai/docs/de/rules/#claude-code-kompatibilit%C3%A4t) Wenn du von Claude Code kommst, unterstuetzt OpenCode dessen Dateikonventionen als Fallback: * **Projektregeln**: `CLAUDE.md` im Projekt (wenn keine `AGENTS.md` existiert) * **Globale Regeln**: `~/.claude/CLAUDE.md` (wenn keine `~/.config/opencode/AGENTS.md` existiert) * **Skills**: `~/.claude/skills/` - siehe [Agent Skills](https://opencode.ai/docs/skills/) fuer Details Um die Claude-Code-Kompatibilitaet zu deaktivieren, setze eine dieser Umgebungsvariablen: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [Rangfolge](https://opencode.ai/docs/de/rules/#rangfolge) ---------------------------------------------------------- Beim Start sucht opencode in dieser Reihenfolge nach Regeldateien: 1. **Lokale Dateien** beim Hochlaufen ab dem aktuellen Verzeichnis (`AGENTS.md`, `CLAUDE.md`) 2. **Globale Datei** unter `~/.config/opencode/AGENTS.md` 3. **Claude-Code-Datei** unter `~/.claude/CLAUDE.md` (falls nicht deaktiviert) Pro Kategorie gewinnt die zuerst passende Datei. Wenn sowohl `AGENTS.md` als auch `CLAUDE.md` existieren, wird nur `AGENTS.md` verwendet. * * * [Eigene Anweisungen](https://opencode.ai/docs/de/rules/#eigene-anweisungen) ---------------------------------------------------------------------------- Du kannst zusaetzliche Anweisungsdateien in deiner `opencode.json` oder in `~/.config/opencode/opencode.json` angeben. So kann dein Team bestehende Regeln wiederverwenden, statt Inhalte in `AGENTS.md` zu duplizieren. Beispiel: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Du kannst auch Remote-URLs nutzen, um Regeln aus dem Web zu laden. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} Remote-Anweisungen werden mit 5 Sekunden Timeout geladen. Alle Anweisungsdateien werden mit deinen `AGENTS.md`\-Dateien kombiniert. * * * [Externe Dateien referenzieren](https://opencode.ai/docs/de/rules/#externe-dateien-referenzieren) -------------------------------------------------------------------------------------------------- opencode parst Datei-Referenzen in `AGENTS.md` nicht automatisch. Du erreichst aehnliches Verhalten auf zwei Wegen. ### [Mit opencode.json](https://opencode.ai/docs/de/rules/#mit-opencodejson) Empfohlen ist das `instructions`\-Feld in der `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [Manuelle Anweisungen in AGENTS.md](https://opencode.ai/docs/de/rules/#manuelle-anweisungen-in-agentsmd) Du kannst opencode explizit anweisen, externe Dateien zu lesen. Hier ein praxisnahes Beispiel: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. Damit kannst du: * Modulare, wiederverwendbare Regeldateien erstellen * Regeln projektuebergreifend per Symlink oder Git-Submodule teilen * `AGENTS.md` kurz halten und auf Detailregeln verweisen * Sicherstellen, dass Dateien nur bei Bedarf geladen werden --- # Zasady | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/rules/#_top) Zasady ====== Ustaw niestandardowe instrukcje dla opencode. Możesz dostarczyć niestandardowe instrukcje do opencode, tworząc plik `AGENTS.md`. Jest to podobne do zasad Cursora. Zawiera instrukcje, które zostaną uwzględnione w kontekście LLM, aby dostosować jego zachowanie do konkretnego projektu. * * * [Inicjalizacja](https://opencode.ai/docs/pl/rules/#inicjalizacja) ------------------------------------------------------------------ Aby utworzyć nowy plik `AGENTS.md`, możesz uruchomić komendę `/init` w otwartym kodzie. Spowoduje to przeskanowanie projektu i całej jego zawartości, aby zrozumieć, czego dotyczy projekt i wygenerować z nim plik `AGENTS.md`. Pomaga to otwartemu kodowi lepiej poruszać się po projekcie. Jeśli masz istniejący plik `AGENTS.md`, spróbujemy go dodać. * * * [Przykład](https://opencode.ai/docs/pl/rules/#przyk%C5%82ad) ------------------------------------------------------------- Możesz także po prostu utworzyć ten plik ręcznie. Oto przykład niektórych rzeczy, które można umieścić w pliku `AGENTS.md`. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` Dodajemy tutaj instrukcje dotyczące konkretnego projektu, które zostaną udostępnione całemu zespołowi. * * * [Typy](https://opencode.ai/docs/pl/rules/#typy) ------------------------------------------------ opencode obsługuje także odczytywanie pliku `AGENTS.md` z wielu lokalizacji. A to służy różnym celom. ### [Projekt](https://opencode.ai/docs/pl/rules/#projekt) Umieść `AGENTS.md` w katalogu głównym projektu, aby uzyskać reguły specyficzne dla projektu. Mają one zastosowanie tylko wtedy, gdy pracujesz w tym katalogu lub jego podkatalogach. ### [Globalne](https://opencode.ai/docs/pl/rules/#globalne) Możesz także mieć reguły globalne w pliku `~/.config/opencode/AGENTS.md`. Jest to stosowane we wszystkich sesjach opencode. Ponieważ nie jest to wymagane dla Git ani udostępniane Twojemu zespołowi, zalecamy użycie tego do określenia wszelkich osobistych zasad, których powinien przestrzegać LLM. ### [Kompatybilność z Claude Code](https://opencode.ai/docs/pl/rules/#kompatybilno%C5%9B%C4%87-z-claude-code) W przypadku użytkowników migrujących z Claude Code opencode obsługuje konwencje plików Claude Code jako rozwiązania awaryjne: * **Zasady projektu**: `CLAUDE.md` w katalogu projektu (używane, jeśli nie istnieje `AGENTS.md`) * **Zasady globalne**: `~/.claude/CLAUDE.md` (używane, jeśli nie istnieje `~/.config/opencode/AGENTS.md`) * **Umiejętności**: `~/.claude/skills/` — szczegóły znajdziesz w [Umiejętnościach agenta](https://opencode.ai/docs/skills/) Aby wyłączyć kompatybilność z Claude Code, ustaw jedną z tych zmiennych środowiskowych: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [Priorytet](https://opencode.ai/docs/pl/rules/#priorytet) ---------------------------------------------------------- Po uruchomieniu opencode szuka plików reguł w następującej kolejności: 1. **Pliki lokalne** poprzez przejście z bieżącego katalogu (`AGENTS.md`, `CLAUDE.md`) 2. **Plik globalny** w `~/.config/opencode/AGENTS.md` 3. **Plik Claude Code** w `~/.claude/CLAUDE.md` (chyba że wyłączony) Pierwszy pasujący plik wygrywa w każdej kategorii. Na przykład, jeśli masz zarówno `AGENTS.md`, jak i `CLAUDE.md`, używany jest tylko `AGENTS.md`. Podobnie `~/.config/opencode/AGENTS.md` ma pierwszeństwo przed `~/.claude/CLAUDE.md`. * * * [Instrukcje niestandardowe](https://opencode.ai/docs/pl/rules/#instrukcje-niestandardowe) ------------------------------------------------------------------------------------------ Możesz określić niestandardowe pliki instrukcji w swoim `opencode.json` lub globalnym `~/.config/opencode/opencode.json`. Dzięki temu Ty i Twój zespół możecie ponownie wykorzystać istniejące reguły, zamiast duplikować je w pliku AGENTS.md. Przykład: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Możesz także użyć zdalnych adresów URL, aby załadować instrukcje z Internetu. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} Instrukcje zdalne są pobierane z 5-sekundowym limitem czasu. Wszystkie pliki instrukcji są łączone z plikami `AGENTS.md`. * * * [Odwoływanie się do plików zewnętrznych](https://opencode.ai/docs/pl/rules/#odwo%C5%82ywanie-si%C4%99-do-plik%C3%B3w-zewn%C4%99trznych) ---------------------------------------------------------------------------------------------------------------------------------------- Chociaż opencode nie analizuje automatycznie odniesień do plików w `AGENTS.md`, możesz osiągnąć podobną funkcjonalność na dwa sposoby: ### [Używanie opencode.json](https://opencode.ai/docs/pl/rules/#u%C5%BCywanie-opencodejson) Zalecanym podejściem jest użycie pola `instructions` w `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [Ręczne instrukcje w AGENTS.md](https://opencode.ai/docs/pl/rules/#r%C4%99czne-instrukcje-w-agentsmd) Możesz nauczyć opencode czytać pliki zewnętrzne, podając wyraźne instrukcje w swoim `AGENTS.md`. Oto praktyczny przykład: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. Takie podejście pozwala: * Twórz modułowe pliki reguł wielokrotnego użytku * Share rules across projects via symlinks or git submodules * Keep AGENTS.md concise while referencing detailed guidelines * Upewnij się, że opencode ładuje pliki tylko wtedy, gdy są potrzebne do konkretnego zadania --- # 규칙 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/rules/#_top) 규칙 == OpenCode에 대한 사용자 정의 지침 설정. `AGENTS.md` 파일을 만들 수 있도록 opencode에 사용자 정의 지침을 제공 할 수 있습니다. Cursor의 규칙과 유사합니다. LLM의 컨텍스트에 포함된 지침을 통해 특정 프로젝트에 대한 행동을 사용자 정의합니다. * * * [초기화](https://opencode.ai/docs/ko/rules/#%EC%B4%88%EA%B8%B0%ED%99%94) ---------------------------------------------------------------------- 새로운 `AGENTS.md` 파일을 만들려면 `/init` 명령을 opencode에서 실행할 수 있습니다. 프로젝트가 무엇인지 이해하고 `AGENTS.md` 파일을 생성합니다. 이 도움말 opencode는 프로젝트를 더 잘 탐색합니다. 기존 `AGENTS.md` 파일이있는 경우이 추가하려고합니다. * * * [예](https://opencode.ai/docs/ko/rules/#%EC%98%88) -------------------------------------------------- 이 파일을 수동으로 만들 수도 있습니다. 다음은 `AGENTS.md` 파일에 넣을 수있는 것들의 예입니다. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` 우리는 여기에 프로젝트 별 지침을 추가하고 이것은 팀을 통해 공유됩니다. * * * [유형](https://opencode.ai/docs/ko/rules/#%EC%9C%A0%ED%98%95) ------------------------------------------------------------ opencode는 또한 다수 위치에서 `AGENTS.md` 파일을 읽습니다. 그리고 이것은 다른 목적을 봉사합니다. [프로젝트](https://opencode.ai/docs/ko/rules/#%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8) -------------------------------------------------------------------------------- 프로젝트 별 규칙에 대한 프로젝트 루트에 `AGENTS.md`를 배치합니다. 이 디렉토리 또는 하위 디렉토리에서 작업 할 때만 적용됩니다. [전역](https://opencode.ai/docs/ko/rules/#%EC%A0%84%EC%97%AD) ------------------------------------------------------------ 또한 `~/.config/opencode/AGENTS.md` 파일에서 글로벌 규칙을 가질 수 있습니다. 이 모든 opencode 세션에서 적용됩니다. 이것은 Git에 전념하지 않거나 팀과 공유하지 않기 때문에 LLM이 따르는 모든 개인 규칙을 지정하는 것이 좋습니다. ### [Claude 코드 호환성](https://opencode.ai/docs/ko/rules/#claude-%EC%BD%94%EB%93%9C-%ED%98%B8%ED%99%98%EC%84%B1) Claude Code에서 마이그레이션하는 경우, opencode는 Claude Code의 파일 컨벤션을 fallbacks로 지원합니다. * \*\* 규칙 \*\* : 프로젝트 디렉토리에 `CLAUDE.md` (`AGENTS.md`가 존재하지 않는 경우 사용) * \*\* 글로벌 규칙\*\*: `~/.claude/CLAUDE.md` (`~/.config/opencode/AGENTS.md`가 존재하지 않는 경우 사용) -**Skills**: `~/.claude/skills/` — [Agent Skills](https://opencode.ai/docs/skills/) 를 참조하십시오. Claude Code 호환성을 비활성화하려면 이러한 환경 변수 중 하나를 설정하십시오. export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [우선순위](https://opencode.ai/docs/ko/rules/#%EC%9A%B0%EC%84%A0%EC%88%9C%EC%9C%84) -------------------------------------------------------------------------------- opencode가 시작될 때, 이 순서에 있는 규칙 파일을 찾습니다: 1. \*\*Local 파일 \*\* 현재 디렉토리에서 추적 (`AGENTS.md`, `CLAUDE.md`) 2. \*\* 글로벌 파일 \*\* `~/.config/opencode/AGENTS.md` 3. \*\*Claude 코드 파일 \*\* `~/.claude/CLAUDE.md`에서 (무효한) 첫 번째 일치 파일은 각 범주에서 승리합니다. 예를 들어, `AGENTS.md`와 `CLAUDE.md` 모두가있는 경우 `AGENTS.md` 만 사용됩니다. 유사하게, `~/.config/opencode/AGENTS.md`는 `~/.claude/CLAUDE.md`에 전진합니다. * * * [사용자 정의 지침](https://opencode.ai/docs/ko/rules/#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98-%EC%A7%80%EC%B9%A8) ------------------------------------------------------------------------------------------------------------------ `opencode.json` 또는 글로벌 `~/.config/opencode/opencode.json`에서 사용자 지정 명령 파일을 지정할 수 있습니다. AGENTS.md에 복제하지 않고 기존 규칙을 재사용 할 수 있습니다. 예: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} 웹에서 지침을로드하는 원격 URL도 사용할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} 원격 지침은 5 초 타임 아웃으로 fetched. 모든 명령 파일은 `AGENTS.md` 파일과 결합됩니다. * * * [외부 파일 참조](https://opencode.ai/docs/ko/rules/#%EC%99%B8%EB%B6%80-%ED%8C%8C%EC%9D%BC-%EC%B0%B8%EC%A1%B0) -------------------------------------------------------------------------------------------------------- opencode가 `AGENTS.md`에 있는 자동적으로 파스 파일 참조를 하지 않는 동안, 당신은 두 가지 방법으로 유사한 기능을 달성할 수 있습니다: [opencode.json 사용](https://opencode.ai/docs/ko/rules/#opencodejson-%EC%82%AC%EC%9A%A9) --------------------------------------------------------------------------------------- `instructions`의 `opencode.json` 필드를 사용하는 것이 좋습니다. { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [AGENTS.md의 수동 지침](https://opencode.ai/docs/ko/rules/#agentsmd%EC%9D%98-%EC%88%98%EB%8F%99-%EC%A7%80%EC%B9%A8) `AGENTS.md`에 명시된 지침을 제공함으로써 외부 파일을 읽을 수 있습니다. 여기에 실용적인 예: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. 이 접근법은 다음과 같습니다: * 모듈, 재사용 가능한 규칙 파일 생성 * symlinks 또는 git submodules를 통해 프로젝트 전반에 걸쳐 규칙 공유 * 상세한 가이드를 참조하면서 AGENTS.md concise 유지 * 특정 작업에 필요한 경우에만 opencode 로드 파일 유지 --- # Reglas | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/rules/#_top) Reglas ====== Establezca instrucciones personalizadas para opencode. Puede proporcionar instrucciones personalizadas a opencode creando un archivo `AGENTS.md`. Esto es similar a las reglas del Cursor. Contiene instrucciones que se incluirán en el contexto de LLM para personalizar su comportamiento para su proyecto específico. * * * [Inicializar](https://opencode.ai/docs/es/rules/#inicializar) -------------------------------------------------------------- Para crear un nuevo archivo `AGENTS.md`, puede ejecutar el comando `/init` en opencode. Esto escaneará su proyecto y todo su contenido para comprender de qué se trata y generar un archivo `AGENTS.md` con él. Esto ayuda a opencode a navegar mejor por el proyecto. Si tiene un archivo `AGENTS.md` existente, intentará agregarlo. * * * [Ejemplo](https://opencode.ai/docs/es/rules/#ejemplo) ------------------------------------------------------ También puedes crear este archivo manualmente. A continuación se muestra un ejemplo de algunas cosas que puede colocar en un archivo `AGENTS.md`. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` Estamos agregando instrucciones específicas del proyecto aquí y esto se compartirá con todo su equipo. * * * [Tipos](https://opencode.ai/docs/es/rules/#tipos) -------------------------------------------------- opencode también admite la lectura del archivo `AGENTS.md` desde múltiples ubicaciones. Y esto tiene diferentes propósitos. ### [Proyecto](https://opencode.ai/docs/es/rules/#proyecto) Coloque un `AGENTS.md` en la raíz de su proyecto para reglas específicas del proyecto. Estos solo se aplican cuando trabaja en este directorio o sus subdirectorios. ### [Global](https://opencode.ai/docs/es/rules/#global) También puedes tener reglas globales en un archivo `~/.config/opencode/AGENTS.md`. Esto se aplica en todas las sesiones opencode. Dado que esto no está comprometido con Git ni se comparte con su equipo, recomendamos usarlo para especificar las reglas personales que debe seguir LLM. ### [Compatibilidad con Claude Code](https://opencode.ai/docs/es/rules/#compatibilidad-con-claude-code) Para los usuarios que migran desde Claude Code, OpenCode admite las convenciones de archivos de Claude Code como alternativas: * **Reglas del proyecto**: `CLAUDE.md` en el directorio de tu proyecto (se usa si no existe `AGENTS.md`) * **Reglas globales**: `~/.claude/CLAUDE.md` (se usa si no existe `~/.config/opencode/AGENTS.md`) * **Habilidades**: `~/.claude/skills/`; consulte [Habilidades del agente](https://opencode.ai/docs/skills/) para obtener más detalles. Para deshabilitar la compatibilidad de Claude Code, configure una de estas variables de entorno: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [Prioridad](https://opencode.ai/docs/es/rules/#prioridad) ---------------------------------------------------------- Cuando se inicia opencode, busca archivos de reglas en este orden: 1. **Archivos locales** atravesando desde el directorio actual (`AGENTS.md`, `CLAUDE.md`) 2. **Archivo global** en `~/.config/opencode/AGENTS.md` 3. **Archivo de Claude Code** en `~/.claude/CLAUDE.md` (a menos que esté deshabilitado) El primer archivo coincidente gana en cada categoría. Por ejemplo, si tiene `AGENTS.md` y `CLAUDE.md`, solo se usa `AGENTS.md`. De manera similar, `~/.config/opencode/AGENTS.md` tiene prioridad sobre `~/.claude/CLAUDE.md`. * * * [Instrucciones personalizadas](https://opencode.ai/docs/es/rules/#instrucciones-personalizadas) ------------------------------------------------------------------------------------------------ Puede especificar archivos de instrucciones personalizados en su `opencode.json` o el `~/.config/opencode/opencode.json` global. Esto le permite a usted y a su equipo reutilizar las reglas existentes en lugar de tener que duplicarlas en AGENTS.md. Ejemplo: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} También puede utilizar URL remotas para cargar instrucciones desde la web. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} Las instrucciones remotas se recuperan con un tiempo de espera de 5 segundos. Todos los archivos de instrucciones se combinan con sus archivos `AGENTS.md`. * * * [Hacer referencia a archivos externos](https://opencode.ai/docs/es/rules/#hacer-referencia-a-archivos-externos) ---------------------------------------------------------------------------------------------------------------- Si bien opencode no analiza automáticamente las referencias de archivos en `AGENTS.md`, puedes lograr una funcionalidad similar de dos maneras: ### [Usar opencode.json](https://opencode.ai/docs/es/rules/#usar-opencodejson) El enfoque recomendado es utilizar el campo `instructions` en `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [Instrucciones manuales en AGENTS.md](https://opencode.ai/docs/es/rules/#instrucciones-manuales-en-agentsmd) Puede enseñarle a opencode a leer archivos externos proporcionando instrucciones explícitas en su `AGENTS.md`. He aquí un ejemplo práctico: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. Este enfoque le permite: * Crear archivos de reglas modulares y reutilizables * Compartir reglas entre proyectos a través de enlaces simbólicos o submódulos de git * Mantenga AGENTS.md conciso mientras hace referencia a pautas detalladas * Asegúrese de que opencode cargue archivos solo cuando sea necesario para la tarea específica --- # Temaer | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/themes/#_top) Temaer ====== Velg et innebygd tema eller definer ditt eget. Med OpenCode kan du velge fra ett av flere innebygde temaer, bruke et tema som tilpasser seg terminaltemaet ditt, eller definere ditt eget tilpassede tema. Som standard bruker OpenCode vårt eget `opencode`\-tema. * * * [Terminalkrav](https://opencode.ai/docs/nb/themes/#terminalkrav) ----------------------------------------------------------------- For at temaer skal vises riktig med fullfargepalett, må terminalen din støtte **truecolor** (24-biters farger). De fleste moderne terminaler støtter dette som standard, men du må kanskje aktivere det: * **Sjekk støtte**: Kjør `echo $COLORTERM` - den skal gi ut `truecolor` eller `24bit` * **Aktiver truecolor**: Sett miljøvariabelen `COLORTERM=truecolor` i shell-profilen din * **Terminalkompatibilitet**: Sørg for at terminalemulatoren din støtter 24-bits farger (de fleste moderne terminaler som iTerm2, Alacritty, Kitty, Windows Terminal og nyere versjoner av GNOME Terminal gjør det) Uten truecolor-støtte kan temaer vises med redusert fargenøyaktighet eller falle tilbake til nærmeste 256-fargers tilnærming. * * * [Innebygde temaer](https://opencode.ai/docs/nb/themes/#innebygde-temaer) ------------------------------------------------------------------------- OpenCode kommer med flere innebygde temaer. | Navn | Beskrivelse | | --- | --- | | `system` | Tilpasser seg terminalens bakgrunnsfarge | | `tokyonight` | Basert på [tokyonight](https://github.com/folke/tokyonight.nvim)
\-temaet | | `everforest` | Basert på [Everforest](https://github.com/sainnhe/everforest)
\-temaet | | `ayu` | Basert på [Ayu](https://github.com/ayu-theme)
mørke tema | | `catppuccin` | Basert på [Catppuccin](https://github.com/catppuccin)
\-temaet | | `catppuccin-macchiato` | Basert på [Catppuccin](https://github.com/catppuccin)
\-temaet | | `gruvbox` | Basert på [Gruvbox](https://github.com/morhetz/gruvbox)
\-temaet | | `kanagawa` | Basert på [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
\-temaet | | `nord` | Basert på [Nord](https://github.com/nordtheme/nord)
\-temaet | | `matrix` | Hacker-stil grønt på svart tema | | `one-dark` | Basert på [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Mørkt tema | Og mer, vi legger stadig til nye temaer. * * * [Systemtema](https://opencode.ai/docs/nb/themes/#systemtema) ------------------------------------------------------------- `system`\-temaet er designet for å automatisk tilpasse seg terminalens fargeskjema. I motsetning til tradisjonelle temaer som bruker faste farger, er _system_\-temaet: * **Genererer gråtone**: Oppretter en tilpasset gråskala basert på terminalens bakgrunnsfarge, og sikrer optimal kontrast. * **Bruker ANSI-farger**: Bruker standard ANSI farger (0-15) for syntaksutheving og UI elementer, som respekterer terminalens fargepalett. * **Bevarer terminalens standardinnstillinger**: Bruker `none` for tekst- og bakgrunnsfarger for å opprettholde terminalens opprinnelige utseende. Systemtemaet er for brukere som: * Vil at OpenCode skal matche terminalens utseende * Bruker tilpassede terminalfargeskjemaer * Foretrekker et konsistent utseende på tvers av alle terminalapplikasjoner * * * [Bruke et tema](https://opencode.ai/docs/nb/themes/#bruke-et-tema) ------------------------------------------------------------------- Du kan velge et tema ved å åpne temavelgeren med kommandoen `/theme`. Eller du kan spesifisere det i `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Egendefinerte temaer](https://opencode.ai/docs/nb/themes/#egendefinerte-temaer) --------------------------------------------------------------------------------- OpenCode støtter et fleksibelt JSON-basert temasystem som lar brukere enkelt lage og tilpasse temaer. * * * ### [Hierarki](https://opencode.ai/docs/nb/themes/#hierarki) Temaer lastes inn fra flere kataloger i følgende rekkefølge der senere kataloger overstyrer tidligere: 1. **Innebygde temaer** - Disse er innebygd i binæren 2. **Brukerkonfigurasjonskatalog** - Definert i `~/.config/opencode/themes/*.json` eller `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Prosjektrotkatalog** - Definert i `/.opencode/themes/*.json` 4. **Gjeldende arbeidskatalog** - Definert i `./.opencode/themes/*.json` Hvis flere kataloger inneholder et tema med samme navn, vil temaet fra katalogen med høyere prioritet bli brukt. * * * ### [Opprette et tema](https://opencode.ai/docs/nb/themes/#opprette-et-tema) For å lage et tilpasset tema, lag en JSON-fil i en av temakatalogene. For brukerspesifikke temaer: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json Og for prosjektspesifikke temaer. mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON-format](https://opencode.ai/docs/nb/themes/#json-format) Temaer bruker et fleksibelt JSON-format med støtte for: * **Hex-farger**: `"#ffffff"` * **ANSI-farger**: `3` (0-255) * **Fargereferanser**: `"primary"` eller egendefinerte definisjoner * **Mørke/lyse varianter**: `{"dark": "#000", "light": "#fff"}` * **Ingen farge**: `"none"` - Bruker terminalens standardfarge eller transparent * * * ### [Fargedefinisjoner](https://opencode.ai/docs/nb/themes/#fargedefinisjoner) `defs`\-delen er valgfri, og den lar deg definere gjenbrukbare farger som kan refereres til i temaet. * * * ### [Terminalstandarder](https://opencode.ai/docs/nb/themes/#terminalstandarder) Spesialverdien `"none"` kan brukes for hvilken som helst farge for å arve terminalens standardfarge. Dette er spesielt nyttig for å lage temaer som passer sømløst med terminalens fargeskjema: * `"text": "none"` - Bruker terminalens standard forgrunnsfarge * `"background": "none"` - Bruker terminalens standard bakgrunnsfarge * * * ### [Eksempel](https://opencode.ai/docs/nb/themes/#eksempel) Her er et eksempel på et tilpasset tema: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # LSP-servere | OpenCode [Gå til indhold](https://opencode.ai/docs/da/lsp/#_top) LSP-servere =========== OpenCode integreres med dine LSP-servere. OpenCode kan integreres med Language Server Protocol (LSP)-servere for at bruge diagnostik som feedback til agenten. * * * [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 er deaktiveret som standard. Når det er aktiveret, starter servere, 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 LSP er aktiveret, og 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. * * * [Bedste praksis](https://opencode.ai/docs/da/lsp/#bedste-praksis) ------------------------------------------------------------------ LSP kan hjælpe agenten med at finde og rette problemer ved at levere diagnostik fra sprogservere. Det er nyttigt i nogle projekter, men er ikke altid en klar fordel. Sprogservere kan komme ud af sync, bruge meget hukommelse, variere efter version eller projekt og gøre agentarbejdsgange langsommere. I mange projekter er det bedre, at agenten kører lint, typecheck eller andre diagnostiske CLI-værktøjer direkte, så fejl føres tilbage i agentens loop uden disse afvejninger. Dokumentér disse kommandoer i instruktionsfiler som `AGENTS.md` eller skills, så agenten ved, hvad den skal køre. Aktivér LSP, når dit projekt har gavn af ekstra sprogserverfeedback. * * * [Konfiguration](https://opencode.ai/docs/da/lsp/#konfiguration) ---------------------------------------------------------------- Du kan aktivere og tilpasse LSP-servere gennem sektionen `lsp` i din opencode-konfiguration. For at aktivere alle indbyggede LSP-servere skal du indstille `lsp` til `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Brug et objekt til at holde indbyggede servere aktiveret, mens du konfigurerer tilsidesættelser eller brugerdefinerede servere. { "$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) Hvis `lsp` udelades, er alle LSP-servere deaktiveret. For at deaktivere alle LSP-servere efter at en anden konfiguration har aktiveret dem, 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. --- # ACP サポート | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/acp/#_top) ACP サポート ======== ACP 互換エディターで OpenCode を使用します。 OpenCode は [Agent Client Protocol](https://agentclientprotocol.com/) または (ACP) をサポートしているため、互換性のあるエディターや IDE で直接使用できます。 ACP は、コードエディターと AI コーディングエージェント間の通信を標準化するオープンプロトコルです。 * * * [設定](https://opencode.ai/docs/ja/acp/#%E8%A8%AD%E5%AE%9A) ---------------------------------------------------------- ACP 経由で OpenCode を使用するには、`opencode acp` コマンドを実行するようにエディタを設定します。 このコマンドは、stdio 経由で JSON-RPC 経由でエディターと通信する ACP 互換のサブプロセスとして OpenCode を開始します。 以下は、ACP をサポートする一般的なエディタの例です。 * * * ### [Zed](https://opencode.ai/docs/ja/acp/#zed) [Zed](https://zed.dev/) 構成 (`~/.config/zed/settings.json`) に追加します。 { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} これを開くには、**コマンドパレット**の `agent: new thread` アクションを使用します。 `keymap.json` を編集してキーボードショートカットをバインドすることもできます。 [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDE](https://opencode.ai/docs/ja/acp/#jetbrains-ide) [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html) に従って、[JetBrains IDE](https://www.jetbrains.com/) acp.json に追加します: { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} これを開くには、AI Chat エージェントセレクターで新しい「OpenCode」エージェントを使用します。 * * * ### [Avante.nvim](https://opencode.ai/docs/ja/acp/#avantenvim) [Avante.nvim](https://github.com/yetone/avante.nvim) 設定に追加: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} 環境変数を渡す必要がある場合: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/ja/acp/#codecompanionnvim) [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) で OpenCode を ACP エージェントとして使用するには、以下を Neovim 構成に追加します。 require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) この構成は、OpenCode をチャットの ACP エージェントとして使用するように CodeCompanion をセットアップします。 環境変数 (`OPENCODE_API_KEY` など) を渡す必要がある場合、詳細については、CodeCompanion.nvim ドキュメントの「[アダプターの構成: 環境変数](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) 」を参照してください。 [サポート](https://opencode.ai/docs/ja/acp/#%E3%82%B5%E3%83%9D%E3%83%BC%E3%83%88) ------------------------------------------------------------------------------ OpenCode は、ACP 経由でもターミナル内で動作するのと同じように動作します。すべての機能がサポートされています。 * 組み込みツール (ファイル操作、ターミナルコマンドなど) * カスタムツールとスラッシュコマンド * OpenCode 設定で構成された MCP サーバー * `AGENTS.md` のプロジェクト固有のルール * カスタムフォーマッタとリンター * エージェントと権限システム --- # ACP Support | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/acp/#_top) ACP Support =========== Use OpenCode in any ACP-compatible editor. OpenCode는 [Agent Client Protocol](https://agentclientprotocol.com/) (ACP)을 지원하므로, ACP 호환 편집기와 IDE에서 OpenCode를 직접 사용할 수 있습니다. ACP는 코드 편집기와 AI 코딩 에이전트 간의 통신을 표준화하는 개방형 프로토콜입니다. * * * [구성](https://opencode.ai/docs/ko/acp/#%EA%B5%AC%EC%84%B1) ---------------------------------------------------------- ACP로 OpenCode를 사용하려면, 편집기에서 `opencode acp` 명령을 실행하도록 config를 설정하세요. 이 명령은 OpenCode를 ACP 호환 subprocess로 시작하며, stdio 기반 JSON-RPC를 통해 편집기와 통신합니다. 아래는 ACP를 지원하는 주요 편집기 예시입니다. * * * ### [Zed](https://opencode.ai/docs/ko/acp/#zed) [Zed](https://zed.dev/) config(`~/.config/zed/settings.json`)에 다음을 추가하세요. { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} 열려면 **Command Palette**에서 `agent: new thread` action을 사용하세요. `keymap.json`을 수정해 키보드 단축키를 바인딩할 수도 있습니다. [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/ko/acp/#jetbrains-ides) [JetBrains IDE](https://www.jetbrains.com/) 에서는 [documentation](https://www.jetbrains.com/help/ai-assistant/acp.html) 에 따라 `acp.json`에 다음을 추가하세요. { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} 열려면 AI Chat agent selector에서 새 `OpenCode` agent를 선택하세요. * * * ### [Avante.nvim](https://opencode.ai/docs/ko/acp/#avantenvim) [Avante.nvim](https://github.com/yetone/avante.nvim) config에 다음을 추가하세요. { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} 환경 변수를 전달해야 한다면 다음과 같이 설정하세요. { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/ko/acp/#codecompanionnvim) [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) 에서 OpenCode를 ACP agent로 사용하려면 Neovim config에 다음을 추가하세요. require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) 이 config는 chat에서 OpenCode를 ACP agent로 사용하도록 CodeCompanion을 설정합니다. 환경 변수(`OPENCODE_API_KEY` 등)를 전달해야 한다면 CodeCompanion.nvim documentation의 [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) 를 참고하세요. [지원](https://opencode.ai/docs/ko/acp/#%EC%A7%80%EC%9B%90) ---------------------------------------------------------- OpenCode는 ACP를 통해서도 터미널과 동일하게 동작합니다. 다음 기능을 모두 지원합니다. * 내장 tool(파일 작업, terminal 명령 등) * 사용자 정의 tool과 slash command * OpenCode config에 설정한 MCP 서버 * `AGENTS.md`의 프로젝트별 규칙 * 사용자 정의 formatter와 linter * agent 및 권한 시스템 --- # 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 może integrować się z serwerami Language Server Protocol (LSP), aby używać diagnostyki jako informacji zwrotnej dla agenta. * * * [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` | LSP jest domyślnie wyłączone. Gdy jest włączone, serwery uruchamiają się po wykryciu jednego z obsługiwanych rozszerzeń plików i spełnieniu wymagań. * * * [Jak to działa](https://opencode.ai/docs/pl/lsp/#jak-to-dzia%C5%82a) --------------------------------------------------------------------- Gdy LSP jest włączony i 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. * * * [Dobre praktyki](https://opencode.ai/docs/pl/lsp/#dobre-praktyki) ------------------------------------------------------------------ LSP może pomóc agentowi znajdować i naprawiać problemy, dostarczając diagnostykę z serwerów językowych. Jest to przydatne w niektórych projektach, ale nie zawsze jest jednoznaczną korzyścią. Serwery językowe mogą wypaść z synchronizacji, zużywać dużo pamięci, różnić się między wersjami lub projektami i spowalniać workflow agenta. W wielu projektach lepiej, aby agent uruchamiał lint, typecheck lub inne diagnostyczne narzędzia CLI bezpośrednio; wtedy błędy wracają do pętli agenta bez tych kompromisów. Udokumentuj te komendy w plikach instrukcji, takich jak `AGENTS.md` lub skills, aby agent wiedział, co uruchomić. Włącz LSP, gdy Twój projekt korzysta z dodatkowej informacji zwrotnej z serwera językowego. * * * [Konfiguracja](https://opencode.ai/docs/pl/lsp/#konfiguracja) -------------------------------------------------------------- Możesz włączać i dostosowywać serwery LSP poprzez sekcję `lsp` w konfiguracji OpenCode. Aby włączyć wszystkie wbudowane serwery LSP, ustaw `lsp` na `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Użyj obiektu, aby pozostawić wbudowane serwery włączone i jednocześnie skonfigurować nadpisania lub serwery niestandardowe. { "$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) Jeśli `lsp` zostanie pominięte, wszystkie serwery LSP są wyłączone. Aby wyłączyć wszystkie serwery LSP po tym, jak inna konfiguracja je włączyła, 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. --- # LSP 服务器 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/lsp/#_top) LSP 服务器 ======= OpenCode 与你的 LSP 服务器集成。 OpenCode 可以与语言服务器协议(LSP)服务器集成,将诊断信息作为 agent 的反馈。 * * * [内置支持](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) --------------------------------------------------------------------------------- 启用 LSP 且 opencode 打开文件时,它会: 1. 将文件扩展名与所有已启用的 LSP 服务器进行匹配。 2. 如果对应的 LSP 服务器尚未运行,则自动启动它。 * * * [最佳实践](https://opencode.ai/docs/zh-cn/lsp/#%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5) --------------------------------------------------------------------------------- LSP 可以通过语言服务器诊断帮助 agent 发现并修复问题。这对某些项目很有用,但并不总是带来净收益。 语言服务器可能与项目不同步、占用较多内存、随版本或项目表现不同,并拖慢 agent 工作流。在许多项目中,更好的做法是让 agent 直接运行 lint、typecheck 或其他诊断类 CLI 工具,这样错误会进入 agent 循环,同时避免这些权衡。将这些命令记录在 `AGENTS.md` 或 skills 等指令文件中,让 agent 知道该运行什么。当你的项目能从额外的语言服务器反馈中受益时再启用 LSP。 * * * [配置](https://opencode.ai/docs/zh-cn/lsp/#%E9%85%8D%E7%BD%AE) ------------------------------------------------------------- 你可以通过 opencode 配置文件中的 `lsp` 部分来启用并自定义 LSP 服务器。 要启用所有内置 LSP 服务器,请将 `lsp` 设置为 `true`。 { "$schema": "https://opencode.ai/config.json", "lsp": true} 使用对象可以在保持内置服务器启用的同时配置覆盖项或自定义服务器。 { "$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 服务器都会被禁用。如果另一个配置启用了 LSP,可将 `lsp` 设置为 `false` 来禁用所有 LSP 服务器: { "$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` 该文件应仅包含许可证密钥,不要添加其他任何内容。 --- # MCP-серверы | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/mcp-servers/#_top) MCP-серверы =========== Добавьте локальные и удаленные инструменты MCP. Вы можете добавить внешние инструменты в opencode, используя _Model Context Protocol_ или MCP. opencode поддерживает как локальные, так и удаленные серверы. После добавления инструменты MCP автоматически становятся доступными для LLM наряду со встроенными инструментами. * * * #### [Предостережения](https://opencode.ai/docs/ru/mcp-servers/#%D0%BF%D1%80%D0%B5%D0%B4%D0%BE%D1%81%D1%82%D0%B5%D1%80%D0%B5%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F) Когда вы используете сервер MCP, он добавляет контекст. Это может быстро сложиться, если у вас много инструментов. Поэтому мы рекомендуем быть осторожными с тем, какие серверы MCP вы используете. Некоторые серверы MCP, такие как сервер MCP GitHub, имеют тенденцию добавлять много токенов и могут легко превысить ограничение контекста. * * * [Включение](https://opencode.ai/docs/ru/mcp-servers/#%D0%B2%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5) ------------------------------------------------------------------------------------------------------------- Вы можете определить серверы MCP в своем [opencode Config](https://opencode.ai/docs/config/) в разделе `mcp`. Добавьте каждому MCP уникальное имя. Вы можете обратиться к этому MCP по имени при запросе LLM. { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} Вы также можете отключить сервер, установив для `enabled` значение `false`. Это полезно, если вы хотите временно отключить сервер, не удаляя его из конфигурации. * * * ### [Переопределение удаленных настроек по умолчанию](https://opencode.ai/docs/ru/mcp-servers/#%D0%BF%D0%B5%D1%80%D0%B5%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%BD%D1%8B%D1%85-%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BA-%D0%BF%D0%BE-%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E) Организации могут предоставлять серверы MCP по умолчанию через свою конечную точку `.well-known/opencode`. Эти серверы могут быть отключены по умолчанию, что позволяет пользователям выбирать те, которые им нужны. Чтобы включить определенный сервер из удаленной конфигурации вашей организации, добавьте его в локальную конфигурацию с помощью `enabled: true`: { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} Значения вашей локальной конфигурации переопределяют удаленные значения по умолчанию. Дополнительную информацию см. в [приоритете конфигурации](https://opencode.ai/docs/config#precedence-order) . * * * [Локальные](https://opencode.ai/docs/ru/mcp-servers/#%D0%BB%D0%BE%D0%BA%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5) ------------------------------------------------------------------------------------------------------------- Добавьте локальные серверы MCP с помощью `type` в `"local"` внутри объекта MCP. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} Эта команда запускает локальный сервер MCP. Вы также можете передать список переменных среды. Например, вот как можно добавить тестовый сервер [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP. { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} И чтобы использовать его, добавьте `use the mcp_everything tool` в свои подсказки. use the mcp_everything tool to add the number 3 and 4 * * * #### [Параметры](https://opencode.ai/docs/ru/mcp-servers/#%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B) Вот все варианты настройки локального сервера MCP. | Вариант | Тип | Обязательный | Описание | | --- | --- | --- | --- | | `type` | Строка | Да | Тип подключения к серверу MCP должен быть `"local"`. | | `command` | Массив | Да | Команда и аргументы для запуска сервера MCP. | | `environment` | Объект | | Переменные среды, которые необходимо установить при запуске сервера. | | `enabled` | логическое значение | | Включите или отключите сервер MCP при запуске. | | `timeout` | Число | | Тайм-аут в мс для получения инструментов с сервера MCP. По умолчанию 5000 (5 секунд). | * * * [Удаленные](https://opencode.ai/docs/ru/mcp-servers/#%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5) ------------------------------------------------------------------------------------------------------------- Добавьте удаленные серверы MCP, установив для `type` значение `"remote"`. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} `url` — это URL-адрес удаленного сервера MCP, а с помощью параметра `headers` вы можете передать список заголовков. * * * #### [Параметры](https://opencode.ai/docs/ru/mcp-servers/#%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B-1) | Вариант | Тип | Обязательный | Описание | | --- | --- | --- | --- | | `type` | Строка | Да | Тип подключения к серверу MCP должен быть `"remote"`. | | `url` | Строка | Да | URL-адрес удаленного сервера MCP. | | `enabled` | логическое значение | | Включите или отключите сервер MCP при запуске. | | `headers` | Объект | | Заголовки для отправки с запросом. | | `oauth` | Объект | | Конфигурация аутентификации OAuth. См. раздел [OAuth](https://opencode.ai/docs/ru/mcp-servers/#oauth)
ниже. | | `timeout` | Число | | Тайм-аут в мс для получения инструментов с сервера MCP. По умолчанию 5000 (5 секунд). | * * * [OAuth](https://opencode.ai/docs/ru/mcp-servers/#oauth) -------------------------------------------------------- opencode автоматически обрабатывает аутентификацию OAuth для удаленных серверов MCP. Когда серверу требуется аутентификация, opencode: 1. Обнаружьте ответ 401 и инициируйте поток OAuth. 2. Используйте **Динамическую регистрацию клиента (RFC 7591)**, если это поддерживается сервером. 3. Надежно храните токены для будущих запросов * * * ### [Автоматически](https://opencode.ai/docs/ru/mcp-servers/#%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%B8) Для большинства серверов MCP с поддержкой OAuth не требуется никакой специальной настройки. Просто настройте удаленный сервер: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} Если сервер требует аутентификации, opencode предложит вам пройти аутентификацию при первой попытке его использования. Если нет, вы можете [вручную запустить поток](https://opencode.ai/docs/ru/mcp-servers/#authenticating) с помощью `opencode mcp auth `. * * * ### [Предварительная регистрация](https://opencode.ai/docs/ru/mcp-servers/#%D0%BF%D1%80%D0%B5%D0%B4%D0%B2%D0%B0%D1%80%D0%B8%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F-%D1%80%D0%B5%D0%B3%D0%B8%D1%81%D1%82%D1%80%D0%B0%D1%86%D0%B8%D1%8F) Если у вас есть учетные данные клиента от поставщика сервера MCP, вы можете их настроить: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [Аутентификация](https://opencode.ai/docs/ru/mcp-servers/#%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) Вы можете вручную активировать аутентификацию или управлять учетными данными. Аутентификация с помощью определенного сервера MCP: opencode mcp auth my-oauth-server Перечислите все серверы MCP и их статус аутентификации: opencode mcp list Удалить сохраненные учетные данные: opencode mcp logout my-oauth-server Команда `mcp auth` откроет ваш браузер для авторизации. После того как вы авторизуетесь, opencode надежно сохранит токены в `~/.local/share/opencode/mcp-auth.json`. * * * #### [Отключение OAuth](https://opencode.ai/docs/ru/mcp-servers/#%D0%BE%D1%82%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-oauth) Если вы хотите отключить автоматический OAuth для сервера (например, для серверов, которые вместо этого используют ключи API), установите для `oauth` значение `false`: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [Параметры OAuth](https://opencode.ai/docs/ru/mcp-servers/#%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B-oauth) | Вариант | Тип | Описание | | --- | --- | --- | | `oauth` | Object \| false | Объект конфигурации OAuth или `false`, чтобы отключить автообнаружение OAuth. | | `clientId` | String | OAuth client ID. Если не указан, будет выполнена динамическая регистрация клиента. | | `clientSecret` | String | OAuth client secret, если этого требует сервер авторизации. | | `scope` | String | OAuth scopes для запроса во время авторизации. | #### [Отладка](https://opencode.ai/docs/ru/mcp-servers/#%D0%BE%D1%82%D0%BB%D0%B0%D0%B4%D0%BA%D0%B0) Если удаленный сервер MCP не может аутентифицироваться, вы можете диагностировать проблемы с помощью: # View auth status for all OAuth-capable serversopencode mcp auth list # Debug connection and OAuth flow for a specific serveropencode mcp debug my-oauth-server Команда `mcp debug` показывает текущий статус аутентификации, проверяет соединение HTTP и пытается выполнить поток обнаружения OAuth. * * * [Управление](https://opencode.ai/docs/ru/mcp-servers/#%D1%83%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5) -------------------------------------------------------------------------------------------------------------------- Ваши MCP доступны в виде инструментов opencode наряду со встроенными инструментами. Таким образом, вы можете управлять ими через конфигурацию opencode, как и любым другим инструментом. * * * ### [Глобально](https://opencode.ai/docs/ru/mcp-servers/#%D0%B3%D0%BB%D0%BE%D0%B1%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE) Это означает, что вы можете включать или отключать их глобально. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} Мы также можем использовать шаблон glob, чтобы отключить все соответствующие MCP. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} Здесь мы используем шаблон `my-mcp*` для отключения всех MCP. * * * ### [Для каждого агента](https://opencode.ai/docs/ru/mcp-servers/#%D0%B4%D0%BB%D1%8F-%D0%BA%D0%B0%D0%B6%D0%B4%D0%BE%D0%B3%D0%BE-%D0%B0%D0%B3%D0%B5%D0%BD%D1%82%D0%B0) Если у вас большое количество серверов MCP, вы можете включить их только для каждого агента и отключить глобально. Для этого: 1. Отключите его как инструмент глобально. 2. В вашей [конфигурации агента](https://opencode.ai/docs/agents#tools) включите сервер MCP в качестве инструмента. { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [Glob-шаблоны](https://opencode.ai/docs/ru/mcp-servers/#glob-%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD%D1%8B) Шаблон glob использует простые шаблоны подстановки регулярных выражений: * `*` соответствует нулю или более любого символа (например, `"my-mcp*"` соответствует `my-mcp_search`, `my-mcp_list` и т. д.). * `?` соответствует ровно одному символу. * Все остальные символы совпадают буквально * * * [Примеры](https://opencode.ai/docs/ru/mcp-servers/#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B) ----------------------------------------------------------------------------------------------- Ниже приведены примеры некоторых распространенных серверов MCP. Вы можете отправить PR, если хотите документировать другие серверы. * * * ### [Sentry](https://opencode.ai/docs/ru/mcp-servers/#sentry) Добавьте [сервер Sentry MCP](https://mcp.sentry.dev/) для взаимодействия с вашими проектами и проблемами Sentry. { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} После добавления конфигурации пройдите аутентификацию с помощью Sentry: opencode mcp auth sentry Откроется окно браузера для завершения процесса OAuth и подключения opencode к вашей учетной записи Sentry. После аутентификации вы можете использовать инструменты Sentry в своих подсказках для запроса данных о проблемах, проектах и ​​ошибках. Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/ru/mcp-servers/#context7) Добавьте [сервер Context7 MCP](https://github.com/upstash/context7) для поиска в документах. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} Если вы зарегистрировали бесплатную учетную запись, вы можете использовать свой ключ API и получить более высокие ограничения скорости. { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} Здесь мы предполагаем, что у вас установлена ​​переменная среды `CONTEXT7_API_KEY`. Добавьте `use context7` в запросы на использование сервера Context7 MCP. Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 Альтернативно вы можете добавить что-то подобное в свой файл [AGENTS.md](https://opencode.ai/docs/rules/) . When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/ru/mcp-servers/#grep-by-vercel) Добавьте сервер MCP [Grep от Vercel](https://grep.app/) для поиска по фрагментам кода на GitHub. { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} Поскольку мы назвали наш сервер MCP `gh_grep`, вы можете добавить `use the gh_grep tool` в свои запросы, чтобы агент мог его использовать. What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool Альтернативно вы можете добавить что-то подобное в свой файл [AGENTS.md](https://opencode.ai/docs/rules/) . If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # Правила | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/rules/#_top) Правила ======= Установите пользовательские инструкции для opencode. Вы можете предоставить собственные инструкции для opencode, создав файл `AGENTS.md`. Это похоже на правила Cursor. Он содержит инструкции, которые будут включены в контекст LLM для настройки его поведения для вашего конкретного проекта. * * * [Инициализировать](https://opencode.ai/docs/ru/rules/#%D0%B8%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C) -------------------------------------------------------------------------------------------------------------------------------------------------------- Чтобы создать новый файл `AGENTS.md`, вы можете запустить команду `/init` в opencode. Это позволит отсканировать ваш проект и все его содержимое, чтобы понять, о чем этот проект, и сгенерировать с его помощью файл `AGENTS.md`. Это помогает opencode лучше ориентироваться в проекте. Если у вас есть существующий файл `AGENTS.md`, мы попытаемся добавить его. * * * [Пример](https://opencode.ai/docs/ru/rules/#%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80) ---------------------------------------------------------------------------------- Вы также можете просто создать этот файл вручную. Вот пример того, что вы можете поместить в файл `AGENTS.md`. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` Мы добавляем сюда инструкции для конкретного проекта, и они будут доступны всей вашей команде. * * * [Типы](https://opencode.ai/docs/ru/rules/#%D1%82%D0%B8%D0%BF%D1%8B) -------------------------------------------------------------------- opencode также поддерживает чтение файла `AGENTS.md` из нескольких мест. И это служит разным целям. ### [Проект](https://opencode.ai/docs/ru/rules/#%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82) Поместите `AGENTS.md` в корень вашего проекта для правил, специфичных для проекта. Они применяются только тогда, когда вы работаете в этом каталоге или его подкаталогах. ### [Глобальный](https://opencode.ai/docs/ru/rules/#%D0%B3%D0%BB%D0%BE%D0%B1%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9) Вы также можете иметь глобальные правила в файле `~/.config/opencode/AGENTS.md`. Это применяется ко всем сеансам opencode. Поскольку это не коммитится в Git и не передается вашей команде, мы рекомендуем использовать его для указания любых личных правил, которым должен следовать LLM. ### [Совместимость кода Клода](https://opencode.ai/docs/ru/rules/#%D1%81%D0%BE%D0%B2%D0%BC%D0%B5%D1%81%D1%82%D0%B8%D0%BC%D0%BE%D1%81%D1%82%D1%8C-%D0%BA%D0%BE%D0%B4%D0%B0-%D0%BA%D0%BB%D0%BE%D0%B4%D0%B0) Для пользователей, переходящих с Claude Code, opencode поддерживает файловые соглашения Claude Code в качестве резерва: * **Правила проекта**: `CLAUDE.md` в каталоге вашего проекта (используется, если `AGENTS.md` не существует). * **Глобальные правила**: `~/.claude/CLAUDE.md` (используется, если `~/.config/opencode/AGENTS.md` не существует). * **Навыки**: `~/.claude/skills/` — подробности см. в [Навыки агента](https://opencode.ai/docs/skills/) . Чтобы отключить совместимость Claude Code, установите одну из этих переменных среды: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [Приоритет](https://opencode.ai/docs/ru/rules/#%D0%BF%D1%80%D0%B8%D0%BE%D1%80%D0%B8%D1%82%D0%B5%D1%82) ------------------------------------------------------------------------------------------------------- Когда opencode запускается, он ищет файлы правил в следующем порядке: 1. **Локальные файлы** путем перехода вверх из текущего каталога (`AGENTS.md`, `CLAUDE.md`) 2. **Глобальный файл** в `~/.config/opencode/AGENTS.md`. 3. **Файл кода Клауда** по адресу `~/.claude/CLAUDE.md` (если не отключено) Первый совпадающий файл побеждает в каждой категории. Например, если у вас есть и `AGENTS.md`, и `CLAUDE.md`, используется только `AGENTS.md`. Аналогично, `~/.config/opencode/AGENTS.md` имеет приоритет над `~/.claude/CLAUDE.md`. * * * [Пользовательские инструкции](https://opencode.ai/docs/ru/rules/#%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%BA%D1%86%D0%B8%D0%B8) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Вы можете указать собственные файлы инструкций в `opencode.json` или в глобальном `~/.config/opencode/opencode.json`. Это позволит вам и вашей команде повторно использовать существующие правила вместо того, чтобы дублировать их на AGENTS.md. Пример: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Вы также можете использовать удаленные URL-адреса для загрузки инструкций из Интернета. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} Удаленные инструкции извлекаются с таймаутом в 5 секунд. Все файлы инструкций объединяются с вашими файлами `AGENTS.md`. * * * [Ссылки на внешние файлы](https://opencode.ai/docs/ru/rules/#%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8-%D0%BD%D0%B0-%D0%B2%D0%BD%D0%B5%D1%88%D0%BD%D0%B8%D0%B5-%D1%84%D0%B0%D0%B9%D0%BB%D1%8B) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Хотя opencode не анализирует автоматически ссылки на файлы в `AGENTS.md`, аналогичной функциональности можно добиться двумя способами: ### [Использование opencode.json](https://opencode.ai/docs/ru/rules/#%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-opencodejson) Рекомендуемый подход — использовать поле `instructions` в `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [Ручные инструкции в AGENTS.md](https://opencode.ai/docs/ru/rules/#%D1%80%D1%83%D1%87%D0%BD%D1%8B%D0%B5-%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%86%D0%B8%D0%B8-%D0%B2-agentsmd) Вы можете научить opencode читать внешние файлы, предоставив явные инструкции в файле `AGENTS.md`. Вот практический пример: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. Такой подход позволяет: * Создавайте модульные файлы правил многократного использования. * Делитесь правилами между проектами с помощью символических ссылок или подмодулей git. * Сохраняйте AGENTS.md кратким, ссылаясь на подробные инструкции. * Убедитесь, что opencode загружает файлы только тогда, когда это необходимо для конкретной задачи. --- # Servidores LSP | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/lsp/#_top) Servidores LSP ============== O opencode integra-se aos seus servidores LSP. O opencode pode se integrar a servidores Language Server Protocol (LSP) para usar diagnósticos como feedback para o agente. * * * [Integrados](https://opencode.ai/docs/pt-br/lsp/#integrados) ------------------------------------------------------------- O opencode vem com vários servidores LSP integrados para linguagens populares: | Servidor LSP | Extensões | Requisitos | | --- | --- | --- | | astro | .astro | Instala automaticamente para projetos Astro | | bash | .sh, .bash, .zsh, .ksh | Instala automaticamente bash-language-server | | clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Instala automaticamente para projetos C/C++ | | csharp | .cs | `.NET SDK` instalado | | clojure-lsp | .clj, .cljs, .cljc, .edn | Comando `clojure-lsp` disponível | | dart | .dart | Comando `dart` disponível | | deno | .ts, .tsx, .js, .jsx, .mjs | Comando `deno` disponível (detecta automaticamente deno.json/deno.jsonc) | | elixir-ls | .ex, .exs | Comando `elixir` disponível | | eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | Dependência `eslint` no projeto | | fsharp | .fs, .fsi, .fsx, .fsscript | `.NET SDK` instalado | | gleam | .gleam | Comando `gleam` disponível | | gopls | .go | Comando `go` disponível | | hls | .hs, .lhs | Comando `haskell-language-server-wrapper` disponível | | jdtls | .java | `Java SDK (version 21+)` instalado | | julials | .jl | `julia` e `LanguageServer.jl` instalados | | kotlin-ls | .kt, .kts | Instala automaticamente para projetos Kotlin | | lua-ls | .lua | Instala automaticamente para projetos Lua | | nixd | .nix | Comando `nixd` disponível | | ocaml-lsp | .ml, .mli | Comando `ocamllsp` disponível | | oxlint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue, .astro, .svelte | Dependência `oxlint` no projeto | | php intelephense | .php | Instala automaticamente para projetos PHP | | prisma | .prisma | Comando `prisma` disponível | | pyright | .py, .pyi | Dependência `pyright` instalada | | ruby-lsp (rubocop) | .rb, .rake, .gemspec, .ru | Comandos `ruby` e `gem` disponíveis | | rust | .rs | Comando `rust-analyzer` disponível | | sourcekit-lsp | .swift, .objc, .objcpp | `swift` instalado (`xcode` no macOS) | | svelte | .svelte | Instala automaticamente para projetos Svelte | | terraform | .tf, .tfvars | Instala automaticamente a partir de lançamentos do GitHub | | tinymist | .typ, .typc | Instala automaticamente a partir de lançamentos do GitHub | | typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | Dependência `typescript` no projeto | | vue | .vue | Instala automaticamente para projetos Vue | | yaml-ls | .yaml, .yml | Instala automaticamente o servidor yaml-language-server da Red Hat | | zls | .zig, .zon | Comando `zig` disponível | O LSP fica desabilitado por padrão. Quando habilitado, os servidores iniciam quando uma das extensões de arquivo acima é detectada e os requisitos são atendidos. * * * [Como Funciona](https://opencode.ai/docs/pt-br/lsp/#como-funciona) ------------------------------------------------------------------- Quando o LSP está habilitado e o opencode abre um arquivo, ele: 1. Verifica a extensão do arquivo em relação a todos os servidores LSP habilitados. 2. Inicia o servidor LSP apropriado se não estiver em execução. * * * [Boas práticas](https://opencode.ai/docs/pt-br/lsp/#boas-pr%C3%A1ticas) ------------------------------------------------------------------------ O LSP pode ajudar o agente a encontrar e corrigir problemas fornecendo diagnósticos dos servidores de linguagem. Isso é útil em alguns projetos, mas nem sempre é um ganho líquido. Servidores de linguagem podem ficar fora de sincronia, usar bastante memória, variar por versão ou projeto e desacelerar fluxos de trabalho do agente. Em muitos projetos, é melhor fazer o agente executar lint, typecheck ou outras ferramentas CLI de diagnóstico diretamente, para que os erros voltem ao ciclo do agente sem essas compensações. Documente esses comandos em arquivos de instruções como `AGENTS.md` ou skills, para que o agente saiba o que executar. Habilite o LSP quando seu projeto se beneficiar de feedback adicional do servidor de linguagem. * * * [Configuração](https://opencode.ai/docs/pt-br/lsp/#configura%C3%A7%C3%A3o) --------------------------------------------------------------------------- Você pode habilitar e personalizar os servidores LSP através da seção `lsp` na sua configuração do opencode. Para habilitar todos os servidores LSP integrados, defina `lsp` como `true`. { "$schema": "https://opencode.ai/config.json", "lsp": true} Use um objeto para manter os servidores integrados habilitados enquanto configura substituições ou servidores personalizados. { "$schema": "https://opencode.ai/config.json", "lsp": {}} Cada servidor LSP suporta o seguinte: | Propriedade | Tipo | Descrição | | --- | --- | --- | | `disabled` | boolean | Defina como `true` para desabilitar o servidor LSP | | `command` | string\[\] | O comando para iniciar o servidor LSP | | `extensions` | string\[\] | Extensões de arquivo que este servidor LSP deve manipular | | `env` | object | Variáveis de ambiente a serem definidas ao iniciar o servidor | | `initialization` | object | Opções de inicialização a serem enviadas ao servidor LSP | Vamos ver alguns exemplos. * * * ### [Variáveis de ambiente](https://opencode.ai/docs/pt-br/lsp/#vari%C3%A1veis-de-ambiente) Use a propriedade `env` para definir variáveis de ambiente ao iniciar o servidor LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "env": { "RUST_LOG": "debug" } } }} * * * ### [Opções de inicialização](https://opencode.ai/docs/pt-br/lsp/#op%C3%A7%C3%B5es-de-inicializa%C3%A7%C3%A3o) Use a propriedade `initialization` para passar opções de inicialização ao servidor LSP. Estas são configurações específicas do servidor enviadas durante a solicitação `initialize` do LSP: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "initialization": { "preferences": { "importModuleSpecifierPreference": "relative" } } } }} * * * ### [Desabilitando servidores LSP](https://opencode.ai/docs/pt-br/lsp/#desabilitando-servidores-lsp) Se `lsp` for omitido, todos os servidores LSP ficam desabilitados. Para desabilitar todos os servidores LSP depois que outra configuração os habilitou, defina `lsp` como `false`: { "$schema": "https://opencode.ai/config.json", "lsp": false} Para desabilitar um servidor LSP **específico**, defina `disabled` como `true`: { "$schema": "https://opencode.ai/config.json", "lsp": { "typescript": { "disabled": true } }} * * * ### [Servidores LSP personalizados](https://opencode.ai/docs/pt-br/lsp/#servidores-lsp-personalizados) Você pode adicionar servidores LSP personalizados especificando o comando e as extensões de arquivo: { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } }} * * * [Informações Adicionais](https://opencode.ai/docs/pt-br/lsp/#informa%C3%A7%C3%B5es-adicionais) ----------------------------------------------------------------------------------------------- ### [PHP Intelephense](https://opencode.ai/docs/pt-br/lsp/#php-intelephense) PHP Intelephense oferece recursos premium através de uma chave de licença. Você pode fornecer uma chave de licença colocando (apenas) a chave em um arquivo de texto em: * No macOS/Linux: `$HOME/intelephense/license.txt` * No Windows: `%USERPROFILE%/intelephense/license.txt` O arquivo deve conter apenas a chave de licença sem conteúdo adicional. --- # القواعد | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/rules/#_top) القواعد ======= اضبط تعليمات مخصصة لـ opencode. يمكنك تزويد opencode بتعليمات مخصصة عبر إنشاء ملف `AGENTS.md`. هذا مشابه لقواعد Cursor. يحتوي هذا الملف على تعليمات تُضاف إلى سياق نموذج اللغة (LLM) لتخصيص سلوكه لمشروعك المحدد. * * * [التهيئة](https://opencode.ai/docs/ar/rules/#%D8%A7%D9%84%D8%AA%D9%87%D9%8A%D8%A6%D8%A9) ----------------------------------------------------------------------------------------- لإنشاء ملف `AGENTS.md` جديد، يمكنك تشغيل الأمر `/init` في opencode. سيقوم ذلك بفحص مشروعك وكل محتوياته لفهم طبيعة المشروع وتوليد ملف `AGENTS.md` بناءً على ذلك. يساعد هذا opencode على التنقّل داخل المشروع بشكل أفضل. إذا كان لديك ملف `AGENTS.md` موجود بالفعل، فسيحاول هذا إضافة محتوى إليه. * * * [مثال](https://opencode.ai/docs/ar/rules/#%D9%85%D8%AB%D8%A7%D9%84) -------------------------------------------------------------------- يمكنك أيضًا إنشاء هذا الملف يدويًا. إليك مثالًا على بعض الأمور التي يمكنك وضعها في ملف `AGENTS.md`. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` نضيف هنا تعليمات خاصة بالمشروع، وسيتم مشاركتها عبر فريقك. * * * [الأنواع](https://opencode.ai/docs/ar/rules/#%D8%A7%D9%84%D8%A3%D9%86%D9%88%D8%A7%D8%B9) ----------------------------------------------------------------------------------------- يدعم opencode أيضًا قراءة ملف `AGENTS.md` من مواقع متعددة، ولكل موقع غرض مختلف. ### [المشروع](https://opencode.ai/docs/ar/rules/#%D8%A7%D9%84%D9%85%D8%B4%D8%B1%D9%88%D8%B9) ضع ملف `AGENTS.md` في جذر مشروعك للقواعد الخاصة بالمشروع. لا تُطبَّق هذه القواعد إلا عند العمل داخل هذا المجلد أو مجلداته الفرعية. ### [عام](https://opencode.ai/docs/ar/rules/#%D8%B9%D8%A7%D9%85) يمكنك أيضًا وضع قواعد عامة في ملف `~/.config/opencode/AGENTS.md`. تُطبَّق هذه القواعد على جميع جلسات opencode. وبما أن هذا الملف لا يتم عمل commit له إلى Git ولا تتم مشاركته مع فريقك، نوصي باستخدامه لتحديد أي قواعد شخصية يجب أن يلتزم بها نموذج اللغة. ### [التوافق مع Claude Code](https://opencode.ai/docs/ar/rules/#%D8%A7%D9%84%D8%AA%D9%88%D8%A7%D9%81%D9%82-%D9%85%D8%B9-claude-code) للمستخدمين الذين ينتقلون من Claude Code، يدعم OpenCode اصطلاحات ملفات Claude Code كبدائل احتياطية: * **قواعد المشروع**: `CLAUDE.md` في دليل مشروعك (يُستخدم إذا لم يوجد `AGENTS.md`) * **قواعد عامة**: `~/.claude/CLAUDE.md` (يُستخدم إذا لم يوجد `~/.config/opencode/AGENTS.md`) * **المهارات**: `~/.claude/skills/` — راجع [مهارات الوكيل](https://opencode.ai/docs/skills/) للتفاصيل لإيقاف التوافق مع Claude Code، عيّن أحد متغيرات البيئة التالية: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [الأولوية](https://opencode.ai/docs/ar/rules/#%D8%A7%D9%84%D8%A3%D9%88%D9%84%D9%88%D9%8A%D8%A9) ------------------------------------------------------------------------------------------------ عند بدء opencode، يبحث عن ملفات القواعد بهذا الترتيب: 1. **ملفات محلية** عبر التنقّل صعودًا من الدليل الحالي (`AGENTS.md`, `CLAUDE.md`) 2. **ملف عام** في `~/.config/opencode/AGENTS.md` 3. **ملف Claude Code** في `~/.claude/CLAUDE.md` (ما لم يتم تعطيله) يتم اعتماد أول ملف مطابق ضمن كل فئة. على سبيل المثال، إذا كان لديك كل من `AGENTS.md` و`CLAUDE.md` فسيتم استخدام `AGENTS.md` فقط. وبالمثل، تكون الأولوية لملف `~/.config/opencode/AGENTS.md` على `~/.claude/CLAUDE.md`. * * * [تعليمات مخصصة](https://opencode.ai/docs/ar/rules/#%D8%AA%D8%B9%D9%84%D9%8A%D9%85%D8%A7%D8%AA-%D9%85%D8%AE%D8%B5%D8%B5%D8%A9) ------------------------------------------------------------------------------------------------------------------------------ يمكنك تحديد ملفات تعليمات مخصصة في `opencode.json` أو في الملف العام `~/.config/opencode/opencode.json`. يتيح ذلك لك ولفريقك إعادة استخدام القواعد الموجودة بدلًا من تكرارها داخل AGENTS.md. مثال: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} يمكنك أيضًا استخدام عناوين URL بعيدة لتحميل التعليمات من الويب. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} يتم جلب التعليمات البعيدة بمهلة قدرها 5 ثوانٍ. تُدمَج جميع ملفات التعليمات مع ملفات `AGENTS.md` لديك. * * * [الإشارة إلى ملفات خارجية](https://opencode.ai/docs/ar/rules/#%D8%A7%D9%84%D8%A5%D8%B4%D8%A7%D8%B1%D8%A9-%D8%A5%D9%84%D9%89-%D9%85%D9%84%D9%81%D8%A7%D8%AA-%D8%AE%D8%A7%D8%B1%D8%AC%D9%8A%D8%A9) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- على الرغم من أن opencode لا يقوم تلقائيًا بتحليل مراجع الملفات داخل `AGENTS.md`، يمكنك تحقيق وظيفة مشابهة بطريقتين: ### [استخدام opencode.json](https://opencode.ai/docs/ar/rules/#%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85-opencodejson) النهج الموصى به هو استخدام الحقل `instructions` في `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [تعليمات يدوية في AGENTS.md](https://opencode.ai/docs/ar/rules/#%D8%AA%D8%B9%D9%84%D9%8A%D9%85%D8%A7%D8%AA-%D9%8A%D8%AF%D9%88%D9%8A%D8%A9-%D9%81%D9%8A-agentsmd) يمكنك تعليم opencode قراءة ملفات خارجية عبر تقديم تعليمات صريحة داخل `AGENTS.md`. إليك مثالًا عمليًا: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. يتيح لك هذا النهج ما يلي: * إنشاء ملفات قواعد معيارية قابلة لإعادة الاستخدام * مشاركة القواعد عبر المشاريع باستخدام symlinks أو git submodules * إبقاء AGENTS.md موجزًا مع الإشارة إلى إرشادات تفصيلية * ضمان أن opencode يحمّل الملفات فقط عند الحاجة للمهمة المحددة --- # Regole | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/rules/#_top) Regole ====== Imposta istruzioni personalizzate per opencode. Puoi fornire istruzioni personalizzate a opencode creando un file `AGENTS.md`. E’ simile alle regole di Cursor. Contiene istruzioni che verranno incluse nel contesto dell’LLM per personalizzarne il comportamento per il tuo progetto. * * * [Inizializza](https://opencode.ai/docs/it/rules/#inizializza) -------------------------------------------------------------- Per creare un nuovo file `AGENTS.md`, puoi eseguire il comando `/init` in opencode. Questo scansiona il progetto e tutti i suoi contenuti per capire di cosa si tratta e generare un file `AGENTS.md`. Questo aiuta opencode a orientarsi meglio nel progetto. Se hai gia’ un file `AGENTS.md` esistente, cerchera’ di aggiungervi contenuti. * * * [Esempio](https://opencode.ai/docs/it/rules/#esempio) ------------------------------------------------------ Puoi anche creare questo file manualmente. Ecco un esempio di alcune cose che puoi inserire in un file `AGENTS.md`. # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` Qui stiamo aggiungendo istruzioni specifiche del progetto e saranno condivise con il tuo team. * * * [Tipi](https://opencode.ai/docs/it/rules/#tipi) ------------------------------------------------ opencode supporta anche la lettura del file `AGENTS.md` da piu’ posizioni, e questo serve a scopi diversi. ### [Progetto](https://opencode.ai/docs/it/rules/#progetto) Metti un `AGENTS.md` nella root del progetto per regole specifiche del progetto. Si applicano solo quando stai lavorando in questa directory o nelle sue sottodirectory. ### [Globale](https://opencode.ai/docs/it/rules/#globale) Puoi anche avere regole globali in un file `~/.config/opencode/AGENTS.md`. Queste si applicano a tutte le sessioni di opencode. Dato che questo non viene committato in Git o condiviso con il team, consigliamo di usarlo per specificare regole personali che l’LLM deve seguire. ### [Compatibilita Claude Code](https://opencode.ai/docs/it/rules/#compatibilita-claude-code) Per gli utenti che migrano da Claude Code, OpenCode supporta come fallback le convenzioni di file di Claude Code: * **Regole di progetto**: `CLAUDE.md` nella directory del progetto (usato se non esiste `AGENTS.md`) * **Regole globali**: `~/.claude/CLAUDE.md` (usato se non esiste `~/.config/opencode/AGENTS.md`) * **Skill**: `~/.claude/skills/` — vedi [Skill agente](https://opencode.ai/docs/skills/) per i dettagli Per disabilitare la compatibilita’ con Claude Code, imposta una di queste variabili d’ambiente: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [Priorita](https://opencode.ai/docs/it/rules/#priorita) -------------------------------------------------------- Quando opencode si avvia, cerca i file di regole in questo ordine: 1. **File locali** risalendo dalla directory corrente (`AGENTS.md`, `CLAUDE.md`) 2. **File globale** in `~/.config/opencode/AGENTS.md` 3. **File Claude Code** in `~/.claude/CLAUDE.md` (se non disabilitato) In ogni categoria vince il primo file corrispondente. Per esempio, se hai sia `AGENTS.md` sia `CLAUDE.md`, viene usato solo `AGENTS.md`. Allo stesso modo, `~/.config/opencode/AGENTS.md` ha priorita’ su `~/.claude/CLAUDE.md`. * * * [Istruzioni personalizzate](https://opencode.ai/docs/it/rules/#istruzioni-personalizzate) ------------------------------------------------------------------------------------------ Puoi specificare file di istruzioni personalizzati nel tuo `opencode.json` o nel globale `~/.config/opencode/opencode.json`. Questo permette a te e al tuo team di riusare regole esistenti invece di doverle duplicare in AGENTS.md. Esempio: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} Puoi anche usare URL remoti per caricare istruzioni dal web. { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} Le istruzioni remote vengono recuperate con un timeout di 5 secondi. Tutti i file di istruzioni vengono combinati con i tuoi file `AGENTS.md`. * * * [Riferisci file esterni](https://opencode.ai/docs/it/rules/#riferisci-file-esterni) ------------------------------------------------------------------------------------ Anche se opencode non interpreta automaticamente i riferimenti a file in `AGENTS.md`, puoi ottenere una funzionalita’ simile in due modi: ### [Usa opencode.json](https://opencode.ai/docs/it/rules/#usa-opencodejson) L’approccio consigliato e’ usare il campo `instructions` in `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [Istruzioni manuali in AGENTS.md](https://opencode.ai/docs/it/rules/#istruzioni-manuali-in-agentsmd) Puoi insegnare a opencode a leggere file esterni fornendo istruzioni esplicite nel tuo `AGENTS.md`. Ecco un esempio pratico: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. Questo approccio ti permette di: * Crea file di regole modulari e riutilizzabili * Condividi regole tra progetti con symlink o submodule Git * Mantieni AGENTS.md conciso riferendoti a linee guida dettagliate * Assicurati che opencode carichi file solo quando servono per il task specifico --- # ルール | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/rules/#_top) ルール === OpenCode のカスタム命令を設定します。 `AGENTS.md` ファイルを作成することで、OpenCode にカスタム命令を提供できます。これは Cursor のルールと似ています。これには、特定のプロジェクトに合わせて LLM の動作をカスタマイズするために LLM のコンテキストに含まれる命令が含まれています。 * * * [初期化](https://opencode.ai/docs/ja/rules/#%E5%88%9D%E6%9C%9F%E5%8C%96) ---------------------------------------------------------------------- 新しい `AGENTS.md` ファイルを作成するには、OpenCode で `/init` コマンドを実行します。 `AGENTS.md` ファイルが生成されます。これは、OpenCode がプロジェクトをより適切にナビゲートするのに役立ちます。 既存の `AGENTS.md` ファイルがある場合、これはそれに追加しようとします。 * * * [例](https://opencode.ai/docs/ja/rules/#%E4%BE%8B) -------------------------------------------------- このファイルを手動で作成することもできます。以下は、`AGENTS.md` ファイルに含めることができるいくつかの例です。 # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` ここにプロジェクト固有の手順を追加します。これはチーム全体で共有されます。 * * * [種類](https://opencode.ai/docs/ja/rules/#%E7%A8%AE%E9%A1%9E) ------------------------------------------------------------ OpenCode は、複数の場所からの `AGENTS.md` ファイルの読み取りもサポートしています。そして、これはさまざまな目的に役立ちます。 ### [プロジェクト](https://opencode.ai/docs/ja/rules/#%E3%83%97%E3%83%AD%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88) プロジェクト固有のルールのために、プロジェクトルートに `AGENTS.md` を配置します。これらは、このディレクトリまたはそのサブディレクトリで作業している場合にのみ適用されます。 ### [グローバル](https://opencode.ai/docs/ja/rules/#%E3%82%B0%E3%83%AD%E3%83%BC%E3%83%90%E3%83%AB) `~/.config/opencode/AGENTS.md` ファイルにグローバルルールを含めることもできます。これは、すべての OpenCode セッションに適用されます。 これは Git にコミットされておらず、チームと共有されていないため、LLM が従うべき個人ルールを指定するためにこれを使用することをお勧めします。 ### [Claude Code 互換性](https://opencode.ai/docs/ja/rules/#claude-code-%E4%BA%92%E6%8F%9B%E6%80%A7) Claude Code から移行するユーザーのために、OpenCode はフォールバックとして Claude Code のファイル規則をサポートしています。 * **プロジェクトルール**: プロジェクトディレクトリ内の `CLAUDE.md` (`AGENTS.md` が存在しない場合に使用されます) * **グローバルルール**: `~/.claude/CLAUDE.md` (`~/.config/opencode/AGENTS.md` が存在しない場合に使用) * **スキル**: `~/.claude/skills/` — 詳細については、[エージェントスキル](https://opencode.ai/docs/skills/) を参照してください。 Claude Code の互換性を無効にするには、次の環境変数のいずれかを設定します。 export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [優先順位](https://opencode.ai/docs/ja/rules/#%E5%84%AA%E5%85%88%E9%A0%86%E4%BD%8D) -------------------------------------------------------------------------------- OpenCode が開始されると、次の順序でルールファイルが検索されます。 1. **ローカルファイル** (現在のディレクトリから上に移動) (`AGENTS.md`、`CLAUDE.md`) 2. **グローバルファイル** (`~/.config/opencode/AGENTS.md`) 3. **Claude Code ファイル** (`~/.claude/CLAUDE.md` にあります) (無効になっていない限り) 最初に一致したファイルが各カテゴリで優先されます。たとえば、`AGENTS.md` と `CLAUDE.md` の両方がある場合、`AGENTS.md` のみが使用されます。同様に、`~/.config/opencode/AGENTS.md` は `~/.claude/CLAUDE.md` よりも優先されます。 * * * [カスタム指示](https://opencode.ai/docs/ja/rules/#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E6%8C%87%E7%A4%BA) ---------------------------------------------------------------------------------------------------- `opencode.json` またはグローバル `~/.config/opencode/opencode.json` でカスタム命令ファイルを指定できます。これにより、あなたとあなたのチームは、既存のルールを AGENTS.md に複製するのではなく、再利用することができます。 例: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} リモート URL を使用して Web から命令をロードすることもできます。 { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} リモート命令は 5 秒のタイムアウトでフェッチされます。 すべての命令ファイルは `AGENTS.md` ファイルと結合されます。 * * * [外部ファイル参照](https://opencode.ai/docs/ja/rules/#%E5%A4%96%E9%83%A8%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%8F%82%E7%85%A7) ------------------------------------------------------------------------------------------------------------------------ OpenCode は `AGENTS.md` のファイル参照を自動的に解析しませんが、次の 2 つの方法で同様の機能を実現できます。 ### [`opencode.json` の使用](https://opencode.ai/docs/ja/rules/#opencodejson-%E3%81%AE%E4%BD%BF%E7%94%A8) 推奨されるアプローチは、`instructions` の `opencode.json` フィールドを使用することです。 { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [AGENTS.md の手動指示](https://opencode.ai/docs/ja/rules/#agentsmd-%E3%81%AE%E6%89%8B%E5%8B%95%E6%8C%87%E7%A4%BA) `AGENTS.md` で明示的な命令を指定することで、OpenCode に外部ファイルを読み取るように教えることができます。実際の例を次に示します。 # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. このアプローチにより、次のことが可能になります。 * モジュール式の再利用可能なルールファイルを作成する * シンボリックリンクまたは git サブモジュールを介してプロジェクト間でルールを共有する * 詳細なガイドラインを参照しながら、AGENTS.md を簡潔に保ちます * OpenCode が特定のタスクに必要な場合にのみファイルをロードするようにする --- # กฎ | OpenCode [Skip to content](https://opencode.ai/docs/th/rules/#_top) กฎ == ตั้งค่าคำแนะนำที่กำหนดเองสำหรับ opencode คุณสามารถให้คำแนะนำที่กำหนดเองแก่ opencode ได้โดยการสร้างไฟล์ `AGENTS.md` ซึ่งคล้ายกับกฎของเคอร์เซอร์ ประกอบด้วยคำแนะนำที่จะรวมอยู่ในบริบทของ LLM เพื่อปรับแต่งลักษณะการทำงานสำหรับโครงการเฉพาะของคุณ * * * [เริ่มต้น](https://opencode.ai/docs/th/rules/#%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%95%E0%B9%89%E0%B8%99) ------------------------------------------------------------------------------------------------------------------------ หากต้องการสร้างไฟล์ `AGENTS.md` ใหม่ คุณสามารถเรียกใช้คำสั่ง `/init` ใน opencode การดำเนินการนี้จะสแกนโปรเจ็กต์ของคุณและเนื้อหาทั้งหมดเพื่อทำความเข้าใจว่าโปรเจ็กต์เกี่ยวกับอะไร และสร้างไฟล์ `AGENTS.md` ด้วย สิ่งนี้ช่วยให้ opencode นำทางโครงการได้ดีขึ้น หากคุณมีไฟล์ `AGENTS.md` อยู่แล้ว ระบบจะพยายามเพิ่มไฟล์ดังกล่าว * * * [ตัวอย่าง](https://opencode.ai/docs/th/rules/#%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87) ------------------------------------------------------------------------------------------------------------------------ คุณสามารถสร้างไฟล์นี้ด้วยตนเองได้ นี่คือตัวอย่างบางสิ่งที่คุณสามารถใส่ลงในไฟล์ `AGENTS.md` # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` เรากำลังเพิ่มคำแนะนำเฉพาะโครงการที่นี่ และจะมีการแชร์กับทีมของคุณ * * * [ประเภท](https://opencode.ai/docs/th/rules/#%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B9%80%E0%B8%A0%E0%B8%97) ---------------------------------------------------------------------------------------------------- opencode ยังรองรับการอ่านไฟล์ `AGENTS.md` จากหลาย ๆ ที่ และสิ่งนี้มีจุดประสงค์ที่แตกต่างกัน ### [โครงการ](https://opencode.ai/docs/th/rules/#%E0%B9%82%E0%B8%84%E0%B8%A3%E0%B8%87%E0%B8%81%E0%B8%B2%E0%B8%A3) วาง `AGENTS.md` ในรูทโปรเจ็กต์ของคุณสำหรับกฎเฉพาะโปรเจ็กต์ สิ่งเหล่านี้ใช้เฉพาะเมื่อคุณทำงานในไดเร็กทอรีนี้หรือไดเร็กทอรีย่อยเท่านั้น ### [ทั่วโลก](https://opencode.ai/docs/th/rules/#%E0%B8%97%E0%B8%B1%E0%B9%88%E0%B8%A7%E0%B9%82%E0%B8%A5%E0%B8%81) คุณยังสามารถมีกฎสากลในไฟล์ `~/.config/opencode/AGENTS.md` สิ่งนี้จะนำไปใช้กับเซสชัน opencode ทั้งหมด เนื่องจากสิ่งนี้ไม่ได้ผูกมัดกับ Git หรือแชร์กับทีมของคุณ เราขอแนะนำให้ใช้สิ่งนี้เพื่อระบุกฎส่วนบุคคลที่ LLM ควรปฏิบัติตาม ### [ความเข้ากันได้กับ Claude Code](https://opencode.ai/docs/th/rules/#%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B8%81%E0%B8%B1%E0%B8%99%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%81%E0%B8%B1%E0%B8%9A-claude-code) สำหรับผู้ใช้ที่ย้ายจาก Claude Code นั้น OpenCode รองรับรูปแบบไฟล์ของ Claude Code เป็นทางเลือก: * **กฎของโครงการ**: `CLAUDE.md` ในไดเรกทอรีโครงการของคุณ (ใช้หากไม่มี `AGENTS.md`) * **กฎสากล**: `~/.claude/CLAUDE.md` (ใช้หากไม่มี `~/.config/opencode/AGENTS.md`) * **ทักษะ**: `~/.claude/skills/` — ดูรายละเอียด [ทักษะตัวแทน](https://opencode.ai/docs/skills/) หากต้องการปิดใช้งานความเข้ากันได้ของ Claude Code ให้ตั้งค่าหนึ่งในตัวแปรสภาพแวดล้อมเหล่านี้: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [ลำดับความสำคัญ](https://opencode.ai/docs/th/rules/#%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) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ เมื่อ opencode เริ่มต้นขึ้น มันจะค้นหาไฟล์กฎตามลำดับนี้: 1. **ไฟล์ในเครื่อง** โดยการสำรวจจากไดเรกทอรีปัจจุบัน (`AGENTS.md`, `CLAUDE.md`) 2. **ไฟล์ทั่วโลก** ที่ `~/.config/opencode/AGENTS.md` 3. **Claude Code files** ที่ `~/.claude/CLAUDE.md` (ยกเว้นปิดการใช้งาน) ไฟล์ที่ตรงกันไฟล์แรกจะชนะในแต่ละหมวดหมู่ ตัวอย่างเช่น หากคุณมีทั้ง `AGENTS.md` และ `CLAUDE.md` ระบบจะใช้เฉพาะ `AGENTS.md` ในทำนองเดียวกัน `~/.config/opencode/AGENTS.md` จะมีความสำคัญมากกว่า `~/.claude/CLAUDE.md` * * * [คำแนะนำที่กำหนดเอง](https://opencode.ai/docs/th/rules/#%E0%B8%84%E0%B8%B3%E0%B9%81%E0%B8%99%E0%B8%B0%E0%B8%99%E0%B8%B3%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.json` หรือ `~/.config/opencode/opencode.json` ทั่วโลก สิ่งนี้ช่วยให้คุณและทีมของคุณสามารถนำกฎที่มีอยู่กลับมาใช้ใหม่ได้ แทนที่จะต้องทำซ้ำกฎเหล่านั้นกับ AGENTS.md ตัวอย่าง: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} คุณยังสามารถใช้ URL ระยะไกลเพื่อโหลดคำแนะนำจากเว็บได้ { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} คำแนะนำระยะไกลจะถูกดึงออกมาโดยหมดเวลา 5 วินาที ไฟล์คำสั่งทั้งหมดจะรวมกับไฟล์ `AGENTS.md` ของคุณ * * * [การอ้างอิงไฟล์ภายนอก](https://opencode.ai/docs/th/rules/#%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%E0%B8%A0%E0%B8%B2%E0%B8%A2%E0%B8%99%E0%B8%AD%E0%B8%81) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ แม้ว่า opencode จะไม่แยกวิเคราะห์การอ้างอิงไฟล์ใน `AGENTS.md` โดยอัตโนมัติ แต่คุณสามารถใช้ฟังก์ชันที่คล้ายกันได้สองวิธี: ### [ใช้ opencode.json](https://opencode.ai/docs/th/rules/#%E0%B9%83%E0%B8%8A%E0%B9%89-opencodejson) แนวทางที่แนะนำคือการใช้ฟิลด์ `instructions` ใน `opencode.json`: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [คำแนะนำแบบแมนนวลใน AGENTS.md](https://opencode.ai/docs/th/rules/#%E0%B8%84%E0%B8%B3%E0%B9%81%E0%B8%99%E0%B8%B0%E0%B8%99%E0%B8%B3%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B9%81%E0%B8%A1%E0%B8%99%E0%B8%99%E0%B8%A7%E0%B8%A5%E0%B9%83%E0%B8%99-agentsmd) คุณสามารถสอนให้ opencode อ่านไฟล์ภายนอกได้โดยการให้คำแนะนำที่ชัดเจนใน `AGENTS.md` ของคุณ นี่เป็นตัวอย่างที่เป็นประโยชน์: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. แนวทางนี้ช่วยให้คุณ: * สร้างไฟล์กฎแบบโมดูลาร์ที่สามารถนำมาใช้ซ้ำได้ * แชร์กฎระหว่างโปรเจ็กต์ผ่าน symlink หรือโมดูลย่อย git * เขียน AGENTS.md ให้กระชับโดยอ้างอิงหลักเกณฑ์โดยละเอียด * ตรวจสอบให้แน่ใจว่า opencode จะโหลดไฟล์เมื่อจำเป็นสำหรับงานเฉพาะเท่านั้น --- # 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/ko/themes/#_top) 테마 == 내장 테마를 선택하거나 자신만의 테마를 정의하세요. OpenCode를 사용하면 여러 내장 테마 중 하나에서 선택할 수 있으며 terminal 테마에 적응하는 테마를 사용하거나 사용자 정의 테마를 정의 할 수 있습니다. 기본적으로 OpenCode는 자체 `opencode` 테마를 사용합니다. * * * [터미널 요구 사항](https://opencode.ai/docs/ko/themes/#%ED%84%B0%EB%AF%B8%EB%84%90-%EC%9A%94%EA%B5%AC-%EC%82%AC%ED%95%AD) ------------------------------------------------------------------------------------------------------------------- 테마가 전체 색상 팔레트로 올바르게 표시되려면 터미널이 **truecolor** (24비트 색상)를 지원해야 합니다. 대부분의 최신 터미널은 기본적으로 이를 지원하지만, 활성화해야 할 수도 있습니다: * **지원 확인**: `echo $COLORTERM` 실행 - `truecolor` 또는 `24bit`가 출력되어야 합니다. * **truecolor 활성화**: 셸 프로필에서 환경 변수 `COLORTERM=truecolor`를 설정하십시오. * **터미널 호환성**: 터미널 에뮬레이터가 24비트 색상을 지원하는지 확인하십시오 (iTerm2, Alacritty, Kitty, Windows Terminal 및 최신 버전의 GNOME Terminal 등 대부분의 최신 터미널이 지원함). truecolor 지원이 없으면 테마가 감소된 색상 정확도로 표시되거나 가장 가까운 256색 근사치로 대체될 수 있습니다. * * * [내장 테마](https://opencode.ai/docs/ko/themes/#%EB%82%B4%EC%9E%A5-%ED%85%8C%EB%A7%88) ----------------------------------------------------------------------------------- OpenCode는 여러 내장 테마와 함께 제공됩니다. | 이름 | 설명 | | --- | --- | | `system` | terminal 배경 색상에 맞춰 자동으로 조정됨 | | `tokyonight` | [Tokyonight](https://github.com/folke/tokyonight.nvim)
테마 기반 | | `everforest` | [Everforest](https://github.com/sainnhe/everforest)
테마 기반 | | `ayu` | [Ayu](https://github.com/ayu-theme)
다크 테마 기반 | | `catppuccin` | [Catppuccin](https://github.com/catppuccin)
테마 기반 | | `catppuccin-macchiato` | [Catppuccin](https://github.com/catppuccin)
테마 기반 | | `gruvbox` | [Gruvbox](https://github.com/morhetz/gruvbox)
테마 기반 | | `kanagawa` | [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
테마 기반 | | `nord` | [Nord](https://github.com/nordtheme/nord)
테마 기반 | | `matrix` | 검은 배경에 녹색 텍스트의 해커 스타일 테마 | | `one-dark` | [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark 테마 기반 | 그리고 더, 우리는 끊임없이 새로운 테마를 추가하고 있습니다. * * * [시스템 테마](https://opencode.ai/docs/ko/themes/#%EC%8B%9C%EC%8A%A4%ED%85%9C-%ED%85%8C%EB%A7%88) --------------------------------------------------------------------------------------------- `system` 테마는 터미널의 색상 스키마에 자동으로 적응하도록 설계되었습니다. 고정 색상을 사용하는 기존 테마와 달리, system 테마는: * **그레이스케일 생성**: 터미널의 배경 색상을 기반으로 사용자 정의 그레이스케일을 생성하여 최적의 대비를 보장합니다. * **ANSI 색상 사용**: 구문 강조 및 UI 요소에 표준 ANSI 색상(0-15)을 활용하여 터미널의 색상 팔레트를 존중합니다. * **터미널 기본값 유지**: 텍스트 및 배경 색상에 `none`을 사용하여 터미널의 기본 모양을 유지합니다. 시스템 테마는 다음과 같은 사용자에게 적합합니다: * OpenCode가 터미널의 모양과 일치하기를 원하는 경우 * 사용자 정의 터미널 색상 스키마를 사용하는 경우 * 모든 터미널 애플리케이션에서 일관된 모양을 선호하는 경우 * * * [테마 사용](https://opencode.ai/docs/ko/themes/#%ED%85%8C%EB%A7%88-%EC%82%AC%EC%9A%A9) ----------------------------------------------------------------------------------- `/theme` 명령어로 테마 선택기를 불러와 테마를 선택할 수 있습니다. 또는 `tui.json`에서 지정할 수 있습니다. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [사용자 정의 테마](https://opencode.ai/docs/ko/themes/#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98-%ED%85%8C%EB%A7%88) ------------------------------------------------------------------------------------------------------------------- OpenCode는 사용자가 쉽게 테마를 만들고 사용자 정의할 수 있도록 유연한 JSON 기반 테마 시스템을 지원합니다. * * * ### [계층 구조](https://opencode.ai/docs/ko/themes/#%EA%B3%84%EC%B8%B5-%EA%B5%AC%EC%A1%B0) 테마는 다음 순서대로 여러 디렉토리에서 로드되며, 나중 디렉토리가 이전 디렉토리를 덮어씁니다: 1. **내장 테마 (Built-in themes)** - 바이너리에 내장되어 있습니다. 2. **사용자 설정 디렉토리 (User config directory)** - `~/.config/opencode/themes/*.json` 또는 `$XDG_CONFIG_HOME/opencode/themes/*.json`에 정의됩니다. 3. **프로젝트 루트 디렉토리 (Project root directory)** - `/.opencode/themes/*.json`에 정의됩니다. 4. **현재 작업 디렉토리 (Current working directory)** - `./.opencode/themes/*.json`에 정의됩니다. 여러 디렉토리에 같은 이름의 테마가 있는 경우, 더 높은 우선 순위를 가진 디렉토리의 테마가 사용됩니다. * * * ### [테마 만들기](https://opencode.ai/docs/ko/themes/#%ED%85%8C%EB%A7%88-%EB%A7%8C%EB%93%A4%EA%B8%B0) 사용자 정의 테마를 만들려면 테마 디렉토리 중 하나에 JSON 파일을 만듭니다. 사용자 전역 테마: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json 프로젝트별 테마: mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON 형식](https://opencode.ai/docs/ko/themes/#json-%ED%98%95%EC%8B%9D) 테마는 다음을 지원하는 유연한 JSON 형식을 사용합니다: * **Hex 색상**: `"#ffffff"` * **ANSI 색상**: `3` (0-255) * **색상 참조**: `"primary"` 또는 사용자 정의 정의 * **다크/라이트 변형**: `{"dark": "#000", "light": "#fff"}` * **색상 없음**: `"none"` - 터미널의 기본 색상 또는 투명 사용 * * * ### [색상 정의](https://opencode.ai/docs/ko/themes/#%EC%83%89%EC%83%81-%EC%A0%95%EC%9D%98) `defs` 섹션은 선택 사항이며 테마 내에서 참조할 수 있는 재사용 가능한 색상을 정의할 수 있습니다. * * * ### [터미널 기본값](https://opencode.ai/docs/ko/themes/#%ED%84%B0%EB%AF%B8%EB%84%90-%EA%B8%B0%EB%B3%B8%EA%B0%92) `"none"`이라는 특별한 값은 모든 색상에 대해 터미널의 기본 색상을 상속하는 데 사용할 수 있습니다. 이는 특히 터미널의 색상 스키마와 매끄럽게 어우러지는 테마를 만들 때 유용합니다: * `"text": "none"` - 터미널의 기본 전경색 사용 * `"background": "none"` - 터미널의 기본 배경색 사용 * * * ### [예제](https://opencode.ai/docs/ko/themes/#%EC%98%88%EC%A0%9C) 사용자 정의 테마의 예입니다: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Temaer | OpenCode [Gå til indhold](https://opencode.ai/docs/da/themes/#_top) Temaer ====== Velg et innebygd tema eller definer ditt eget. Med OpenCode kan du velge fra ett av flere innebygde temaer, bruge et tema som tilpasser seg terminaltemaet ditt, eller definere ditt eget tilpassede tema. Som standard bruger OpenCode vårt eget `opencode`\-tema. * * * [Terminalkrav](https://opencode.ai/docs/da/themes/#terminalkrav) ----------------------------------------------------------------- For at temaer skal vises riktig med fullfarvepalett, må terminalen din støtte **truecolor** (24-biters farver). De fleste moderne terminaler støtter dette som standard, men du må kanskje aktivere det: * **Tjek støtte**: Kjør `echo $COLORTERM` - den skal gi ut `truecolor` eller `24bit` * **Aktiver truecolor**: Sett miljøvariabelen `COLORTERM=truecolor` i shellprofilen din * **Terminalkompatibilitet**: Sørg for at terminalemulatoren din støtter 24-bits farver (de fleste moderne terminaler som iTerm2, Alacritty, Kitty, Windows Terminal og nyere versioner av GNOME Terminal gør det) Uden truecolor-støtte kan temaer vises med redusert farvenøjagtighed eller falde tilbage til nærmeste 256-farvers tilnærming. * * * [Indbyggede temaer](https://opencode.ai/docs/da/themes/#indbyggede-temaer) --------------------------------------------------------------------------- OpenCode kommer med flere innebygde temaer. | Navn | Beskrivelse | | --- | --- | | `system` | Tilpasser seg terminalens bakgrunnsfarve | | `tokyonight` | Basert på [Tokyonight](https://github.com/folke/tokyonight.nvim)
\-temaet | | `everforest` | Basert på [Everforest](https://github.com/sainnhe/everforest)
\-temaet | | `ayu` | Basert på [Ayu](https://github.com/ayu-theme)
mørke tema | | `catppuccin` | Basert på [Catppuccin](https://github.com/catppuccin)
\-temaet | | `catppuccin-macchiato` | Basert på [Catppuccin](https://github.com/catppuccin)
\-temaet | | `gruvbox` | Basert på [Gruvbox](https://github.com/morhetz/gruvbox)
\-temaet | | `kanagawa` | Basert på [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
\-temaet | | `nord` | Basert på [Nord](https://github.com/nordtheme/nord)
\-temaet | | `matrix` | Hacker-stil grønt på svart tema | | `one-dark` | Basert på [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Mørkt tema | Og mer, vi tilføjer stadig til nye temaer. * * * [Systemtema](https://opencode.ai/docs/da/themes/#systemtema) ------------------------------------------------------------- `system`\-temaet er designet for at automatisk tilpasse seg terminalens farvevalg. I motsetning til tradisjonelle temaer som bruger faste farver, er _system_\-temaet: * **Genererer gråskala**: Opreter en brugerdefineret gråskala basert på terminalens bakgrunnsfarve, og sikrer optimal kontrast. * **Bruger ANSI farver**: Bruger standard ANSI farver (0-15) for syntaksutheving og UI elementer, som respekterer terminalens farvepalett. * **Bevarer terminalens standardinnstillinger**: Bruger `none` for tekst- og bakgrunnsfarver for at opretholde terminalens opprinnelige utseende. Systemtemaet er for brugere som: * Vil at OpenCode skal matche terminalens utseende * Brug tilpassede terminalfarveskjemaer * Foretrekker et konsistent utseende på tvers av alle terminalapplikasjoner * * * [Brug et tema](https://opencode.ai/docs/da/themes/#brug-et-tema) ----------------------------------------------------------------- Du kan velge et tema ved at hente frem temavalg med kommandoen `/theme`. Eller du kan angive det i `tui.json`. { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [Brugerdefinerede temaer](https://opencode.ai/docs/da/themes/#brugerdefinerede-temaer) --------------------------------------------------------------------------------------- OpenCode støtter et fleksibelt JSON-basert temasystem som lar brugere enkelt lage og tilpasse temaer. * * * ### [Hierarki](https://opencode.ai/docs/da/themes/#hierarki) Temaer lastes inn fra flere kataloger i følgende rekkefølge der senere kataloger overstyrer tidligere: 1. **Innebygde temaer** - Disse er innebygd i binæren 2. **Brugerkonfigurasjonskatalog** - Definert i `~/.config/opencode/themes/*.json` eller `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **Prosjektrotkatalog** - Definert i `/.opencode/themes/*.json` 4. **Nuværende arbejdskatalog** - Definert i `./.opencode/themes/*.json` Hvis flere kataloger inneholder et tema med samme navn, vil temaet fra katalogen med høyere prioritet bli brugt. * * * ### [Oprettelse af et tema](https://opencode.ai/docs/da/themes/#oprettelse-af-et-tema) For at lage et brugerdefineret tema, lag en JSON-fil i en av temakatalogene. For brugeromfattende temaer: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json Og for prosjektspesifikke temaer. mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON-format](https://opencode.ai/docs/da/themes/#json-format) Temaer bruger et fleksibelt JSON-format med støtte for: * **Sekskantfarver**: `"#ffffff"` * **ANSI farver**: `3` (0-255) * **Farvereferanser**: `"primary"` eller egendefinerte definisjoner * **Mørke/lyse varianter**: `{"dark": "#000", "light": "#fff"}` * **Ingen farve**: `"none"` - Bruger terminalens standardfarve eller transparent * * * ### [Farvedefinitioner](https://opencode.ai/docs/da/themes/#farvedefinitioner) `defs`\-delen er valgfri, og den lar deg definere gjenbrugbare farver som kan refereres til i temaet. * * * ### [Terminalstandarder](https://opencode.ai/docs/da/themes/#terminalstandarder) Spesialverdien `"none"` kan bruges for hvilken som helst farve for at arve terminalens standardfarve. Dette er spesielt nyttig for at lage temaer som passer sømløst med terminalens farveskjema: * `"text": "none"` - Bruger terminalens standard forgrunnsfarve * `"background": "none"` - Bruger terminalens standard bakgrunnsfarve * * * ### [Eksempel](https://opencode.ai/docs/da/themes/#eksempel) Her er et eksempel på et brugerdefineret tema: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Modeller | OpenCode [Gå til indhold](https://opencode.ai/docs/da/models/#_top) Modeller ======== Konfiguration af en LLM udbyder og model. OpenCode bruger [AI SDK](https://ai-sdk.dev/) og [Models.dev](https://models.dev/) til at understøtte **75+ LLM udbydere** og det understøtter at køre lokale modeller. * * * [Udbydere](https://opencode.ai/docs/da/models/#udbydere) --------------------------------------------------------- De fleste populære udbydere er forudindlæst som standard. Hvis du har tilføjet legitimationsoplysningerne for en udbyder gennem kommandoen `/connect`, vil de være tilgængelige, når du starter OpenCode. Få mere at vide om [providers](https://opencode.ai/docs/providers) . * * * [Vælg en model](https://opencode.ai/docs/da/models/#v%C3%A6lg-en-model) ------------------------------------------------------------------------ Når du har konfigureret din udbyder, kan du vælge den ønskede model ved at indtaste: /models * * * [Anbefalede modeller](https://opencode.ai/docs/da/models/#anbefalede-modeller) ------------------------------------------------------------------------------- Der er mange modeller derude, og der kommer nye modeller hver uge. Der er dog kun få af dem, der er gode til både at generere kode og værktøjsopkald. Her er flere modeller, der fungerer godt med OpenCode, uden bestemt rækkefølge. (Dette er ikke en udtømmende liste og er heller ikke nødvendigvis opdateret): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4,5 * Claude Sonnet 4,5 * Minimax M2.1 * Gemini 3 Pro * * * [Indstil en standard](https://opencode.ai/docs/da/models/#indstil-en-standard) ------------------------------------------------------------------------------- For at indstille en af ​​disse som standardmodellen kan du indstille `model`\-nøglen i din OpenCode konfig. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Her er det fulde ID `provider_id/model_id`. For eksempel, hvis du bruger [OpenCode Zen](https://opencode.ai/docs/zen) , vil du bruge `opencode/gpt-5.1-codex` til GPT 5.1 Codex. Hvis du har konfigureret en [custom provider](https://opencode.ai/docs/providers#custom) , er `provider_id` nøglen fra `provider` delen af ​​din konfiguration, og `model_id` er nøglen fra `provider.models`. * * * [Konfiguration af modeller](https://opencode.ai/docs/da/models/#konfiguration-af-modeller) ------------------------------------------------------------------------------------------- Du kan konfigurere en models muligheder globalt gennem konfigurationen. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Her konfigurerer vi globale indstillinger for to indbyggede modeller: `gpt-5` når de tilgås via `openai` udbyderen og `claude-sonnet-4-20250514` når de tilgås via `anthropic` udbyderen. Den indbyggede udbyder og modelnavne kan findes på [Models.dev](https://models.dev/) . Du kan også konfigurere disse indstillinger for alle agenter, du bruger. Agentkonfigurationen tilsidesætter alle globale muligheder her. [Learn more](https://opencode.ai/docs/agents/#additional) . Du kan også definere brugerdefinerede varianter, der udvider de indbyggede. Varianter giver dig mulighed for at konfigurere forskellige indstillinger for den samme model uden at oprette duplikerede poster: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Varianter](https://opencode.ai/docs/da/models/#varianter) ----------------------------------------------------------- Mange modeller understøtter flere varianter med forskellige konfigurationer. OpenCode leveres med indbyggede standardvarianter til populære udbydere. ### [Indbyggede varianter](https://opencode.ai/docs/da/models/#indbyggede-varianter) OpenCode leveres med standardvarianter for mange udbydere: **Anthropic**: * `high` - Højt tænkende budget (standard) * `max` - Maksimalt tænkebudget **OpenAI**: Varierer efter model, men nogenlunde: * `none` - Ingen begrundelse * `minimal` - Minimal ræsonnement indsats * `low` - Lav ræsonnement indsats * `medium` - Middel ræsonnement indsats * `high` - Høj ræsonnement indsats * `xhigh` - Ekstra høj ræsonnement indsats **Google**: * `low` - Lavere effort/token budget * `high` - Højere effort/token budget ### [Brugerdefinerede varianter](https://opencode.ai/docs/da/models/#brugerdefinerede-varianter) Du kan tilsidesætte eksisterende varianter eller tilføje dine egne: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Skift varianter](https://opencode.ai/docs/da/models/#skift-varianter) Brug tastebindingen `variant_cycle` til hurtigt at skifte mellem varianter. [Learn more](https://opencode.ai/docs/keybinds) . * * * [Indlæsning af modeller](https://opencode.ai/docs/da/models/#indl%C3%A6sning-af-modeller) ------------------------------------------------------------------------------------------ Når OpenCode starter op, søger den efter modeller i følgende prioriterede rækkefølge: 1. Kommandolinjeflaget `--model` eller `-m`. Formatet er det samme som i konfigurationsfilen: `provider_id/model_id`. 2. Modellisten i OpenCode-konfigurationen. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} Formatet her er `provider/model`. 3. Den sidst brugte model. 4. Den første model med en intern prioritet. --- # Modelle | OpenCode [Zum Inhalt springen](https://opencode.ai/docs/de/models/#_top) Modelle ======= Konfigurieren eines LLM-Anbieters und -Modells. OpenCode verwendet [AI SDK](https://ai-sdk.dev/) und [Models.dev](https://models.dev/) zur Unterstützung von **75+ LLM-Anbietern** und unterstützt die Ausführung lokaler Modelle. * * * [Anbieter](https://opencode.ai/docs/de/models/#anbieter) --------------------------------------------------------- Die meisten gängigen Anbieter sind standardmäßig vorinstalliert. Wenn Sie die Anmeldeinformationen für einen Anbieter über den Befehl `/connect` hinzugefügt haben, sind diese verfügbar, wenn Sie OpenCode starten. Erfahren Sie mehr über [providers](https://opencode.ai/docs/providers) . * * * [Modell auswählen](https://opencode.ai/docs/de/models/#modell-ausw%C3%A4hlen) ------------------------------------------------------------------------------ Sobald Sie Ihren Anbieter konfiguriert haben, können Sie das gewünschte Modell auswählen, indem Sie Folgendes eingeben: /models * * * [Empfohlene Modelle](https://opencode.ai/docs/de/models/#empfohlene-modelle) ----------------------------------------------------------------------------- Es gibt viele Modelle da draußen und jede Woche kommen neue Modelle heraus. Allerdings gibt es nur wenige von ihnen, die sowohl gut darin sind, Code zu generieren als auch Tools aufzurufen. Hier sind mehrere Modelle, die gut mit OpenCode funktionieren, in keiner bestimmten Reihenfolge. (Dies ist weder eine vollständige noch eine unbedingt aktuelle Liste): * GPT 5.2 * GPT 5.1 Kodex * Claude Opus 4.5 * Claude Sonett 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [Standard festlegen](https://opencode.ai/docs/de/models/#standard-festlegen) ----------------------------------------------------------------------------- Um eines davon als Standardmodell festzulegen, können Sie den Schlüssel `model` in Ihrem festlegen OpenCode config. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Hier ist der vollständige ID `provider_id/model_id`. Wenn Sie beispielsweise [OpenCode Zen](https://opencode.ai/docs/zen) verwenden, würden Sie `opencode/gpt-5.1-codex` für GPT 5.1 Codex verwenden. Wenn Sie einen [custom provider](https://opencode.ai/docs/providers#custom) konfiguriert haben, ist `provider_id` der Schlüssel aus dem `provider`\-Teil Ihrer Konfiguration und `model_id` der Schlüssel aus `provider.models`. * * * [Modelle konfigurieren](https://opencode.ai/docs/de/models/#modelle-konfigurieren) ----------------------------------------------------------------------------------- Sie können die Optionen eines Modells global über die Konfiguration konfigurieren. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Hier konfigurieren wir globale Einstellungen für zwei integrierte Modelle: `gpt-5` bei Zugriff über den `openai`\-Anbieter und `claude-sonnet-4-20250514` bei Zugriff über den `anthropic`\-Anbieter. Die integrierten Anbieter- und Modellnamen finden Sie unter [Models.dev](https://models.dev/) . Sie können diese Optionen auch für alle von Ihnen verwendeten Agenten konfigurieren. Die Agentenkonfiguration beschreibt hier alle globalen Optionen. [Learn more](https://opencode.ai/docs/agents/#additional) . Sie können auch benutzerdefinierte Varianten definieren, die integrierte Varianten erweitern. Mit Varianten können Sie unterschiedliche Einstellungen für dasselbe Modell konfigurieren, ohne doppelte Einträge zu erstellen: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Varianten](https://opencode.ai/docs/de/models/#varianten) ----------------------------------------------------------- Viele Modelle unterstützen mehrere Varianten mit unterschiedlichen Konfigurationen. OpenCode wird mit integrierten Standardvarianten für beliebte Anbieter ausgeliefert. ### [Integrierte Varianten](https://opencode.ai/docs/de/models/#integrierte-varianten) OpenCode wird für viele Anbieter mit Standardvarianten ausgeliefert: **Anthropic**: * `high` – Budget für hohes Denken (Standard) * `max` – Maximales Denkbudget **OpenAI**: Variiert je nach Modell, aber ungefähr: * `none` – Keine Begründung * `minimal` – Minimaler Argumentationsaufwand * `low` – Geringer Denkaufwand * `medium` – Mittlerer Denkaufwand * `high` – Hoher Denkaufwand * `xhigh` – Extra hoher Argumentationsaufwand **Google**: * `low` – Beliebtestes effort/token-Budget * `high` – Höheres effort/token-Budget ### [Benutzerdefinierte Varianten](https://opencode.ai/docs/de/models/#benutzerdefinierte-varianten) Sie können vorhandene Varianten überschreiben oder eigene hinzufügen: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Varianten durchwechseln](https://opencode.ai/docs/de/models/#varianten-durchwechseln) Verwenden Sie die Tastenkombination `variant_cycle`, um schnell zwischen Varianten zu wechseln. [Learn more](https://opencode.ai/docs/keybinds) . * * * [Laden von Modellen](https://opencode.ai/docs/de/models/#laden-von-modellen) ----------------------------------------------------------------------------- Wenn OpenCode startet, sucht es nach Modellen in der folgenden Prioritätsreihenfolge: 1. Das Befehlszeilenflag `--model` oder `-m`. Das Format ist das gleiche wie in der Konfigurationsdatei: `provider_id/model_id`. 2. Die Modellliste in der OpenCode-Konfiguration. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} Das Format hier ist `provider/model`. 3. Das zuletzt verwendete Modell. 4. Das erste Modell, das eine interne Priorität verwendet. --- # 모델 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/models/#_top) 모델 == LLM 공급자 및 모델 구성. opencode는 [AI SDK](https://ai-sdk.dev/) 및 [Models.dev](https://models.dev/) 를 사용하여 **75+ LLM 제공 업체**를 지원하며 로컬 모델을 실행합니다. * * * [공급자](https://opencode.ai/docs/ko/models/#%EA%B3%B5%EA%B8%89%EC%9E%90) ----------------------------------------------------------------------- 가장 인기 있는 공급자는 기본적으로 미리 로드되어 있습니다. `/connect` 명령을 통해 공급자를위한 자격 증명을 추가하면 opencode를 시작할 때 사용할 수 있습니다. 자세히 알아보기 [providers](https://opencode.ai/docs/providers) . * * * [모델 선택](https://opencode.ai/docs/ko/models/#%EB%AA%A8%EB%8D%B8-%EC%84%A0%ED%83%9D) ----------------------------------------------------------------------------------- 공급자를 구성하면 입력하여 원하는 모델을 선택할 수 있습니다. /models * * * [추천 모델](https://opencode.ai/docs/ko/models/#%EC%B6%94%EC%B2%9C-%EB%AA%A8%EB%8D%B8) ----------------------------------------------------------------------------------- 수많은 모델이 있으며, 매주 새로운 모델이 출시됩니다. 하지만 코드 작성과 도구 호출 모두에서 뛰어난 성능을 보이는 모델들이 있습니다. 특별한 순서는 없습니다. (이 목록은 전체 목록이 아니며 최신 상태가 아닐 수 있습니다): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * M2.1 * Gemini 3 Pro * * * [기본값 설정](https://opencode.ai/docs/ko/models/#%EA%B8%B0%EB%B3%B8%EA%B0%92-%EC%84%A4%EC%A0%95) --------------------------------------------------------------------------------------------- 기본 모델로 설정하려면 `model` 키를 설정할 수 있습니다. opencode 설정. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} 전체 ID는 `provider_id/model_id`입니다. 예를 들어, [OpenCode Zen](https://opencode.ai/docs/zen) 을 사용한다면, GPT 5.1 Codex에 `opencode/gpt-5.1-codex`를 사용할 수 있습니다. [custom Provider](https://opencode.ai/docs/providers#custom) 를 구성하면 `provider_id`는 구성의 `provider` 부분에서 키이며 `model_id`는 `provider.models`에서 키입니다. * * * [모델 구성](https://opencode.ai/docs/ko/models/#%EB%AA%A8%EB%8D%B8-%EA%B5%AC%EC%84%B1) ----------------------------------------------------------------------------------- config를 통해 모델의 옵션을 구성할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} 여기서는 두 개의 내장 모델에 대한 전역 설정을 구성합니다: `gpt-5`를 통해 액세스 할 때 `openai` 공급자 및 `claude-sonnet-4-20250514`는 `anthropic` 공급자를 통해 액세스 할 때. 내장 공급자 및 모델 이름은 [Models.dev](https://models.dev/) 에서 찾을 수 있습니다. 사용중인 에이전트에 이러한 옵션을 구성할 수 있습니다. 에이전트 구성은 여기에 모든 글로벌 옵션을 overrides. [더 알아보기](https://opencode.ai/docs/agents/#additional) . 내장 된 것을 확장하는 사용자 정의 변형을 정의 할 수 있습니다. Variants는 중복 항목 생성 없이 동일한 모델을 위한 다른 설정을 구성할 수 있습니다: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [변형](https://opencode.ai/docs/ko/models/#%EB%B3%80%ED%98%95) ------------------------------------------------------------- 많은 모델이 다양한 구성의 변형(variant)을 지원합니다. opencode는 인기있는 공급자를위한 기본 변형으로 배송됩니다. [내장 변형](https://opencode.ai/docs/ko/models/#%EB%82%B4%EC%9E%A5-%EB%B3%80%ED%98%95) ----------------------------------------------------------------------------------- opencode는 많은 공급자를 위한 기본 변종으로 발송합니다: **Anthropic**: * `high` - 높은 생각(Thinking) 예산 (기본) * `max` - 최대 생각 예산 \*\* OpenAI \*\*: 모델에 따라 다릅니다. * `none` - 추론(Reasoning) 없음 * `minimal` - 최소 추론 노력 * `low` - 낮은 이유 노력 * `medium` - 중간 이유 노력 * `high` - 높은 이유 노력 * `xhigh` - 추가 높은 이유 노력 \*\* 구글 \*\*: * `low` - 더 낮은 노력/토큰 예산 * `high` - 더 높은 노력 / 토큰 예산 ### [사용자 정의 변형](https://opencode.ai/docs/ko/models/#%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%A0%95%EC%9D%98-%EB%B3%80%ED%98%95) 기존의 변형을 과도하게 할 수 있거나 자신에게 추가 할 수 있습니다. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} [변형 순환](https://opencode.ai/docs/ko/models/#%EB%B3%80%ED%98%95-%EC%88%9C%ED%99%98) ----------------------------------------------------------------------------------- keybind `variant_cycle`를 사용하여 변형 사이 신속하게 전환합니다. [더 알아보기](https://opencode.ai/docs/keybinds) . * * * [모델 로딩 순서](https://opencode.ai/docs/ko/models/#%EB%AA%A8%EB%8D%B8-%EB%A1%9C%EB%94%A9-%EC%88%9C%EC%84%9C) --------------------------------------------------------------------------------------------------------- opencode가 시작될 때, 다음의 우선순위 순서에 있는 모형을 검사합니다: 1. `--model` 또는 `-m` 명령 선 깃발. 형식은 구성 파일과 동일합니다. `provider_id/model_id`. 2. opencode config의 모델 목록. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} 여기에 형식은 `provider/model`입니다. 3. 마지막 사용된 모형. 4. 내부 우선 순위를 사용하는 첫 번째 모델. --- # Modelli | OpenCode [Salta ai contenuti](https://opencode.ai/docs/it/models/#_top) Modelli ======= Configurare un provider LLM e un modello. OpenCode usa [AI SDK](https://ai-sdk.dev/) e [Models.dev](https://models.dev/) per supportare **75+ provider LLM** e supporta anche l’esecuzione di modelli locali. * * * [Provider](https://opencode.ai/docs/it/models/#provider) --------------------------------------------------------- I provider piu popolari sono precaricati per impostazione predefinita. Se hai aggiunto le credenziali di un provider tramite il comando `/connect`, saranno disponibili quando avvii OpenCode. [Scopri di piu](https://opencode.ai/docs/providers) sui provider. * * * [Seleziona un modello](https://opencode.ai/docs/it/models/#seleziona-un-modello) --------------------------------------------------------------------------------- Dopo aver configurato il provider, puoi selezionare il modello che vuoi digitando: /models * * * [Modelli consigliati](https://opencode.ai/docs/it/models/#modelli-consigliati) ------------------------------------------------------------------------------- Esistono moltissimi modelli, e ne escono di nuovi ogni settimana. Tuttavia, solo alcuni sono davvero bravi sia a generare codice sia a chiamare strumenti. Ecco alcuni modelli che funzionano bene con OpenCode, in nessun ordine particolare. (Non e una lista esaustiva e potrebbe non essere aggiornata): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [Imposta un predefinito](https://opencode.ai/docs/it/models/#imposta-un-predefinito) ------------------------------------------------------------------------------------- Per impostarne uno come modello predefinito, puoi impostare la chiave `model` nella config di OpenCode. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Qui l’ID completo e `provider_id/model_id`. Per esempio, se usi [OpenCode Zen](https://opencode.ai/docs/zen) , useresti `opencode/gpt-5.1-codex` per GPT 5.1 Codex. Se hai configurato un [provider personalizzato](https://opencode.ai/docs/providers#custom) , `provider_id` e la chiave nella sezione `provider` della config e `model_id` e la chiave in `provider.models`. * * * [Configurazione modelli](https://opencode.ai/docs/it/models/#configurazione-modelli) ------------------------------------------------------------------------------------- Puoi configurare globalmente le opzioni di un modello tramite la config. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Qui stiamo configurando impostazioni globali per due modelli integrati: `gpt-5` quando viene usato tramite il provider `openai` e `claude-sonnet-4-20250514` quando viene usato tramite il provider `anthropic`. I nomi di provider e modelli integrati si trovano su [Models.dev](https://models.dev/) . Puoi anche configurare queste opzioni per gli agenti che usi. La config dell’agente sovrascrive le opzioni globali definite qui. [Scopri di piu](https://opencode.ai/docs/agents/#additional) . Puoi anche definire varianti personalizzate che estendono quelle integrate. Le varianti ti permettono di configurare impostazioni diverse per lo stesso modello senza creare voci duplicate: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Varianti](https://opencode.ai/docs/it/models/#varianti) --------------------------------------------------------- Molti modelli supportano piu varianti con configurazioni diverse. OpenCode include varianti predefinite integrate per i provider piu comuni. ### [Varianti integrate](https://opencode.ai/docs/it/models/#varianti-integrate) OpenCode include varianti predefinite per molti provider: **Anthropic**: * `high` - High thinking budget (default) * `max` - Maximum thinking budget **OpenAI**: Varies by model but roughly: * `none` - No reasoning * `minimal` - Minimal reasoning effort * `low` - Low reasoning effort * `medium` - Medium reasoning effort * `high` - High reasoning effort * `xhigh` - Extra high reasoning effort **Google**: * `low` - Lower effort/token budget * `high` - Higher effort/token budget ### [Varianti personalizzate](https://opencode.ai/docs/it/models/#varianti-personalizzate) Puoi sovrascrivere varianti esistenti o aggiungerne di tue: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Ciclare tra varianti](https://opencode.ai/docs/it/models/#ciclare-tra-varianti) Usa il keybind `variant_cycle` per passare rapidamente tra le varianti. [Scopri di piu](https://opencode.ai/docs/keybinds) . * * * [Caricamento modelli](https://opencode.ai/docs/it/models/#caricamento-modelli) ------------------------------------------------------------------------------- Quando OpenCode si avvia, controlla i modelli in questo ordine di priorita: 1. Il flag da riga di comando `--model` o `-m`. Il formato e lo stesso della config: `provider_id/model_id`. 2. La lista dei modelli nella config di OpenCode. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} Qui il formato e `provider/model`. 3. L’ultimo modello usato. 4. Il primo modello in base a una priorita interna. --- # Modelos | OpenCode [Pular para o conteúdo](https://opencode.ai/docs/pt-br/models/#_top) Modelos ======= Configurando um provedor e modelo LLM. O opencode usa o [AI SDK](https://ai-sdk.dev/) e [Models.dev](https://models.dev/) para suportar **75+ provedores LLM** e suporta a execução de modelos locais. * * * [Provedores](https://opencode.ai/docs/pt-br/models/#provedores) ---------------------------------------------------------------- Os provedores mais populares são pré-carregados por padrão. Se você adicionou as credenciais para um provedor através do comando `/connect`, elas estarão disponíveis quando você iniciar o opencode. Saiba mais sobre [provedores](https://opencode.ai/docs/providers) . * * * [Selecionando um modelo](https://opencode.ai/docs/pt-br/models/#selecionando-um-modelo) ---------------------------------------------------------------------------------------- Depois de configurar seu provedor, você pode selecionar o modelo que deseja digitando: /models * * * [Modelos recomendados](https://opencode.ai/docs/pt-br/models/#modelos-recomendados) ------------------------------------------------------------------------------------ Existem muitos modelos disponíveis, com novos modelos sendo lançados toda semana. No entanto, há apenas alguns deles que são bons tanto em gerar código quanto em chamar ferramentas. Aqui estão vários modelos que funcionam bem com o opencode, em nenhuma ordem específica. (Esta não é uma lista exaustiva nem necessariamente atualizada): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [Definindo um padrão](https://opencode.ai/docs/pt-br/models/#definindo-um-padr%C3%A3o) --------------------------------------------------------------------------------------- Para definir um desses como o modelo padrão, você pode definir a chave `model` na sua configuração do opencode. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Aqui, o ID completo é `provider_id/model_id`. Por exemplo, se você estiver usando [OpenCode Zen](https://opencode.ai/docs/zen) , você usaria `opencode/gpt-5.1-codex` para GPT 5.1 Codex. Se você configurou um [provedor personalizado](https://opencode.ai/docs/providers#custom) , o `provider_id` é a chave da parte `provider` da sua configuração, e o `model_id` é a chave de `provider.models`. * * * [Configurando modelos](https://opencode.ai/docs/pt-br/models/#configurando-modelos) ------------------------------------------------------------------------------------ Você pode configurar globalmente as opções de um modelo através da configuração. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Aqui estamos configurando as configurações globais para dois modelos integrados: `gpt-5` quando acessado via o provedor `openai`, e `claude-sonnet-4-20250514` quando acessado via o provedor `anthropic`. Os nomes dos provedores e modelos integrados podem ser encontrados em [Models.dev](https://models.dev/) . Você também pode configurar essas opções para quaisquer agentes que estiver usando. A configuração do agente substitui quaisquer opções globais aqui. [Saiba mais](https://opencode.ai/docs/agents/#additional) . Você também pode definir variantes personalizadas que estendem as integradas. As variantes permitem que você configure diferentes configurações para o mesmo modelo sem criar entradas duplicadas: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Variantes](https://opencode.ai/docs/pt-br/models/#variantes) -------------------------------------------------------------- Muitos modelos suportam várias variantes com diferentes configurações. O opencode vem com variantes padrão integradas para provedores populares. ### [Variantes integradas](https://opencode.ai/docs/pt-br/models/#variantes-integradas) O opencode vem com variantes padrão para muitos provedores: **Anthropic**: * `high` - Orçamento de pensamento alto (padrão) * `max` - Orçamento de pensamento máximo **OpenAI**: Varia por modelo, mas aproximadamente: * `none` - Sem raciocínio * `minimal` - Esforço de raciocínio mínimo * `low` - Baixo esforço de raciocínio * `medium` - Esforço de raciocínio médio * `high` - Alto esforço de raciocínio * `xhigh` - Esforço de raciocínio extra alto **Google**: * `low` - Orçamento de esforço/token mais baixo * `high` - Orçamento de esforço/token mais alto ### [Variantes personalizadas](https://opencode.ai/docs/pt-br/models/#variantes-personalizadas) Você pode substituir variantes existentes ou adicionar as suas: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Ciclo de variantes](https://opencode.ai/docs/pt-br/models/#ciclo-de-variantes) Use a tecla de atalho `variant_cycle` para alternar rapidamente entre variantes. [Saiba mais](https://opencode.ai/docs/keybinds) . * * * [Carregando modelos](https://opencode.ai/docs/pt-br/models/#carregando-modelos) -------------------------------------------------------------------------------- Quando o opencode é iniciado, ele verifica modelos na seguinte ordem de prioridade: 1. A flag de linha de comando `--model` ou `-m`. O formato é o mesmo que no arquivo de configuração: `provider_id/model_id`. 2. A lista de modelos na configuração do opencode. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} O formato aqui é `provider/model`. 3. O último modelo usado. 4. O primeiro modelo usando uma prioridade interna. --- # Modeller | OpenCode [Gå til innholdet](https://opencode.ai/docs/nb/models/#_top) Modeller ======== Konfigurere en LLM leverandør og modell. OpenCode bruker [AI SDK](https://ai-sdk.dev/) og [Models.dev](https://models.dev/) for å støtte **75+ LLM leverandører** og den støtter kjøring av lokale modeller. * * * [Leverandører](https://opencode.ai/docs/nb/models/#leverand%C3%B8rer) ---------------------------------------------------------------------- De fleste populære leverandørene er forhåndslastet som standard. Hvis du har lagt til legitimasjonen for en leverandør gjennom kommandoen `/connect`, vil den være tilgjengelig når du starter OpenCode. Finn ut mer om [leverandører](https://opencode.ai/docs/providers) . * * * [Velge en modell](https://opencode.ai/docs/nb/models/#velge-en-modell) ----------------------------------------------------------------------- Når du har konfigurert leverandøren din, kan du velge modellen du ønsker ved å skrive inn: /models * * * [Anbefalte modeller](https://opencode.ai/docs/nb/models/#anbefalte-modeller) ----------------------------------------------------------------------------- Det er mange modeller der ute, med nye modeller som kommer ut hver uke. Imidlertid er det bare noen få av dem som er gode til både å generere kode og verktøykalling. Her er flere modeller som fungerer godt med OpenCode, uten spesiell rekkefølge. (Dette er ikke en uttømmende liste og er heller ikke nødvendigvis oppdatert): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [Angi en standard](https://opencode.ai/docs/nb/models/#angi-en-standard) ------------------------------------------------------------------------- For å angi en av disse som standardmodell, kan du angi `model`\-tasten i din OpenCode-konfigurasjon. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Her er hele ID `provider_id/model_id`. For eksempel, hvis du bruker [OpenCode Zen](https://opencode.ai/docs/zen) , vil du bruke `opencode/gpt-5.1-codex` for GPT 5.1 Codex. Hvis du har konfigurert en [egendefinert leverandør](https://opencode.ai/docs/providers#custom) , er `provider_id` nøkkelen fra `provider`\-delen av konfigurasjonen din, og `model_id` er nøkkelen fra `provider.models`. * * * [Konfigurer modeller](https://opencode.ai/docs/nb/models/#konfigurer-modeller) ------------------------------------------------------------------------------- Du kan konfigurere en modells alternativer globalt gjennom konfigurasjonen. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Her konfigurerer vi globale innstillinger for to innebygde modeller: `gpt-5` når de åpnes via `openai`\-leverandøren, og `claude-sonnet-4-20250514` når de åpnes via `anthropic`\-leverandøren. De innebygde leverandør- og modellnavnene finnes på [Models.dev](https://models.dev/) . Du kan også konfigurere disse alternativene for alle agenter du bruker. Agentkonfigurasjonen overstyrer alle globale alternativer her. [Finn ut mer](https://opencode.ai/docs/agents/#additional) . Du kan også definere tilpassede varianter som utvider de innebygde. Varianter lar deg konfigurere forskjellige innstillinger for samme modell uten å opprette dupliserte oppføringer: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Varianter](https://opencode.ai/docs/nb/models/#varianter) ----------------------------------------------------------- Mange modeller støtter flere varianter med forskjellige konfigurasjoner. opencode leveres med innebygde standardvarianter for populære leverandører. ### [Innebygde varianter](https://opencode.ai/docs/nb/models/#innebygde-varianter) OpenCode leveres med standardvarianter for mange leverandører: **Anthropic**: * `high` - Høyt tenkebudsjett (standard) * `max` - Maksimalt tenkebudsjett **OpenAI**: Varierer etter modell, men omtrent: * `none` - Ingen resonnement * `minimal` - Minimal resonnementinnsats * `low` - Lav resonnementinnsats * `medium` - Middels resonnementinnsats * `high` - Høy resonnementinnsats * `xhigh` - Ekstra høy resonnementinnsats **Google**: * `low` - Lavere innsats/tokenbudsjett * `high` - Høyere innsats/tokenbudsjett ### [Egendefinerte varianter](https://opencode.ai/docs/nb/models/#egendefinerte-varianter) Du kan overstyre eksisterende varianter eller legge til dine egne: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Bytt varianter](https://opencode.ai/docs/nb/models/#bytt-varianter) Bruk tastebindingen `variant_cycle` for raskt å bytte mellom varianter. [Finn ut mer](https://opencode.ai/docs/keybinds) . * * * [Lasting av modeller](https://opencode.ai/docs/nb/models/#lasting-av-modeller) ------------------------------------------------------------------------------- Når OpenCode starter opp, ser den etter modeller i følgende prioriterte rekkefølge: 1. Kommandolinjeflagget `--model` eller `-m`. Formatet er det samme som i konfigurasjonsfilen: `provider_id/model_id`. 2. Modelllisten i OpenCode-konfigurasjonen. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} Formatet her er `provider/model`. 3. Den sist brukte modellen. 4. Den første modellen bruker en intern prioritet. --- # Modelos | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/models/#_top) Modelos ======= Configuración de un proveedor y modelo LLM. OpenCode usa el [AI SDK](https://ai-sdk.dev/) y [Models.dev](https://models.dev/) para admitir **75+ proveedores LLM** y admite la ejecución de modelos locales. * * * [Proveedores](https://opencode.ai/docs/es/models/#proveedores) --------------------------------------------------------------- Los proveedores más populares están precargados de forma predeterminada. Si agregó las credenciales de un proveedor mediante el comando `/connect`, estarán disponibles cuando inicie OpenCode. Obtenga más información sobre [proveedores](https://opencode.ai/docs/providers) . * * * [Seleccionar un modelo](https://opencode.ai/docs/es/models/#seleccionar-un-modelo) ----------------------------------------------------------------------------------- Una vez que hayas configurado tu proveedor podrás seleccionar el modelo que desees escribiendo: /models * * * [Modelos recomendados](https://opencode.ai/docs/es/models/#modelos-recomendados) --------------------------------------------------------------------------------- Hay muchos modelos disponibles y cada semana salen nuevos modelos. Sin embargo, sólo unos pocos de ellos son buenos tanto para generar código como para llamar a herramientas. Aqui tienes varios modelos que funcionan bien con OpenCode, sin orden particular. (Esta no es una lista exhaustiva ni necesariamente actualizada): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [Establecer un valor predeterminado](https://opencode.ai/docs/es/models/#establecer-un-valor-predeterminado) ------------------------------------------------------------------------------------------------------------- Para configurar uno de estos como modelo predeterminado, puedes definir la clave `model` en tu configuracion de OpenCode. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Aquí el ID completo es `provider_id/model_id`. Por ejemplo, si usa [OpenCode Zen](https://opencode.ai/docs/zen) , usaría `opencode/gpt-5.1-codex` para GPT 5.1 Codex. Si ha configurado un [proveedor personalizado](https://opencode.ai/docs/providers#custom) , `provider_id` es la clave de la parte `provider` de su configuración y `model_id` es la clave de `provider.models`. * * * [Configurar modelos](https://opencode.ai/docs/es/models/#configurar-modelos) ----------------------------------------------------------------------------- Puede configurar globalmente las opciones de un modelo a través de la configuración. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Aquí estamos configurando ajustes globales para dos modelos integrados: `gpt-5` cuando se accede a través del proveedor `openai` y `claude-sonnet-4-20250514` cuando se accede a través del proveedor `anthropic`. Los nombres de modelo y proveedor integrados se pueden encontrar en [Models.dev](https://models.dev/) . También puede configurar estas opciones para cualquier agente que esté utilizando. La configuración del agente anula cualquier opción global aquí. [Más información](https://opencode.ai/docs/agents/#additional) . También puede definir variantes personalizadas que amplíen las integradas. Las variantes le permiten configurar diferentes ajustes para el mismo modelo sin crear entradas duplicadas: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Variantes](https://opencode.ai/docs/es/models/#variantes) ----------------------------------------------------------- Muchos modelos admiten múltiples variantes con diferentes configuraciones. OpenCode se envía con variantes predeterminadas integradas para proveedores populares. ### [Variantes integradas](https://opencode.ai/docs/es/models/#variantes-integradas) OpenCode se envía con variantes predeterminadas para muchos proveedores: **Anthropic**: * `high` - Presupuesto de pensamiento alto (predeterminado) * `max` - Presupuesto de pensamiento máximo **OpenAI**: Varía según el modelo, pero aproximadamente: * `none` - Sin razonamiento * `minimal` - Mínimo esfuerzo de razonamiento * `low` - Bajo esfuerzo de razonamiento * `medium` - Esfuerzo de razonamiento medio * `high` - Alto esfuerzo de razonamiento * `xhigh` - Esfuerzo de razonamiento extra alto **Google**: * `low` - Menor esfuerzo/presupuesto simbólico * `high` - Mayor esfuerzo/presupuesto simbólico ### [Variantes personalizadas](https://opencode.ai/docs/es/models/#variantes-personalizadas) Puede anular las variantes existentes o agregar las suyas propias: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Alternar variantes](https://opencode.ai/docs/es/models/#alternar-variantes) Utilice la combinación de teclas `variant_cycle` para cambiar rápidamente entre variantes. [Más información](https://opencode.ai/docs/keybinds) . * * * [Carga de modelos](https://opencode.ai/docs/es/models/#carga-de-modelos) ------------------------------------------------------------------------- Cuando se inicia OpenCode, busca modelos en el siguiente orden de prioridad: 1. El indicador de línea de comando `--model` o `-m`. El formato es el mismo que en el archivo de configuración: `provider_id/model_id`. 2. La lista de modelos en la configuración OpenCode. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} El formato aquí es `provider/model`. 3. El último modelo utilizado. 4. El primer modelo que utiliza una prioridad interna. --- # Modeller | OpenCode [İçeriğe geç](https://opencode.ai/docs/tr/models/#_top) Modeller ======== LLM sağlayıcılarını ve model seçimlerini yapılandırın. opencode, **75+ LLM sağlayıcısını** desteklemek için [AI SDK](https://ai-sdk.dev/) ve [Models.dev](https://models.dev/) kullanır ve yerel modellerin çalıştırılmasını destekler. * * * [Sağlayıcılar](https://opencode.ai/docs/tr/models/#sa%C4%9Flay%C4%B1c%C4%B1lar) -------------------------------------------------------------------------------- Çoğu popüler sağlayıcı varsayılan olarak önceden yüklenmiştir. Bir sağlayıcının kimlik bilgilerini `/connect` komutu aracılığıyla eklediyseniz, bunlar opencode’u başlattığınızda kullanılabilir olacaktır. [Sağlayıcılar](https://opencode.ai/docs/providers) hakkında daha fazla bilgi edinin. * * * [Model seçimi](https://opencode.ai/docs/tr/models/#model-se%C3%A7imi) ---------------------------------------------------------------------- Sağlayıcınızı yapılandırdıktan sonra aşağıdaki komutu yazarak istediğiniz modeli seçebilirsiniz: /models * * * [Önerilen modeller](https://opencode.ai/docs/tr/models/#%C3%B6nerilen-modeller) -------------------------------------------------------------------------------- Piyasada pek çok model var ve her hafta yeni modeller çıkıyor. Ancak, hem kod oluşturmada hem de araç çağırmada iyi olan yalnızca birkaçı var. Burada, opencode ile belirli bir sıraya göre iyi çalışan birkaç model yer almaktadır. (Bu kapsamlı bir liste değildir ve mutlaka güncel olması da gerekmez): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [Varsayılan ayarlama](https://opencode.ai/docs/tr/models/#varsay%C4%B1lan-ayarlama) ------------------------------------------------------------------------------------ Bunlardan birini varsayılan model olarak ayarlamak için `model` anahtarınızı telefonunuzudan ayarlayabilirsiniz. opencode yapılandırması { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Burada tam kimlik `provider_id/model_id`’dir. Örneğin, [OpenCode Zen](https://opencode.ai/docs/zen) kullanıyorsanız, GPT 5.1 Codex için `opencode/gpt-5.1-codex` kullanırsınız. Bir [custom provider](https://opencode.ai/docs/providers#custom) yapılandırılmışsa, `provider_id`, performansınızın `provider` bölümünden gelen anahtardır ve `model_id`, `provider.models`’den gelen anahtardır. * * * [Model yapılandırma](https://opencode.ai/docs/tr/models/#model-yap%C4%B1land%C4%B1rma) --------------------------------------------------------------------------------------- Bir modelin seçeneklerini genel olarak yapılandırma aracılığıyla yapılandırabilirsiniz. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Burada iki yerleşik model için genel ayarları yapılandırıyoruz: `gpt-5` sağlayıcısı aracılığıyla erişildiğinde `openai` ve `claude-sonnet-4-20250514` sağlayıcısı aracılığıyla erişildiğinde `anthropic`. Yerleşik sağlayıcı ve model adları [Models.dev](https://models.dev/) adresinde bulunabilir. Bu seçenekleri kullandığınız tüm aracılar için de yapılandırabilirsiniz. Aracı yapılandırması burada tüm genel seçenekleri geçersiz kılar. [Daha fazla bilgi](https://opencode.ai/docs/agents/#additional) . Ayrıca yerleşik çeşitleri genişleten özel varyantlar da tanımlayabilirsiniz. Varyantlar, yinelenen girişler oluşturmadan aynı model için farklı ayarları yapılandırmanıza olanak tanır: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Varyantlar](https://opencode.ai/docs/tr/models/#varyantlar) ------------------------------------------------------------- Birçok model, farklı konfigürasyonlara sahip birden fazla kapasiteye sahip. opencode, popüler sağlayıcılar için sunulan değişkenlerle birlikte gelir. ### [Yerleşik çeşitler](https://opencode.ai/docs/tr/models/#yerle%C5%9Fik-%C3%A7e%C5%9Fitler) opencode birçok sağlayıcı için varsayılan değişkenlerle birlikte gelir: **Antropik**: * `high` - Yüksek düşünme bütçesi (varsayılan) * `max` - Maksimum düşünme bütçesi **OpenAI**: Modele göre değişir ancak kabaca: * `none` - Gerekçe yok * `minimal` - Minimum akıl yürütme çabası * `low` - Düşük muhakeme çabası * `medium` - Orta düzey muhakeme çabası * `high` - Yüksek akıl yürütme çabası * `xhigh` - Ekstra yüksek muhakeme çabası **Google**: * `low` - Daha düşük effort/token bütçesi * `high` - Daha yüksek effort/token bütçesi ### [Özel çeşitler](https://opencode.ai/docs/tr/models/#%C3%B6zel-%C3%A7e%C5%9Fitler) Mevcut varyantları geçersiz kılabilir veya kendinizinkini ekleyebilirsiniz: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Döngü çeşitleri](https://opencode.ai/docs/tr/models/#d%C3%B6ng%C3%BC-%C3%A7e%C5%9Fitleri) Çeşitler arasında hızlı geçiş yapmak için `variant_cycle` tuş atamasını kullanın. [Daha fazla bilgi](https://opencode.ai/docs/keybinds) . * * * [Modelleri yükleme](https://opencode.ai/docs/tr/models/#modelleri-y%C3%BCkleme) -------------------------------------------------------------------------------- opencode başlatıldığında modelleri aşağıdaki öncelik sırasına göre kontrol eder: 1. `--model` veya `-m` komut satırı bayrağı. Biçim, yapılandırma dosyasındakiyle aynıdır: `provider_id/model_id`. 2. opencode yapılandırmasındaki model listesi. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} Buradaki format `provider/model`’dır. 3. En son kullanılan model. 4. Dahili öncelik kullanan ilk model. --- # モデル | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/models/#_top) モデル === LLM プロバイダーとモデルを構成します。 OpenCode は [AI SDK](https://ai-sdk.dev/) および [Models.dev](https://models.dev/) を使用して **75 以上の LLM プロバイダー** をサポートし、ローカルモデルの実行をサポートします。 * * * [プロバイダー](https://opencode.ai/docs/ja/models/#%E3%83%97%E3%83%AD%E3%83%90%E3%82%A4%E3%83%80%E3%83%BC) ----------------------------------------------------------------------------------------------------- 最も一般的なプロバイダーはデフォルトでプリロードされています。 `/connect` コマンドを使用してプロバイダーの資格情報を追加した場合は、OpenCode を開始するときにそれらの資格情報を使用できるようになります。 [プロバイダー](https://opencode.ai/docs/providers) . * * * [モデルの選択](https://opencode.ai/docs/ja/models/#%E3%83%A2%E3%83%87%E3%83%AB%E3%81%AE%E9%81%B8%E6%8A%9E) ----------------------------------------------------------------------------------------------------- プロバイダーを構成したら、次のように入力して必要なモデルを選択できます。 /models * * * [推奨モデル](https://opencode.ai/docs/ja/models/#%E6%8E%A8%E5%A5%A8%E3%83%A2%E3%83%87%E3%83%AB) ------------------------------------------------------------------------------------------- たくさんのモデルがあり、毎週のように新しいモデルが登場します。 しかし、コード生成とツール呼び出しの両方に優れたものはほんのわずかしかありません。 ここでは、OpenCode で適切に動作するいくつかのモデルを順不同で示します。 (これは完全なリストではなく、必ずしも最新であるとは限りません): * GPT5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * MiniMax M2.1 * Gemini 3 Pro * * * [デフォルトの設定](https://opencode.ai/docs/ja/models/#%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%81%AE%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------------------------------------------------------------------- これらのいずれかをデフォルトのモデルとして設定するには、`model` キーを OpenCode の設定に追加します。 { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} ここでの完全な ID は `provider_id/model_id` です。たとえば、[OpenCode Zen](https://opencode.ai/docs/zen) を使用している場合、GPT 5.1 Codex には `opencode/gpt-5.1-codex` を使用します。 [カスタムプロバイダー](https://opencode.ai/docs/providers#custom) を構成している場合、`provider_id` は構成の `provider` 部分のキーであり、`model_id` は `provider.models` のキーです。 * * * [モデルの設定](https://opencode.ai/docs/ja/models/#%E3%83%A2%E3%83%87%E3%83%AB%E3%81%AE%E8%A8%AD%E5%AE%9A) ----------------------------------------------------------------------------------------------------- config を通じてモデルのオプションをグローバルに設定できます。 { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} ここでは、2 つの組み込みモデル (`gpt-5` プロバイダー経由でアクセスする場合は `openai`、`claude-sonnet-4-20250514` プロバイダー経由でアクセスする場合は `anthropic`) のグローバル設定を構成しています。 組み込みプロバイダーとモデル名は、[Models.dev](https://models.dev/) で確認できます。 使用しているエージェントに対してこれらのオプションを構成することもできます。ここでエージェント設定はグローバルオプションをオーバーライドします。 [詳細はこちら](https://opencode.ai/docs/agents/#additional) 。 組み込みバリアントを拡張するカスタムバリアントを定義することもできます。バリアントを使用すると、重複したエントリを作成せずに、同じモデルに対して異なる設定を構成できます。 { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [バリアント](https://opencode.ai/docs/ja/models/#%E3%83%90%E3%83%AA%E3%82%A2%E3%83%B3%E3%83%88) ------------------------------------------------------------------------------------------- 多くのモデルは、異なる構成の複数のバリアントをサポートしています。 OpenCode には、一般的なプロバイダーのデフォルトのバリアントが組み込まれています。 ### [組み込みバリアント](https://opencode.ai/docs/ja/models/#%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF%E3%83%90%E3%83%AA%E3%82%A2%E3%83%B3%E3%83%88) OpenCode には、多くのプロバイダーのデフォルトのバリアントが付属しています。 **Anthropic**: * `high` - 高度な思考予算 (デフォルト) * `max` - 最大の思考予算 **OpenAI**: モデルによって異なりますが、おおよそ次のとおりです。 * `none` - 理由はありません * `minimal` - 最小限の推論努力 * `low` - 推論の労力が少ない * `medium` - 中程度の推論努力 * `high` - 高い推論努力 * `xhigh` - 非常に高い推論努力 **Google**: * `low` - 労力/トークン予算の削減 * `high` - より高い労力/トークン予算 ### [カスタムバリアント](https://opencode.ai/docs/ja/models/#%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%90%E3%83%AA%E3%82%A2%E3%83%B3%E3%83%88) 既存のバリアントをオーバーライドすることも、独自のバリアントを追加することもできます。 { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [バリアントの切り替え](https://opencode.ai/docs/ja/models/#%E3%83%90%E3%83%AA%E3%82%A2%E3%83%B3%E3%83%88%E3%81%AE%E5%88%87%E3%82%8A%E6%9B%BF%E3%81%88) キーバインド `variant_cycle` を使用すると、バリアントをすばやく切り替えることができます。 [詳細はこちら](https://opencode.ai/docs/keybinds) 。 * * * [モデルのロード](https://opencode.ai/docs/ja/models/#%E3%83%A2%E3%83%87%E3%83%AB%E3%81%AE%E3%83%AD%E3%83%BC%E3%83%89) --------------------------------------------------------------------------------------------------------------- OpenCode が起動すると、次の優先順位でモデルがチェックされます。 1. `--model` または `-m` コマンドラインフラグ。形式は構成ファイルと同じです: `provider_id/model_id`。 2. OpenCode 構成内のモデルのリスト。 { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} ここでの形式は `provider/model` です。 3. 最後に使用されたモデル。 4. 内部優先順位に基づく最初のモデル。 --- # โมเดล | OpenCode [Skip to content](https://opencode.ai/docs/th/models/#_top) โมเดล ===== การกำหนดค่าผู้ให้บริการและรุ่น LLM OpenCode ใช้ [AI SDK](https://ai-sdk.dev/) และ [Models.dev](https://models.dev/) เพื่อรองรับผู้ให้บริการ **75+ LLM** และรองรับการใช้งานโมเดลท้องถิ่น * * * [ผู้ให้บริการ](https://opencode.ai/docs/th/models/#%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) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ผู้ให้บริการที่ได้รับความนิยมส่วนใหญ่จะถูกโหลดไว้ล่วงหน้าตามค่าเริ่มต้น หากคุณได้เพิ่มข้อมูลรับรองสำหรับผู้ให้บริการผ่านคำสั่ง `/connect` ข้อมูลเหล่านั้นจะพร้อมใช้งานเมื่อคุณเริ่ม OpenCode เรียนรู้เพิ่มเติมเกี่ยวกับ [ผู้ให้บริการ](https://opencode.ai/docs/providers) * * * [เลือกรุ่น](https://opencode.ai/docs/th/models/#%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81%E0%B8%A3%E0%B8%B8%E0%B9%88%E0%B8%99) ----------------------------------------------------------------------------------------------------------------------------------- เมื่อคุณกำหนดค่าผู้ให้บริการแล้ว คุณสามารถเลือกรุ่นที่ต้องการได้โดยพิมพ์: /models * * * [รุ่นที่แนะนำ](https://opencode.ai/docs/th/models/#%E0%B8%A3%E0%B8%B8%E0%B9%88%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%81%E0%B8%99%E0%B8%B0%E0%B8%99%E0%B8%B3) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- มีโมเดลออกมามากมาย โดยมีโมเดลใหม่ๆ ออกมาทุกสัปดาห์ อย่างไรก็ตาม มีเพียงไม่กี่ตัวเท่านั้นที่เก่งทั้งการสร้างโค้ดและการเรียกใช้เครื่องมือ ต่อไปนี้เป็นโมเดลหลายรุ่นที่ทำงานได้ดีกับ OpenCode โดยไม่เรียงลำดับเป็นพิเศษ (นี่ไม่ใช่รายการที่ครอบคลุมและไม่จำเป็นต้องเป็นข้อมูลล่าสุด): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * MiniMax M2.1 * Gemini 3 Pro * * * [ตั้งค่าเริ่มต้น](https://opencode.ai/docs/th/models/#%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87%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) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- หากต้องการตั้งค่าสิ่งใดสิ่งหนึ่งเป็นโมเดลเริ่มต้น คุณสามารถตั้งค่าคีย์ `model` ในของคุณ การกำหนดค่า OpenCode { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} ID แบบเต็มคือ `provider_id/model_id` ตัวอย่างเช่น หากคุณใช้ [OpenCode Zen](https://opencode.ai/docs/zen) คุณจะใช้ `opencode/gpt-5.1-codex` สำหรับ GPT 5.1 Codex หากคุณได้กำหนดค่า [ผู้ให้บริการที่กำหนดเอง](https://opencode.ai/docs/providers#%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) `provider_id` จะเป็นคีย์จากส่วน `provider` ของการกำหนดค่าของคุณ และ `model_id` จะเป็นคีย์จาก `provider.models` * * * [กำหนดค่าโมเดล](https://opencode.ai/docs/th/models/#%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%B9%82%E0%B8%A1%E0%B9%80%E0%B8%94%E0%B8%A5) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- คุณสามารถกำหนดค่าตัวเลือกของโมเดลได้ทั่วโลกผ่านการกำหนดค่า { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} ที่นี่เรากำลังกำหนดการตั้งค่าส่วนกลางสำหรับโมเดลในตัวสองรุ่น: `gpt-5` เมื่อเข้าถึงผ่านผู้ให้บริการ `openai` และ `claude-sonnet-4-20250514` เมื่อเข้าถึงผ่านผู้ให้บริการ `anthropic` สามารถดูผู้ให้บริการและชื่อรุ่นในตัวได้ที่ [Models.dev](https://models.dev/) คุณยังสามารถกำหนดค่าตัวเลือกเหล่านี้สำหรับตัวแทนใดๆ ที่คุณใช้อยู่ได้ การกำหนดค่าตัวแทนจะแทนที่ตัวเลือกส่วนกลางใดๆ ที่นี่ [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/agents/#%E0%B9%80%E0%B8%9E%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B9%80%E0%B8%95%E0%B8%B4%E0%B8%A1) คุณยังสามารถกำหนดตัวแปรแบบกำหนดเองที่ขยายตัวแปรในตัวได้ ตัวแปรช่วยให้คุณกำหนดการตั้งค่าที่แตกต่างกันสำหรับรุ่นเดียวกันโดยไม่ต้องสร้างรายการที่ซ้ำกัน: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Variants (แบบ)](https://opencode.ai/docs/th/models/#variants-%E0%B9%81%E0%B8%9A%E0%B8%9A) ------------------------------------------------------------------------------------------- โมเดลหลายตัวรองรับหลาย variants (รูปแบบย่อย) ที่มีการกำหนดค่าต่างกัน OpenCode มาพร้อมกับ variants เริ่มต้นในตัวสำหรับผู้ให้บริการยอดนิยม ### [Variants ในตัว (Built-in Variants)](https://opencode.ai/docs/th/models/#variants-%E0%B9%83%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7-built-in-variants) OpenCode มาพร้อมกับ variants เริ่มต้นสำหรับผู้ให้บริการหลายราย: **Anthropic**: * `high` - งบประมาณการคิดสูง (ค่าเริ่มต้น) * `max` - งบประมาณการคิดสูงสุด **OpenAI**: แตกต่างกันไปตามรุ่น แต่โดยประมาณ: * `none` - ไม่ใช้การให้เหตุผล * `minimal` - ความพยายามในการให้เหตุผลน้อยที่สุด * `low` - ความพยายามในการให้เหตุผลต่ำ * `medium` - ความพยายามในการให้เหตุผลปานกลาง * `high` - ความพยายามในการให้เหตุผลสูง * `xhigh` - ความพยายามในการให้เหตุผลสูงเป็นพิเศษ **Google**: * `low` - งบประมาณการคิดต่ำ/token ต่ำ * `high` - งบประมาณการคิดสูง/token สูง ### [Variants แบบกำหนดเอง](https://opencode.ai/docs/th/models/#variants-%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%81%E0%B8%B3%E0%B8%AB%E0%B8%99%E0%B8%94%E0%B9%80%E0%B8%AD%E0%B8%87) คุณสามารถแทนที่ variants ที่มีอยู่หรือเพิ่มของคุณเองได้: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [การหมุนเวียน Variants](https://opencode.ai/docs/th/models/#%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AB%E0%B8%A1%E0%B8%B8%E0%B8%99%E0%B9%80%E0%B8%A7%E0%B8%B5%E0%B8%A2%E0%B8%99-variants) ใช้ปุ่มลัด `variant_cycle` เพื่อสลับระหว่าง variants ต่างๆ อย่างรวดเร็ว [เรียนรู้เพิ่มเติม](https://opencode.ai/docs/keybinds) * * * [กำลังโหลดโมเดล](https://opencode.ai/docs/th/models/#%E0%B8%81%E0%B8%B3%E0%B8%A5%E0%B8%B1%E0%B8%87%E0%B9%82%E0%B8%AB%E0%B8%A5%E0%B8%94%E0%B9%82%E0%B8%A1%E0%B9%80%E0%B8%94%E0%B8%A5) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- เมื่อ OpenCode เริ่มทำงาน ระบบจะตรวจสอบรุ่นตามลำดับความสำคัญต่อไปนี้: 1. การตั้งค่าสถานะบรรทัดคำสั่ง `--model` หรือ `-m` รูปแบบจะเหมือนกับในไฟล์ปรับแต่ง: `provider_id/model_id` 2. รายการโมเดลในการกำหนดค่า OpenCode { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} รูปแบบที่นี่คือ `provider/model` 3. รุ่นที่ใช้ล่าสุด. 4. รุ่นแรกที่ใช้ลำดับความสำคัญภายใน --- # Модели | OpenCode [Перейти к содержимому](https://opencode.ai/docs/ru/models/#_top) Модели ====== Настройка поставщика и модели LLM. opencode использует [AI SDK](https://ai-sdk.dev/) и [Models.dev](https://models.dev/) для поддержки **более 75 поставщиков LLM** и поддерживает запуск локальных моделей. * * * [Провайдеры](https://opencode.ai/docs/ru/models/#%D0%BF%D1%80%D0%BE%D0%B2%D0%B0%D0%B9%D0%B4%D0%B5%D1%80%D1%8B) --------------------------------------------------------------------------------------------------------------- Большинство популярных провайдеров предварительно загружены по умолчанию. Если вы добавили учетные данные для поставщика с помощью команды `/connect`, они будут доступны при запуске opencode. Узнайте больше о [providers](https://opencode.ai/docs/providers) . * * * [Выберите модель](https://opencode.ai/docs/ru/models/#%D0%B2%D1%8B%D0%B1%D0%B5%D1%80%D0%B8%D1%82%D0%B5-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D1%8C) --------------------------------------------------------------------------------------------------------------------------------------------- После того, как вы настроили своего провайдера, вы можете выбрать нужную модель, введя: /models * * * [Рекомендуемые модели](https://opencode.ai/docs/ru/models/#%D1%80%D0%B5%D0%BA%D0%BE%D0%BC%D0%B5%D0%BD%D0%B4%D1%83%D0%B5%D0%BC%D1%8B%D0%B5-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D0%B8) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Моделей очень много, новые выходят каждую неделю. Однако лишь немногие из них хороши как в генерации кода, так и в вызове инструментов. Вот несколько моделей, которые хорошо работают с opencode (в произвольном порядке). (Это не исчерпывающий список и не обязательно актуальный): * GPT 5.2 * Кодекс GPT 5.1 * Claude Opus 4.5 * Claude Sonnet 4.5 * MiniMax M2.1 * Gemini 3 Pro * * * [Установить значение по умолчанию](https://opencode.ai/docs/ru/models/#%D1%83%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%B8%D1%82%D1%8C-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BF%D0%BE-%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Чтобы установить одну из них в качестве модели по умолчанию, вы можете установить ключ `model` в вашем Конфигурация opencode. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Здесь полный идентификатор `provider_id/model_id`. Например, если вы используете [OpenCode Zen](https://opencode.ai/docs/zen) , вы должны использовать `opencode/gpt-5.1-codex` для кодекса GPT 5.1. Если вы настроили [пользовательский поставщик](https://opencode.ai/docs/providers#custom) , `provider_id` — это ключ из части `provider` вашей конфигурации, а `model_id` — это ключ из `provider.models`. * * * [Настройка моделей](https://opencode.ai/docs/ru/models/#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D0%B5%D0%B9) ----------------------------------------------------------------------------------------------------------------------------------------------------------- Вы можете глобально настроить параметры модели через файл config. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Здесь мы настраиваем глобальные параметры для двух встроенных моделей: `gpt-5` при доступе через поставщика `openai` и `claude-sonnet-4-20250514` при доступе через поставщика `anthropic`. Названия встроенных поставщиков и моделей можно найти на сайте [Models.dev](https://models.dev/) . Вы также можете настроить эти параметры для любых используемых вами агентов. Конфигурация агента переопределяет любые глобальные параметры здесь. [Подробнее](https://opencode.ai/docs/agents/#additional) . Вы также можете определить собственные варианты, расширяющие встроенные. Варианты позволяют настраивать разные параметры для одной и той же модели без создания повторяющихся записей: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Варианты](https://opencode.ai/docs/ru/models/#%D0%B2%D0%B0%D1%80%D0%B8%D0%B0%D0%BD%D1%82%D1%8B) ------------------------------------------------------------------------------------------------- Многие модели поддерживают несколько вариантов с разными конфигурациями. opencode поставляется со встроенными вариантами по умолчанию для популярных провайдеров. ### [Встроенные варианты](https://opencode.ai/docs/ru/models/#%D0%B2%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5-%D0%B2%D0%B0%D1%80%D0%B8%D0%B0%D0%BD%D1%82%D1%8B) opencode поставляется с вариантами по умолчанию для многих провайдеров: **Anthropic**: * `high` — Бюджет рассуждений: высокий (по умолчанию) * `max` — Максимальный бюджет рассуждений **OpenAI**: Зависит от модели, но примерно: * `none` — Без рассуждений. * `minimal` — Минимальные усилия для рассуждений * `low` — Низкие усилия для рассуждений. * `medium` — Средние усилия для рассуждений. * `high` — Высокие усилия для рассуждений. * `xhigh` — Сверхвысокие усилия для рассуждений. **Google**: * `low` – меньший бюджет усилий/токенов. * `high` — более высокий бюджет усилий/токенов ### [Пользовательские варианты](https://opencode.ai/docs/ru/models/#%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%B2%D0%B0%D1%80%D0%B8%D0%B0%D0%BD%D1%82%D1%8B) Вы можете переопределить существующие варианты или добавить свои собственные: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Переключение вариантов](https://opencode.ai/docs/ru/models/#%D0%BF%D0%B5%D1%80%D0%B5%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B2%D0%B0%D1%80%D0%B8%D0%B0%D0%BD%D1%82%D0%BE%D0%B2) Используйте сочетание клавиш `variant_cycle` для быстрого переключения между вариантами. [Подробнее](https://opencode.ai/docs/keybinds) . * * * [Загрузка моделей](https://opencode.ai/docs/ru/models/#%D0%B7%D0%B0%D0%B3%D1%80%D1%83%D0%B7%D0%BA%D0%B0-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D0%B5%D0%B9) ---------------------------------------------------------------------------------------------------------------------------------------------------- Когда opencode запускается, он проверяет модели в следующем порядке приоритета: 1. CLI-флаг `--model` или `-m`. Формат тот же, что и в файле конфигурации: `provider_id/model_id`. 2. Список моделей в конфигурации opencode. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} Здесь используется формат `provider/model`. 3. Последняя использованная модель. 4. Первая модель, использующая внутренний приоритет. --- # 主题 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/themes/#_top) 主题 == 选择内置主题或定义您自己的主题。 通过 OpenCode,您可以从多个内置主题中进行选择,使用能自动适配终端主题的主题,或者定义您自己的自定义主题。 默认情况下,OpenCode 使用我们自己的 `opencode` 主题。 * * * [终端要求](https://opencode.ai/docs/zh-cn/themes/#%E7%BB%88%E7%AB%AF%E8%A6%81%E6%B1%82) ------------------------------------------------------------------------------------ 为了使主题能够正确显示完整的调色板,您的终端必须支持**真彩色**(24 位色)。大多数现代终端默认支持此功能,但您可能需要手动启用: * **检查支持情况**:运行 `echo $COLORTERM` — 输出应为 `truecolor` 或 `24bit` * **启用真彩色**:在您的 shell 配置文件中设置环境变量 `COLORTERM=truecolor` * **终端兼容性**:确保您的终端模拟器支持 24 位色(大多数现代终端如 iTerm2、Alacritty、Kitty、Windows Terminal 以及较新版本的 GNOME Terminal 均已支持) 如果没有真彩色支持,主题可能会出现色彩精度下降的情况,或者回退到最接近的 256 色近似值。 * * * [内置主题](https://opencode.ai/docs/zh-cn/themes/#%E5%86%85%E7%BD%AE%E4%B8%BB%E9%A2%98) ------------------------------------------------------------------------------------ OpenCode 自带多个内置主题。 | 名称 | 描述 | | --- | --- | | `system` | 自动适配终端的背景颜色 | | `tokyonight` | 基于 [Tokyonight](https://github.com/folke/tokyonight.nvim)
主题 | | `everforest` | 基于 [Everforest](https://github.com/sainnhe/everforest)
主题 | | `ayu` | 基于 [Ayu](https://github.com/ayu-theme)
暗色主题 | | `catppuccin` | 基于 [Catppuccin](https://github.com/catppuccin)
主题 | | `catppuccin-macchiato` | 基于 [Catppuccin](https://github.com/catppuccin)
主题 | | `gruvbox` | 基于 [Gruvbox](https://github.com/morhetz/gruvbox)
主题 | | `kanagawa` | 基于 [Kanagawa](https://github.com/rebelot/kanagawa.nvim)
主题 | | `nord` | 基于 [Nord](https://github.com/nordtheme/nord)
主题 | | `matrix` | 黑客风格的黑底绿字主题 | | `one-dark` | 基于 [Atom One](https://github.com/Th3Whit3Wolf/one-nvim)
Dark 主题 | 我们还在不断添加更多主题。 * * * [系统主题](https://opencode.ai/docs/zh-cn/themes/#%E7%B3%BB%E7%BB%9F%E4%B8%BB%E9%A2%98) ------------------------------------------------------------------------------------ `system` 主题旨在自动适配您终端的配色方案。与使用固定颜色的传统主题不同,_system_ 主题具有以下特点: * **生成灰度色阶**:根据终端的背景颜色创建自定义灰度色阶,确保最佳对比度。 * **使用 ANSI 颜色**:利用标准 ANSI 颜色(0-15)进行语法高亮和 UI 元素渲染,遵循终端的调色板设置。 * **保留终端默认值**:将文本和背景颜色设为 `none`,以保持终端的原生外观。 系统主题适合以下用户: * 希望 OpenCode 与终端的外观保持一致 * 使用了自定义终端配色方案 * 偏好所有终端应用程序拥有统一的视觉风格 * * * [使用主题](https://opencode.ai/docs/zh-cn/themes/#%E4%BD%BF%E7%94%A8%E4%B8%BB%E9%A2%98) ------------------------------------------------------------------------------------ 您可以通过 `/theme` 命令调出主题选择界面来选择主题,也可以在 `tui.json` 文件中直接指定。 { "$schema": "https://opencode.ai/tui.json", "theme": "tokyonight"} * * * [自定义主题](https://opencode.ai/docs/zh-cn/themes/#%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%BB%E9%A2%98) ---------------------------------------------------------------------------------------------- OpenCode 支持灵活的基于 JSON 的主题系统,让用户可以轻松创建和自定义主题。 * * * ### [层级优先级](https://opencode.ai/docs/zh-cn/themes/#%E5%B1%82%E7%BA%A7%E4%BC%98%E5%85%88%E7%BA%A7) 主题按以下顺序从多个目录加载,后面的目录会覆盖前面的目录: 1. **内置主题** — 嵌入在二进制文件中 2. **用户配置目录** — 定义在 `~/.config/opencode/themes/*.json` 或 `$XDG_CONFIG_HOME/opencode/themes/*.json` 3. **项目根目录** — 定义在 `/.opencode/themes/*.json` 4. **当前工作目录** — 定义在 `./.opencode/themes/*.json` 如果多个目录包含同名主题,将使用优先级较高的目录中的主题。 * * * ### [创建主题](https://opencode.ai/docs/zh-cn/themes/#%E5%88%9B%E5%BB%BA%E4%B8%BB%E9%A2%98) 要创建自定义主题,请在上述任一主题目录中创建一个 JSON 文件。 创建用户级主题: mkdir -p ~/.config/opencode/themesvim ~/.config/opencode/themes/my-theme.json 创建项目级主题: mkdir -p .opencode/themesvim .opencode/themes/my-theme.json * * * ### [JSON 格式](https://opencode.ai/docs/zh-cn/themes/#json-%E6%A0%BC%E5%BC%8F) 主题使用灵活的 JSON 格式,支持以下特性: * **十六进制颜色**:`"#ffffff"` * **ANSI 颜色**:`3`(0-255) * **颜色引用**:`"primary"` 或自定义定义的颜色名 * **深色/浅色变体**:`{"dark": "#000", "light": "#fff"}` * **无颜色**:`"none"` — 使用终端的默认颜色或透明背景 * * * ### [颜色定义](https://opencode.ai/docs/zh-cn/themes/#%E9%A2%9C%E8%89%B2%E5%AE%9A%E4%B9%89) `defs` 部分是可选的,它允许您定义可在主题中重复引用的可复用颜色。 * * * ### [终端默认值](https://opencode.ai/docs/zh-cn/themes/#%E7%BB%88%E7%AB%AF%E9%BB%98%E8%AE%A4%E5%80%BC) 特殊值 `"none"` 可用于任何颜色属性,以继承终端的默认颜色。这在创建需要与终端配色方案无缝融合的主题时特别有用: * `"text": "none"` — 使用终端的默认前景色 * `"background": "none"` — 使用终端的默认背景色 * * * ### [示例](https://opencode.ai/docs/zh-cn/themes/#%E7%A4%BA%E4%BE%8B) 以下是一个自定义主题的完整示例: { "$schema": "https://opencode.ai/theme.json", "defs": { "nord0": "#2E3440", "nord1": "#3B4252", "nord2": "#434C5E", "nord3": "#4C566A", "nord4": "#D8DEE9", "nord5": "#E5E9F0", "nord6": "#ECEFF4", "nord7": "#8FBCBB", "nord8": "#88C0D0", "nord9": "#81A1C1", "nord10": "#5E81AC", "nord11": "#BF616A", "nord12": "#D08770", "nord13": "#EBCB8B", "nord14": "#A3BE8C", "nord15": "#B48EAD" }, "theme": { "primary": { "dark": "nord8", "light": "nord10" }, "secondary": { "dark": "nord9", "light": "nord9" }, "accent": { "dark": "nord7", "light": "nord7" }, "error": { "dark": "nord11", "light": "nord11" }, "warning": { "dark": "nord12", "light": "nord12" }, "success": { "dark": "nord14", "light": "nord14" }, "info": { "dark": "nord8", "light": "nord10" }, "text": { "dark": "nord4", "light": "nord0" }, "textMuted": { "dark": "nord3", "light": "nord1" }, "background": { "dark": "nord0", "light": "nord6" }, "backgroundPanel": { "dark": "nord1", "light": "nord5" }, "backgroundElement": { "dark": "nord1", "light": "nord4" }, "border": { "dark": "nord2", "light": "nord3" }, "borderActive": { "dark": "nord3", "light": "nord2" }, "borderSubtle": { "dark": "nord2", "light": "nord3" }, "diffAdded": { "dark": "nord14", "light": "nord14" }, "diffRemoved": { "dark": "nord11", "light": "nord11" }, "diffContext": { "dark": "nord3", "light": "nord3" }, "diffHunkHeader": { "dark": "nord3", "light": "nord3" }, "diffHighlightAdded": { "dark": "nord14", "light": "nord14" }, "diffHighlightRemoved": { "dark": "nord11", "light": "nord11" }, "diffAddedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffContextBg": { "dark": "nord1", "light": "nord5" }, "diffLineNumber": { "dark": "nord2", "light": "nord4" }, "diffAddedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "diffRemovedLineNumberBg": { "dark": "#3B4252", "light": "#E5E9F0" }, "markdownText": { "dark": "nord4", "light": "nord0" }, "markdownHeading": { "dark": "nord8", "light": "nord10" }, "markdownLink": { "dark": "nord9", "light": "nord9" }, "markdownLinkText": { "dark": "nord7", "light": "nord7" }, "markdownCode": { "dark": "nord14", "light": "nord14" }, "markdownBlockQuote": { "dark": "nord3", "light": "nord3" }, "markdownEmph": { "dark": "nord12", "light": "nord12" }, "markdownStrong": { "dark": "nord13", "light": "nord13" }, "markdownHorizontalRule": { "dark": "nord3", "light": "nord3" }, "markdownListItem": { "dark": "nord8", "light": "nord10" }, "markdownListEnumeration": { "dark": "nord7", "light": "nord7" }, "markdownImage": { "dark": "nord9", "light": "nord9" }, "markdownImageText": { "dark": "nord7", "light": "nord7" }, "markdownCodeBlock": { "dark": "nord4", "light": "nord0" }, "syntaxComment": { "dark": "nord3", "light": "nord3" }, "syntaxKeyword": { "dark": "nord9", "light": "nord9" }, "syntaxFunction": { "dark": "nord8", "light": "nord8" }, "syntaxVariable": { "dark": "nord7", "light": "nord7" }, "syntaxString": { "dark": "nord14", "light": "nord14" }, "syntaxNumber": { "dark": "nord15", "light": "nord15" }, "syntaxType": { "dark": "nord7", "light": "nord7" }, "syntaxOperator": { "dark": "nord9", "light": "nord9" }, "syntaxPunctuation": { "dark": "nord4", "light": "nord0" } }} --- # Modele | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/models/#_top) Modele ====== Konfigurowanie dostawcy i modelu LLM. opencode używa [AI SDK](https://ai-sdk.dev/) i [Models.dev](https://models.dev/) do obsługi **ponad 75 dostawców LLM** i obsługi uruchamiania modeli pierwszych. * * * [Dostawcy](https://opencode.ai/docs/pl/models/#dostawcy) --------------------------------------------------------- Dostępna usługa dostawcy jest dostępna. Jeśli otrzymasz poświadczenie dostawcy za pomocą polecenia `/connect`, będzie on dostępny po uruchomieniu opencode. Dowiedz się więcej o [dostawcach](https://opencode.ai/docs/providers) . * * * [Wybierz model](https://opencode.ai/docs/pl/models/#wybierz-model) ------------------------------------------------------------------- Po skonfigurowaniu dostawcy możesz wybrać dostępny model, wpisując: /models * * * [Polecane modele](https://opencode.ai/docs/pl/models/#polecane-modele) ----------------------------------------------------------------------- Na rynku jest mnóstwo modeli, co tydzień pojawia się nowe. Jednak tylko kilka z nich jest dobrych przy generowaniu kodu, jak i wywołaniu narzędzia. Oto kilka modeli, które dobrze współpracują z opencode, w kolejności. (Nie jest to lista wyczerpująca i nie jest konieczna aktualna): * GPT 5.2 * Kodeks GPT 5.1 * Klaudiusz Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Bliźnięta 3Pro * * * [Ustaw wartość domyślną](https://opencode.ai/docs/pl/models/#ustaw-warto%C5%9B%C4%87-domy%C5%9Bln%C4%85) --------------------------------------------------------------------------------------------------------- Aby zainstalować jeden z nich jako model domyślny, możesz zainstalować klucz `model` w swoim opencode konfiguracja { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} Tutaj pełny identyfikator do `provider_id/model_id`. Na przykład, użycie [OpenCode Zen](https://opencode.ai/docs/zen) , przestrzeganie `opencode/gpt-5.1-codex` dla Kodeksu GPT 5.1. Jeśli skonfigurowałeś \[dostawcę zwykłegogo\] (./providers#custom), `provider_id` jest kluczem z części `provider` twojej konfiguracji, a `model_id` jest kluczem z `provider.models`. * * * [Skonfiguruj modele](https://opencode.ai/docs/pl/models/#skonfiguruj-modele) ----------------------------------------------------------------------------- Można globalnie skorzystać z opcji modelu poprzez plik config. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} Tutaj konfigurujemy urządzenia globalne dla dwóch modeli: `gpt-5` w przypadku dostępu za pośrednictwem dostawcy `openai` i `claude-sonnet-4-20250514` w przypadku dostępu za pośrednictwem dostawcy `anthropic`. Wbudowane nazwy dostawców i modele można znaleźć na [Models.dev](https://models.dev/) . Można także skorzystać z opcji dla dowolnych agentów, których używa się. Konfiguracja agenta jest dostępna jako opcja globalna. [Dowiedz się więcej](https://opencode.ai/docs/agents/#additional) . Można również zastosować alternatywne warianty, które wykluczają. Warianty konfiguracji ustawień konfiguracyjnych dla tego samego modelu bez tworzenia duplikatów wpisów: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [Warianty](https://opencode.ai/docs/pl/models/#warianty) --------------------------------------------------------- Wiele modeli obsługuje wiele wariantów lub różnych wybranych. opencode jest dostarczany z podstawowymi wariantami wariantów dla dostawców. ### [Wbudowane warianty](https://opencode.ai/docs/pl/models/#wbudowane-warianty) opencode jest dostarczany z domyślnymi wariantami dla wielu dostawców: **Antropiczny**: * `high` – Wysoki budżet na przemyślenie (domyślnie) * `max` - Maksymalny budżet na myślenie **OpenAI**: Różni się zależnością od modelu, ale mniej więcej: * `none` – Brak uzasadnienia * `minimal` - Minimalny wysiłek rozumowania * `low` - Niewielki wysiłek w zakresie rozumowania * `medium` – Średni wysiłek rozumowania * `high` - Duży wysiłek w zakresie rozumowania * `xhigh` - Bardzo duży wysiłek w zakresie rozumowania **Google**: * `low` — Mniejszy nakład pracy/budżet tokena * `high` — Większy nakład pracy/budżet tokena ### [Warianty niestandardowe](https://opencode.ai/docs/pl/models/#warianty-niestandardowe) Można uwzględnić warianty lub dodać własne: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [Przełączanie wariantów](https://opencode.ai/docs/pl/models/#prze%C5%82%C4%85czanie-wariant%C3%B3w) Naciśnij klawisza `variant_cycle`, aby szybko przełączać się między wariantami. [Dowiedz się więcej](https://opencode.ai/docs/keybinds) . * * * [Ładowanie modeli](https://opencode.ai/docs/pl/models/#%C5%82adowanie-modeli) ------------------------------------------------------------------------------ Po uruchomieniu opencode sprawdzanie modeli w następującej kolejności: 1. Flaga wiersza autora `--model` lub `-m`. Format jest taki sam jak w pliku konfiguracyjnym: `provider_id/model_id`. 2. Lista modeli w konstrukcji opencode. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} Sformatuj tutaj na `provider/model`. 3. Ostatni używany model. 4. Pierwszy model sterujący priorytetem wewnętrznym. --- # 模型 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/models/#_top) 模型 == 配置 LLM 提供商和模型。 OpenCode 使用 [AI SDK](https://ai-sdk.dev/) 和 [Models.dev](https://models.dev/) 支持 **75+ LLM 提供商**,并支持运行本地模型。 * * * [提供商](https://opencode.ai/docs/zh-cn/models/#%E6%8F%90%E4%BE%9B%E5%95%86) -------------------------------------------------------------------------- 大多数热门提供商已默认预加载。如果你通过 `/connect` 命令添加了提供商的凭据,它们将在你启动 OpenCode 时自动可用。 了解更多关于[提供商](https://opencode.ai/docs/providers) 的信息。 * * * [选择模型](https://opencode.ai/docs/zh-cn/models/#%E9%80%89%E6%8B%A9%E6%A8%A1%E5%9E%8B) ------------------------------------------------------------------------------------ 配置好提供商后,你可以通过输入以下命令来选择想要使用的模型: /models * * * [推荐模型](https://opencode.ai/docs/zh-cn/models/#%E6%8E%A8%E8%8D%90%E6%A8%A1%E5%9E%8B) ------------------------------------------------------------------------------------ 市面上有非常多的模型,每周都有新模型发布。 然而,真正擅长代码生成和工具调用的模型只有少数几个。 以下是与 OpenCode 配合良好的几个模型,排名不分先后(此列表并非详尽无遗,也不一定是最新的): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [设置默认模型](https://opencode.ai/docs/zh-cn/models/#%E8%AE%BE%E7%BD%AE%E9%BB%98%E8%AE%A4%E6%A8%A1%E5%9E%8B) -------------------------------------------------------------------------------------------------------- 要将某个模型设为默认模型,可以在 OpenCode 配置中设置 `model` 字段。 { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} 这里完整的 ID 格式为 `provider_id/model_id`。例如,如果你使用 [OpenCode Zen](https://opencode.ai/docs/zen) ,则 GPT 5.1 Codex 对应的值为 `opencode/gpt-5.1-codex`。 如果你配置了[自定义提供商](https://opencode.ai/docs/providers#custom) ,`provider_id` 是配置中 `provider` 部分的键名,`model_id` 是 `provider.models` 中的键名。 * * * [配置模型](https://opencode.ai/docs/zh-cn/models/#%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B) ------------------------------------------------------------------------------------ 你可以通过配置文件全局配置模型的选项。 { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} 这里我们为两个内置模型配置了全局设置:通过 `openai` 提供商访问的 `gpt-5`,以及通过 `anthropic` 提供商访问的 `claude-sonnet-4-20250514`。 内置的提供商和模型名称可以在 [Models.dev](https://models.dev/) 上查阅。 你还可以为使用中的任何代理配置这些选项。代理配置会覆盖此处的全局选项。[了解更多](https://opencode.ai/docs/agents/#additional) 。 你也可以定义扩展内置变体的自定义变体。变体允许你为同一个模型配置不同的设置,而无需创建重复的条目: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [变体](https://opencode.ai/docs/zh-cn/models/#%E5%8F%98%E4%BD%93) ---------------------------------------------------------------- 许多模型支持具有不同配置的多种变体。OpenCode 为热门提供商内置了默认变体。 ### [内置变体](https://opencode.ai/docs/zh-cn/models/#%E5%86%85%E7%BD%AE%E5%8F%98%E4%BD%93) OpenCode 为许多提供商提供了默认变体: **Anthropic**: * `high` - 高思考预算(默认) * `max` - 最大思考预算 **OpenAI**: 因模型而异,但大致如下: * `none` - 无推理 * `minimal` - 极少推理 * `low` - 低推理 * `medium` - 中等推理 * `high` - 高推理 * `xhigh` - 超高推理 **Google**: * `low` - 较低推理/Token 预算 * `high` - 较高推理/Token 预算 ### [自定义变体](https://opencode.ai/docs/zh-cn/models/#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8F%98%E4%BD%93) 你可以覆盖现有变体或添加自己的变体: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [切换变体](https://opencode.ai/docs/zh-cn/models/#%E5%88%87%E6%8D%A2%E5%8F%98%E4%BD%93) 使用快捷键 `variant_cycle` 可以快速在变体之间切换。[了解更多](https://opencode.ai/docs/keybinds) 。 * * * [加载模型](https://opencode.ai/docs/zh-cn/models/#%E5%8A%A0%E8%BD%BD%E6%A8%A1%E5%9E%8B) ------------------------------------------------------------------------------------ OpenCode 启动时,会按以下优先顺序加载模型: 1. `--model` 或 `-m` 命令行标志。格式与配置文件中相同:`provider_id/model_id`。 2. OpenCode 配置中的 model 字段。 { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} 格式为 `provider/model`。 3. 上次使用的模型。 4. 按内部优先级排列的第一个可用模型。 --- # النماذج | OpenCode [تخطَّ إلى المحتوى](https://opencode.ai/docs/ar/models/#_top) النماذج ======= تهيئة مزوّد LLM والنموذج. يستخدم OpenCode كلاً من [AI SDK](https://ai-sdk.dev/) و[Models.dev](https://models.dev/) لدعم **أكثر من 75 مزوّداً لنماذج LLM**، كما يدعم تشغيل النماذج محلياً. * * * [المزوّدون](https://opencode.ai/docs/ar/models/#%D8%A7%D9%84%D9%85%D8%B2%D9%88%D9%91%D8%AF%D9%88%D9%86) -------------------------------------------------------------------------------------------------------- أكثر المزوّدين شيوعاً مُحمَّلون مسبقاً افتراضياً. إذا أضفت بيانات اعتماد أحد المزوّدين عبر الأمر `/connect` فستكون متاحة عند تشغيل OpenCode. تعرّف على المزيد حول [المزوّدين](https://opencode.ai/docs/providers) . * * * [اختر نموذجاً](https://opencode.ai/docs/ar/models/#%D8%A7%D8%AE%D8%AA%D8%B1-%D9%86%D9%85%D9%88%D8%B0%D8%AC%D8%A7%D9%8B) ------------------------------------------------------------------------------------------------------------------------ بعد تهيئة المزوّد يمكنك اختيار النموذج الذي تريده بكتابة: /models * * * [النماذج الموصى بها](https://opencode.ai/docs/ar/models/#%D8%A7%D9%84%D9%86%D9%85%D8%A7%D8%B0%D8%AC-%D8%A7%D9%84%D9%85%D9%88%D8%B5%D9%89-%D8%A8%D9%87%D8%A7) ------------------------------------------------------------------------------------------------------------------------------------------------------------- هناك الكثير من النماذج المتاحة، وتظهر نماذج جديدة كل أسبوع. لكن القليل منها فقط يكون جيداً في كلٍ من توليد الشيفرة واستدعاء الأدوات. فيما يلي عدة نماذج تعمل جيداً مع OpenCode، دون ترتيب معيّن. (هذه ليست قائمة شاملة وقد لا تكون محدَّثة دائماً): * GPT 5.2 * GPT 5.1 Codex * Claude Opus 4.5 * Claude Sonnet 4.5 * Minimax M2.1 * Gemini 3 Pro * * * [تعيين الافتراضي](https://opencode.ai/docs/ar/models/#%D8%AA%D8%B9%D9%8A%D9%8A%D9%86-%D8%A7%D9%84%D8%A7%D9%81%D8%AA%D8%B1%D8%A7%D8%B6%D9%8A) --------------------------------------------------------------------------------------------------------------------------------------------- لتعيين أحد هذه النماذج كنموذج افتراضي، يمكنك ضبط المفتاح `model` في ملف إعدادات OpenCode. { "$schema": "https://opencode.ai/config.json", "model": "lmstudio/google/gemma-3n-e4b"} المعرّف الكامل هنا يكون بالشكل `provider_id/model_id`. على سبيل المثال، إذا كنت تستخدم [OpenCode Zen](https://opencode.ai/docs/zen) فستستخدم `opencode/gpt-5.1-codex` لنموذج GPT 5.1 Codex. إذا كنت قد هيّأت [مزوّداً مخصّصاً](https://opencode.ai/docs/providers#custom) ، فإن `provider_id` هو المفتاح الموجود ضمن قسم `provider` في إعداداتك، و`model_id` هو المفتاح الموجود ضمن `provider.models`. * * * [إعداد النماذج](https://opencode.ai/docs/ar/models/#%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF-%D8%A7%D9%84%D9%86%D9%85%D8%A7%D8%B0%D8%AC) ------------------------------------------------------------------------------------------------------------------------------- يمكنك ضبط خيارات النموذج على مستوى عام عبر ملف الإعدادات. { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": ["reasoning.encrypted_content"], }, }, }, }, "anthropic": { "models": { "claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000, }, }, }, }, }, },} هنا نقوم بضبط إعدادات عامة لنموذجين مدمجين: `gpt-5` عند الوصول إليه عبر مزوّد `openai`، و`claude-sonnet-4-20250514` عند الوصول إليه عبر مزوّد `anthropic`. يمكن العثور على أسماء المزوّدين والنماذج المدمجة على [Models.dev](https://models.dev/) . يمكنك أيضاً ضبط هذه الخيارات لأي وكلاء تستخدمهم. تتجاوز إعدادات الوكيل أي خيارات عامة هنا. [اعرف المزيد](https://opencode.ai/docs/agents/#additional) . كما يمكنك تعريف متغيّرات مخصّصة تُوسّع المتغيّرات المدمجة. تتيح لك المتغيّرات ضبط إعدادات مختلفة للنموذج نفسه دون إنشاء إدخالات مكرّرة: { "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "models": { "gpt-5": { "variants": { "high": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", }, "low": { "reasoningEffort": "low", "textVerbosity": "low", "reasoningSummary": "auto", }, }, }, }, }, },} * * * [المتغيّرات](https://opencode.ai/docs/ar/models/#%D8%A7%D9%84%D9%85%D8%AA%D8%BA%D9%8A%D9%91%D8%B1%D8%A7%D8%AA) --------------------------------------------------------------------------------------------------------------- تدعم العديد من النماذج عدة متغيّرات بإعدادات مختلفة. يأتي OpenCode مع متغيّرات افتراضية مدمجة للمزوّدين الشائعين. ### [المتغيّرات المدمجة](https://opencode.ai/docs/ar/models/#%D8%A7%D9%84%D9%85%D8%AA%D8%BA%D9%8A%D9%91%D8%B1%D8%A7%D8%AA-%D8%A7%D9%84%D9%85%D8%AF%D9%85%D8%AC%D8%A9) يأتي OpenCode مع متغيّرات افتراضية لعدد كبير من المزوّدين: **Anthropic**: * `high` - ميزانية تفكير مرتفعة (الافتراضي) * `max` - أقصى ميزانية تفكير **OpenAI**: تختلف حسب النموذج، لكن بشكل عام: * `none` - بدون استدلال * `minimal` - أقل جهد للاستدلال * `low` - جهد استدلال منخفض * `medium` - جهد استدلال متوسط * `high` - جهد استدلال مرتفع * `xhigh` - جهد استدلال مرتفع جداً **Google**: * `low` - جهد/ميزانية رموز أقل * `high` - جهد/ميزانية رموز أعلى ### [متغيّرات مخصّصة](https://opencode.ai/docs/ar/models/#%D9%85%D8%AA%D8%BA%D9%8A%D9%91%D8%B1%D8%A7%D8%AA-%D9%85%D8%AE%D8%B5%D9%91%D8%B5%D8%A9) يمكنك تجاوز المتغيّرات الموجودة أو إضافة متغيّراتك الخاصة: { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "models": { "gpt-5": { "variants": { "thinking": { "reasoningEffort": "high", "textVerbosity": "low", }, "fast": { "disabled": true, }, }, }, }, }, },} ### [التبديل بين المتغيّرات](https://opencode.ai/docs/ar/models/#%D8%A7%D9%84%D8%AA%D8%A8%D8%AF%D9%8A%D9%84-%D8%A8%D9%8A%D9%86-%D8%A7%D9%84%D9%85%D8%AA%D8%BA%D9%8A%D9%91%D8%B1%D8%A7%D8%AA) استخدم اختصار لوحة المفاتيح `variant_cycle` للتبديل بسرعة بين المتغيّرات. [اعرف المزيد](https://opencode.ai/docs/keybinds) . * * * [تحميل النماذج](https://opencode.ai/docs/ar/models/#%D8%AA%D8%AD%D9%85%D9%8A%D9%84-%D8%A7%D9%84%D9%86%D9%85%D8%A7%D8%B0%D8%AC) ------------------------------------------------------------------------------------------------------------------------------- عند بدء تشغيل OpenCode، يتحقق من النماذج وفق ترتيب الأولوية التالي: 1. خيار CLI `--model` أو `-m`. الصيغة هي نفسها الموجودة في ملف الإعدادات: `provider_id/model_id`. 2. قائمة النماذج في إعدادات OpenCode. { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-20250514"} الصيغة هنا هي `provider/model`. 3. آخر نموذج تم استخدامه. 4. أول نموذج وفق أولوية داخلية. --- # プラグイン | 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` 配列は無視されます。 --- # GitHub | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/github/#_top) GitHub ====== GitHub issue와 pull request에서 OpenCode를 사용하세요. OpenCode는 GitHub 워크플로와 통합됩니다. 댓글에 `/opencode` 또는 `/oc`를 mention하면 OpenCode가 GitHub Actions runner 안에서 작업을 실행합니다. * * * [기능](https://opencode.ai/docs/ko/github/#%EA%B8%B0%EB%8A%A5) ------------------------------------------------------------- * **Issue triage**: OpenCode에게 issue를 분석하고 내용을 설명하도록 요청할 수 있습니다. * **Fix and implement**: OpenCode에게 issue 수정이나 기능 구현을 요청할 수 있습니다. 새 branch에서 작업한 뒤 변경 사항을 담은 PR을 생성합니다. * **Secure**: OpenCode는 GitHub runner 내부에서 실행됩니다. * * * [설치](https://opencode.ai/docs/ko/github/#%EC%84%A4%EC%B9%98) ------------------------------------------------------------- GitHub repo에 연결된 프로젝트에서 아래 명령을 실행하세요. opencode github install 이 명령은 GitHub app 설치, workflow 생성, secrets 설정 과정을 안내합니다. * * * ### [Manual Setup](https://opencode.ai/docs/ko/github/#manual-setup) 원하면 수동으로도 설정할 수 있습니다. 1. **Install the GitHub app** [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent) 로 이동하세요. 대상 repo에 app이 설치되어 있는지 확인하세요. 2. **Add the workflow** 아래 workflow 파일을 repo의 `.github/workflows/opencode.yml`에 추가하세요. `env`에는 필요한 API key를 넣고, `model`은 환경에 맞게 설정하세요. name: opencode on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: opencode: if: | contains(github.event.comment.body, '/oc') || contains(github.event.comment.body, '/opencode') runs-on: ubuntu-latest permissions: id-token: write steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 1 persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 # share: true # github_token: xxxx 3. **Store the API keys in secrets** 조직 또는 프로젝트 **Settings**에서 왼쪽의 **Secrets and variables**를 펼친 뒤 **Actions**를 선택하세요. 필요한 API key를 추가하면 됩니다. * * * [구성](https://opencode.ai/docs/ko/github/#%EA%B5%AC%EC%84%B1) ------------------------------------------------------------- * `model`: OpenCode에서 사용할 model입니다. `provider/model` 형식이며 **필수**입니다. * `agent`: 사용할 agent입니다. primary agent여야 합니다. 찾지 못하면 config의 `default_agent`를 사용하고, 그것도 없으면 `"build"`로 fallback합니다. * `share`: OpenCode 세션 공유 여부입니다. public repo에서는 기본값이 **true**입니다. * `prompt`: 기본 동작을 override하는 선택형 custom prompt입니다. OpenCode의 요청 처리 방식을 조정할 때 사용합니다. * `token`: 댓글 생성, 커밋, PR 생성 같은 작업을 수행할 때 사용하는 선택형 GitHub access token입니다. 기본적으로 OpenCode는 OpenCode GitHub App의 installation access token을 사용하므로, 커밋/댓글/PR 작성 주체가 app으로 표시됩니다. 또는 OpenCode GitHub App을 설치하지 않고도 GitHub Action runner의 [기본 제공 `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) 을 사용할 수 있습니다. 이 경우 workflow에 필요한 permission을 반드시 부여하세요. permissions: id-token: write contents: write pull-requests: write issues: write 필요하면 [personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) (PAT)도 사용할 수 있습니다. * * * [Supported Events](https://opencode.ai/docs/ko/github/#supported-events) ------------------------------------------------------------------------- OpenCode는 아래 GitHub event로 트리거할 수 있습니다. | Event Type | Triggered By | Details | | --- | --- | --- | | `issue_comment` | issue 또는 PR 댓글 | 댓글에 `/opencode` 또는 `/oc`를 mention하세요. OpenCode가 맥락을 읽고 branch 생성, PR 생성, 답변을 수행할 수 있습니다. | | `pull_request_review_comment` | PR의 특정 코드 줄 댓글 | 코드 리뷰 중 `/opencode` 또는 `/oc`를 mention하세요. OpenCode가 파일 경로, 라인 번호, diff 맥락을 받습니다. | | `issues` | issue 생성 또는 수정 | issue가 생성/수정될 때 OpenCode를 자동 트리거합니다. `prompt` 입력이 필요합니다. | | `pull_request` | PR 생성 또는 업데이트 | PR open/synchronize/reopen 시 OpenCode를 자동 트리거합니다. 자동 리뷰에 유용합니다. | | `schedule` | cron 기반 스케줄 | 스케줄에 따라 OpenCode를 실행합니다. `prompt` 입력이 필요합니다. 출력은 로그와 PR로 남습니다(issue 댓글 대상 없음). | | `workflow_dispatch` | GitHub UI에서 수동 실행 | Actions 탭에서 필요 시 OpenCode를 실행합니다. `prompt` 입력이 필요하며 출력은 로그와 PR로 남습니다. | ### [Schedule Example](https://opencode.ai/docs/ko/github/#schedule-example) 자동화 작업을 위해 스케줄 기반으로 OpenCode를 실행할 수 있습니다. name: Scheduled OpenCode Task on: schedule: - cron: "0 9 * * 1" # Every Monday at 9am UTC jobs: opencode: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Checkout repository uses: actions/checkout@v6 with: persist-credentials: false - name: Run OpenCode uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review the codebase for any TODO comments and create a summary. If you find issues worth addressing, open an issue to track them. schedule event는 지시를 추출할 댓글이 없기 때문에 `prompt` 입력이 **필수**입니다. 또한 schedule workflow는 permission 체크용 사용자 맥락 없이 실행되므로, OpenCode가 branch나 PR을 만들게 하려면 `contents: write`와 `pull-requests: write`를 부여해야 합니다. * * * ### [Pull Request Example](https://opencode.ai/docs/ko/github/#pull-request-example) PR이 열리거나 업데이트될 때 자동 리뷰를 수행할 수 있습니다. name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: id-token: write contents: read pull-requests: read issues: read steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-4-20250514 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements `pull_request` event에서 `prompt`를 지정하지 않으면 OpenCode는 pull request 리뷰를 기본 동작으로 수행합니다. * * * ### [Issues Triage Example](https://opencode.ai/docs/ko/github/#issues-triage-example) 새로운 issue를 자동으로 triage할 수 있습니다. 아래 예시는 스팸을 줄이기 위해 계정 생성 후 30일 이상인 사용자만 대상으로 필터링합니다. name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest permissions: id-token: write contents: write pull-requests: write issues: write steps: - name: Check account age id: check uses: actions/github-script@v7 with: script: | const user = await github.rest.users.getByUsername({ username: context.payload.issue.user.login }); const created = new Date(user.data.created_at); const days = (Date.now() - created) / (1000 * 60 * 60 * 24); return days >= 30; result-encoding: string - uses: actions/checkout@v6 if: steps.check.outputs.result == 'true' with: persist-credentials: false - uses: anomalyco/opencode/github@latest if: steps.check.outputs.result == 'true' env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} with: model: anthropic/claude-sonnet-4-20250514 prompt: | Review this issue. If there's a clear fix or relevant docs: - Provide documentation links - Add error handling guidance for code examples Otherwise, do not comment. `issues` event 역시 지시를 추출할 댓글이 없기 때문에 `prompt` 입력이 **필수**입니다. * * * [Custom prompts](https://opencode.ai/docs/ko/github/#custom-prompts) --------------------------------------------------------------------- 기본 prompt를 override해 워크플로에 맞게 OpenCode 동작을 커스터마이즈할 수 있습니다. - uses: anomalyco/opencode/github@latest with: model: anthropic/claude-sonnet-4-5 prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements 이 방식은 프로젝트별 리뷰 기준, 코딩 표준, 중점 점검 항목을 강제할 때 유용합니다. * * * [예시](https://opencode.ai/docs/ko/github/#%EC%98%88%EC%8B%9C) ------------------------------------------------------------- 아래는 GitHub에서 OpenCode를 활용하는 대표 예시입니다. * **Issue 설명 요청** GitHub issue에 아래 댓글을 남기세요. /opencode explain this issue OpenCode는 전체 스레드와 모든 댓글을 읽고 명확한 설명으로 답변합니다. * **Issue 수정 요청** GitHub issue에서 아래처럼 요청하세요. /opencode fix this OpenCode가 새 branch를 만들고 변경을 구현한 뒤, 변경 사항이 담긴 PR을 생성합니다. * **PR 리뷰 중 변경 요청** GitHub PR에 아래 댓글을 남기세요. Delete the attachment from S3 when the note is removed /oc OpenCode가 요청한 변경을 구현하고 같은 PR에 커밋합니다. * **특정 코드 줄 리뷰 요청** PR의 “Files” 탭에서 코드 줄에 직접 댓글을 남기세요. OpenCode는 파일, 줄 번호, diff 맥락을 자동으로 인식해 더 정확한 응답을 제공합니다. [Comment on specific lines in Files tab]/oc add error handling here 특정 줄 댓글에서는 OpenCode가 다음 정보를 함께 받습니다. * 검토 중인 정확한 파일 * 해당 코드 줄 * 주변 diff 맥락 * 라인 번호 정보 따라서 파일 경로나 라인 번호를 직접 적지 않아도 더 정밀하게 요청할 수 있습니다. --- # MCP 服务器 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/mcp-servers/#_top) MCP 服务器 ======= 添加本地和远程 MCP 工具。 你可以通过 _Model Context Protocol_(MCP)为 OpenCode 添加外部工具。OpenCode 同时支持本地和远程服务器。 添加后,MCP 工具会自动与内置工具一起提供给 LLM 使用。 * * * #### [注意事项](https://opencode.ai/docs/zh-cn/mcp-servers/#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9) 使用 MCP 服务器时,它会占用上下文空间。如果你启用了大量工具,上下文消耗会迅速增加。因此,我们建议谨慎选择要使用的 MCP 服务器。 某些 MCP 服务器(例如 GitHub MCP 服务器)往往会消耗大量 Token,很容易超出上下文限制。 * * * [启用](https://opencode.ai/docs/zh-cn/mcp-servers/#%E5%90%AF%E7%94%A8) --------------------------------------------------------------------- 你可以在 [OpenCode 配置](https://opencode.ai/docs/config/) 的 `mcp` 字段下定义 MCP 服务器。为每个 MCP 指定一个唯一的名称,在提示词中可以通过该名称来引用对应的 MCP。 { "$schema": "https://opencode.ai/config.json", "mcp": { "name-of-mcp-server": { // ... "enabled": true, }, "name-of-other-mcp-server": { // ... }, },} 你也可以将 `enabled` 设置为 `false` 来禁用某个服务器。当你想临时禁用某个服务器而不将其从配置中移除时,这个选项非常有用。 * * * ### [覆盖远程默认值](https://opencode.ai/docs/zh-cn/mcp-servers/#%E8%A6%86%E7%9B%96%E8%BF%9C%E7%A8%8B%E9%BB%98%E8%AE%A4%E5%80%BC) 组织可以通过其 `.well-known/opencode` 端点提供默认的 MCP 服务器。这些服务器可能默认处于禁用状态,允许用户按需启用。 要启用组织远程配置中的某个服务器,请在本地配置中添加该服务器并设置 `enabled: true`: { "$schema": "https://opencode.ai/config.json", "mcp": { "jira": { "type": "remote", "url": "https://jira.example.com/mcp", "enabled": true } }} 本地配置值会覆盖远程默认值。详情请参阅[配置优先级](https://opencode.ai/docs/config#precedence-order) 。 * * * [本地](https://opencode.ai/docs/zh-cn/mcp-servers/#%E6%9C%AC%E5%9C%B0) --------------------------------------------------------------------- 通过在 MCP 对象中将 `type` 设置为 `"local"` 来添加本地 MCP 服务器。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-local-mcp-server": { "type": "local", // Or ["bun", "x", "my-mcp-command"] "command": ["npx", "-y", "my-mcp-command"], "enabled": true, "environment": { "MY_ENV_VAR": "my_env_var_value", }, }, },} `command` 用于指定本地 MCP 服务器的启动命令。你还可以传入一组环境变量。 例如,以下是添加测试用的 [`@modelcontextprotocol/server-everything`](https://www.npmjs.com/package/@modelcontextprotocol/server-everything) MCP 服务器的方法。 { "$schema": "https://opencode.ai/config.json", "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"], }, },} 要使用它,可以在提示词中添加 `use the mcp_everything tool`。 use the mcp_everything tool to add the number 3 and 4 * * * #### [选项](https://opencode.ai/docs/zh-cn/mcp-servers/#%E9%80%89%E9%A1%B9) 以下是配置本地 MCP 服务器的所有选项。 | 选项 | 类型 | 必填 | 描述 | | --- | --- | --- | --- | | `type` | 字符串 | 是 | MCP 服务器连接类型,必须为 `"local"`。 | | `command` | 数组 | 是 | 运行 MCP 服务器的命令及参数。 | | `environment` | 对象 | | 运行服务器时设置的环境变量。 | | `enabled` | 布尔值 | | 启动时启用或禁用该 MCP 服务器。 | | `timeout` | 数字 | | 从 MCP 服务器获取工具的超时时间(毫秒)。默认为 5000(即 5 秒)。 | * * * [远程](https://opencode.ai/docs/zh-cn/mcp-servers/#%E8%BF%9C%E7%A8%8B) --------------------------------------------------------------------- 通过将 `type` 设置为 `"remote"` 来添加远程 MCP 服务器。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://my-mcp-server.com", "enabled": true, "headers": { "Authorization": "Bearer MY_API_KEY" } } }} `url` 是远程 MCP 服务器的地址,通过 `headers` 选项可以传入一组请求头。 * * * #### [选项](https://opencode.ai/docs/zh-cn/mcp-servers/#%E9%80%89%E9%A1%B9-1) | 选项 | 类型 | 必填 | 描述 | | --- | --- | --- | --- | | `type` | 字符串 | 是 | MCP 服务器连接类型,必须为 `"remote"`。 | | `url` | 字符串 | 是 | 远程 MCP 服务器的 URL。 | | `enabled` | 布尔值 | | 启动时启用或禁用该 MCP 服务器。 | | `headers` | 对象 | | 随请求发送的请求头。 | | `oauth` | 对象 | | OAuth 身份验证配置。详见下方 [OAuth](https://opencode.ai/docs/zh-cn/mcp-servers/#oauth)
部分。 | | `timeout` | 数字 | | 从 MCP 服务器获取工具的超时时间(毫秒)。默认为 5000(即 5 秒)。 | * * * [OAuth](https://opencode.ai/docs/zh-cn/mcp-servers/#oauth) ----------------------------------------------------------- OpenCode 会自动处理远程 MCP 服务器的 OAuth 身份验证。当服务器需要身份验证时,OpenCode 将: 1. 检测 401 响应并启动 OAuth 流程 2. 在服务器支持的情况下使用**动态客户端注册(RFC 7591)** 3. 安全地存储 Token 以供后续请求使用 * * * ### [自动认证](https://opencode.ai/docs/zh-cn/mcp-servers/#%E8%87%AA%E5%8A%A8%E8%AE%A4%E8%AF%81) 对于大多数支持 OAuth 的 MCP 服务器,无需特殊配置。只需配置远程服务器即可: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } }} 如果服务器需要身份验证,OpenCode 会在你首次使用时提示你进行认证。你也可以使用 `opencode mcp auth ` [手动触发认证流程](https://opencode.ai/docs/zh-cn/mcp-servers/#authenticating) 。 * * * ### [预注册](https://opencode.ai/docs/zh-cn/mcp-servers/#%E9%A2%84%E6%B3%A8%E5%86%8C) 如果你已经从 MCP 服务器提供商处获得了客户端凭据,可以直接配置: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MY_MCP_CLIENT_ID}", "clientSecret": "{env:MY_MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } }} * * * ### [身份验证](https://opencode.ai/docs/zh-cn/mcp-servers/#%E8%BA%AB%E4%BB%BD%E9%AA%8C%E8%AF%81) 你可以手动触发身份验证或管理凭据。 对特定 MCP 服务器进行身份验证: opencode mcp auth my-oauth-server 列出所有 MCP 服务器及其认证状态: opencode mcp list 删除已存储的凭据: opencode mcp logout my-oauth-server `mcp auth` 命令会打开浏览器进行授权。授权完成后,OpenCode 会将 Token 安全地存储在 `~/.local/share/opencode/mcp-auth.json` 中。 * * * #### [禁用 OAuth](https://opencode.ai/docs/zh-cn/mcp-servers/#%E7%A6%81%E7%94%A8-oauth) 如果你想为某个服务器禁用自动 OAuth(例如,该服务器使用 API 密钥而非 OAuth),可以将 `oauth` 设置为 `false`: { "$schema": "https://opencode.ai/config.json", "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } }} * * * #### [OAuth 选项](https://opencode.ai/docs/zh-cn/mcp-servers/#oauth-%E9%80%89%E9%A1%B9) | 选项 | 类型 | 描述 | | --- | --- | --- | | `oauth` | 对象 \| `false` | OAuth 配置对象,或设为 `false` 以禁用 OAuth 自动检测。 | | `clientId` | 字符串 | OAuth 客户端 ID。如果未提供,将尝试动态客户端注册。 | | `clientSecret` | 字符串 | OAuth 客户端密钥(如果授权服务器要求提供)。 | | `scope` | 字符串 | 授权时请求的 OAuth 作用域。 | #### [调试](https://opencode.ai/docs/zh-cn/mcp-servers/#%E8%B0%83%E8%AF%95) 如果远程 MCP 服务器身份验证失败,你可以通过以下方式诊断问题: # 查看所有支持 OAuth 的服务器的认证状态opencode mcp auth list # 调试特定服务器的连接和 OAuth 流程opencode mcp debug my-oauth-server `mcp debug` 命令会显示当前认证状态、测试 HTTP 连接,并尝试执行 OAuth 发现流程。 * * * [管理](https://opencode.ai/docs/zh-cn/mcp-servers/#%E7%AE%A1%E7%90%86) --------------------------------------------------------------------- 你的 MCP 在 OpenCode 中作为工具使用,与内置工具并列。因此,你可以像管理其他工具一样,通过 OpenCode 配置来管理它们。 * * * ### [全局](https://opencode.ai/docs/zh-cn/mcp-servers/#%E5%85%A8%E5%B1%80) 你可以全局启用或禁用 MCP 工具。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp-foo": false }} 也可以使用 glob 模式来禁用所有匹配的 MCP。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "my-mcp-command-foo"] }, "my-mcp-bar": { "type": "local", "command": ["bun", "x", "my-mcp-command-bar"] } }, "tools": { "my-mcp*": false }} 这里使用 glob 模式 `my-mcp*` 来禁用所有 MCP。 * * * ### [按代理配置](https://opencode.ai/docs/zh-cn/mcp-servers/#%E6%8C%89%E4%BB%A3%E7%90%86%E9%85%8D%E7%BD%AE) 如果你有大量 MCP 服务器,可以选择全局禁用它们,然后仅在特定代理中启用。具体做法: 1. 全局禁用该工具。 2. 在[代理配置](https://opencode.ai/docs/agents#tools) 中,将 MCP 服务器作为工具启用。 { "$schema": "https://opencode.ai/config.json", "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } }} * * * #### [Glob 模式](https://opencode.ai/docs/zh-cn/mcp-servers/#glob-%E6%A8%A1%E5%BC%8F) glob 模式使用简单的正则通配符规则: * `*` 匹配零个或多个任意字符(例如,`"my-mcp*"` 匹配 `my-mcp_search`、`my-mcp_list` 等) * `?` 匹配恰好一个字符 * 其他字符按字面值匹配 * * * [示例](https://opencode.ai/docs/zh-cn/mcp-servers/#%E7%A4%BA%E4%BE%8B) --------------------------------------------------------------------- 以下是一些常见 MCP 服务器的配置示例。如果你想记录其他服务器的用法,欢迎提交 PR。 * * * ### [Sentry](https://opencode.ai/docs/zh-cn/mcp-servers/#sentry) 添加 [Sentry MCP 服务器](https://mcp.sentry.dev/) 以与你的 Sentry 项目和问题进行交互。 { "$schema": "https://opencode.ai/config.json", "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } }} 添加配置后,使用 Sentry 进行身份验证: opencode mcp auth sentry 这会打开浏览器窗口完成 OAuth 流程,将 OpenCode 连接到你的 Sentry 账户。 认证完成后,你可以在提示词中使用 Sentry 工具来查询问题、项目和错误数据。 Show me the latest unresolved issues in my project. use sentry * * * ### [Context7](https://opencode.ai/docs/zh-cn/mcp-servers/#context7) 添加 [Context7 MCP 服务器](https://github.com/upstash/context7) 以搜索文档。 { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } }} 如果你注册了免费账户,可以使用 API 密钥来获得更高的速率限制。 { "$schema": "https://opencode.ai/config.json", "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } }} 这里假设你已经设置了 `CONTEXT7_API_KEY` 环境变量。 在提示词中添加 `use context7` 即可使用 Context7 MCP 服务器。 Configure a Cloudflare Worker script to cache JSON API responses for five minutes. use context7 你也可以在 [AGENTS.md](https://opencode.ai/docs/rules/) 中添加类似的规则。 When you need to search docs, use `context7` tools. * * * ### [Grep by Vercel](https://opencode.ai/docs/zh-cn/mcp-servers/#grep-by-vercel) 添加 [Grep by Vercel](https://grep.app/) MCP 服务器以搜索 GitHub 上的代码片段。 { "$schema": "https://opencode.ai/config.json", "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } }} 由于我们将 MCP 服务器命名为 `gh_grep`,你可以在提示词中添加 `use the gh_grep tool` 来让代理使用它。 What's the right way to set a custom domain in an SST Astro component? use the gh_grep tool 你也可以在 [AGENTS.md](https://opencode.ai/docs/rules/) 中添加类似的规则。 If you are unsure how to do something, use `gh_grep` to search code examples from GitHub. --- # 规则 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/rules/#_top) 规则 == 为 opencode 设置自定义指令。 您可以通过创建 `AGENTS.md` 文件来为 opencode 提供自定义指令。这类似于 Cursor 的规则功能。该文件包含的指令会被纳入 LLM 的上下文中,以便针对您的特定项目自定义其行为。 * * * [初始化](https://opencode.ai/docs/zh-cn/rules/#%E5%88%9D%E5%A7%8B%E5%8C%96) ------------------------------------------------------------------------- 要创建新的 `AGENTS.md` 文件,您可以在 opencode 中运行 `/init` 命令。 该命令会扫描您的项目及其所有内容,了解项目的用途,并据此生成一个 `AGENTS.md` 文件。这有助于 opencode 更好地导航您的项目。 如果您已有 `AGENTS.md` 文件,该命令会尝试在其基础上进行补充。 * * * [示例](https://opencode.ai/docs/zh-cn/rules/#%E7%A4%BA%E4%BE%8B) --------------------------------------------------------------- 您也可以手动创建此文件。以下是一些可以放入 `AGENTS.md` 文件中的内容示例。 # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.)- `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts)- `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled- Shared code goes in `packages/core/` with proper exports configuration- Functions go in `packages/functions/`- Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` 我们在这里添加了项目特定的指令,这些指令会在您的团队中共享。 * * * [类型](https://opencode.ai/docs/zh-cn/rules/#%E7%B1%BB%E5%9E%8B) --------------------------------------------------------------- opencode 还支持从多个位置读取 `AGENTS.md` 文件,不同的位置有不同的用途。 ### [项目级](https://opencode.ai/docs/zh-cn/rules/#%E9%A1%B9%E7%9B%AE%E7%BA%A7) 在项目根目录放置一个 `AGENTS.md` 文件,用于定义项目特定的规则。这些规则仅在您在该目录或其子目录中工作时生效。 ### [全局级](https://opencode.ai/docs/zh-cn/rules/#%E5%85%A8%E5%B1%80%E7%BA%A7) 您还可以在 `~/.config/opencode/AGENTS.md` 文件中设置全局规则。这些规则会应用于所有 opencode 会话。 由于该文件不会被提交到 Git 或与团队共享,我们建议用它来指定 LLM 应遵循的个人规则。 ### [Claude Code 兼容性](https://opencode.ai/docs/zh-cn/rules/#claude-code-%E5%85%BC%E5%AE%B9%E6%80%A7) 对于从 Claude Code 迁移过来的用户,OpenCode 支持 Claude Code 的文件约定作为回退方案: * **项目规则**:项目目录中的 `CLAUDE.md`(在没有 `AGENTS.md` 的情况下使用) * **全局规则**:`~/.claude/CLAUDE.md`(在没有 `~/.config/opencode/AGENTS.md` 的情况下使用) * **技能**:`~/.claude/skills/` — 详情请参阅[代理技能](https://opencode.ai/docs/skills/) 要禁用 Claude Code 兼容性,请设置以下环境变量之一: export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude supportexport OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable only ~/.claude/CLAUDE.mdexport OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # Disable only .claude/skills * * * [优先级](https://opencode.ai/docs/zh-cn/rules/#%E4%BC%98%E5%85%88%E7%BA%A7) ------------------------------------------------------------------------- 当 opencode 启动时,它会按以下顺序查找规则文件: 1. **本地文件**,从当前目录向上遍历(`AGENTS.md`、`CLAUDE.md`) 2. **全局文件**,位于 `~/.config/opencode/AGENTS.md` 3. **Claude Code 文件**,位于 `~/.claude/CLAUDE.md`(除非已禁用) 在每个类别中,第一个匹配的文件优先。例如,如果您同时拥有 `AGENTS.md` 和 `CLAUDE.md`,则只会使用 `AGENTS.md`。同样,`~/.config/opencode/AGENTS.md` 优先于 `~/.claude/CLAUDE.md`。 * * * [自定义指令](https://opencode.ai/docs/zh-cn/rules/#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%87%E4%BB%A4) --------------------------------------------------------------------------------------------- 您可以在 `opencode.json` 或全局配置文件 `~/.config/opencode/opencode.json` 中指定自定义指令文件。这允许您和团队复用现有规则,而无需将它们复制到 AGENTS.md 中。 示例: { "$schema": "https://opencode.ai/config.json", "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]} 您还可以使用远程 URL 从网络加载指令。 { "$schema": "https://opencode.ai/config.json", "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]} 远程指令的获取超时时间为 5 秒。 所有指令文件都会与您的 `AGENTS.md` 文件合并。 * * * [引用外部文件](https://opencode.ai/docs/zh-cn/rules/#%E5%BC%95%E7%94%A8%E5%A4%96%E9%83%A8%E6%96%87%E4%BB%B6) ------------------------------------------------------------------------------------------------------- 虽然 opencode 不会自动解析 `AGENTS.md` 中的文件引用,但您可以通过以下两种方式实现类似的功能: ### [使用 opencode.json](https://opencode.ai/docs/zh-cn/rules/#%E4%BD%BF%E7%94%A8-opencodejson) 推荐的方式是使用 `opencode.json` 中的 `instructions` 字段: { "$schema": "https://opencode.ai/config.json", "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"]} ### [在 AGENTS.md 中手动指定](https://opencode.ai/docs/zh-cn/rules/#%E5%9C%A8-agentsmd-%E4%B8%AD%E6%89%8B%E5%8A%A8%E6%8C%87%E5%AE%9A) 您可以在 `AGENTS.md` 中提供明确的指令,教 opencode 读取外部文件。以下是一个实际示例: # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. They're relevant to the SPECIFIC task at hand. Instructions: - Do NOT preemptively load all references - use lazy loading based on actual need- When loaded, treat content as mandatory instructions that override defaults- Follow references recursively when needed ## Development Guidelines For TypeScript code style and best practices: @docs/typescript-guidelines.mdFor React component architecture and hooks patterns: @docs/react-patterns.mdFor REST API design and error handling: @docs/api-standards.mdFor testing strategies and coverage requirements: @test/testing-guidelines.md ## General Guidelines Read the following file immediately as it's relevant to all workflows: @rules/general-guidelines.md. 这种方式允许您: * 创建模块化、可复用的规则文件 * 通过符号链接或 Git 子模块在项目之间共享规则 * 保持 AGENTS.md 简洁,同时引用详细的指南 * 确保 opencode 仅在特定任务需要时才加载文件 --- # Umiejętności Agenta | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/skills/#_top) Umiejętności Agenta =================== Definiuj powtarzalne zachowania za pomocą definicji SKILL.md Umiejętności agenta pozwalają opencode odkryć instrukcje wielokrotnego użytku z repozytorium lub katalogu domowego. Umiejętności są ładowane na żądanie za pośrednictwem natywnego narzędzia `skill` — agenci widzą dostępne umiejętności i w razie potrzeby mogą załadować pełną zawartość. * * * [Lokalizacja plików](https://opencode.ai/docs/pl/skills/#lokalizacja-plik%C3%B3w) ---------------------------------------------------------------------------------- Utwórz jeden folder na nazwę umiejętności i umieść w nim `SKILL.md`. opencode przeszukuje te lokalizacje: * Project config: `.opencode/skills//SKILL.md` * Global config: `~/.config/opencode/skills//SKILL.md` * Project Claude-compatible: `.claude/skills//SKILL.md` * Global Claude-compatible: `~/.claude/skills//SKILL.md` * Project agent-compatible: `.agents/skills//SKILL.md` * Global agent-compatible: `~/.agents/skills//SKILL.md` * * * [Zrozumienie wykrywania](https://opencode.ai/docs/pl/skills/#zrozumienie-wykrywania) ------------------------------------------------------------------------------------- W przypadku ścieżek lokalnych projektu opencode przechodzi od bieżącego katalogu roboczego, aż dotrze do drzewa roboczego git. Ładuje po drodze dowolne pasujące `skills/*/SKILL.md` w `.opencode/` i dowolne pasujące `.claude/skills/*/SKILL.md` lub `.agents/skills/*/SKILL.md`. Ładowane są także definicje globalne z `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` i `~/.agents/skills/*/SKILL.md`. * * * [Tworzenie frontmatter](https://opencode.ai/docs/pl/skills/#tworzenie-frontmatter) ----------------------------------------------------------------------------------- Każdy `SKILL.md` musi zaczynać się od treści YAML. Rozpoznawane są tylko te pola: * `name` (wymagane) * `description` (wymagane) * `license` (opcjonalnie) * `compatibility` (opcjonalnie) * `metadata` (opcjonalnie, mapa string-to-string) Nieznane pola frontmatter są ignorowane. * * * [Walidacja nazw](https://opencode.ai/docs/pl/skills/#walidacja-nazw) --------------------------------------------------------------------- `name` musi: * Mieć od 1 do 64 znaków * Należy używać małych liter alfanumerycznych i oddzielać je pojedynczym łącznikiem * Nie zaczyna się ani nie kończy na `-` * Nie może zawierać następujących po sobie `--` * Dopasuj nazwę katalogu zawierającą `SKILL.md` Odpowiednik wyrażenia regularnego: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [Zasady dotyczące długości](https://opencode.ai/docs/pl/skills/#zasady-dotycz%C4%85ce-d%C5%82ugo%C5%9Bci) ---------------------------------------------------------------------------------------------------------- `description` musi mieć od 1 do 1024 znaków. Zadbaj o to, aby agent mógł dokonać prawidłowego wyboru. * * * [Przykład użycia](https://opencode.ai/docs/pl/skills/#przyk%C5%82ad-u%C5%BCycia) --------------------------------------------------------------------------------- Utwórz `.opencode/skills/git-release/SKILL.md` w ten sposób: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [Opis narzędzia](https://opencode.ai/docs/pl/skills/#opis-narz%C4%99dzia) -------------------------------------------------------------------------- opencode wymienia dostępne umiejętności w opisie narzędzia `skill`. Każdy wpis zawiera nazwę i opis umiejętności: git-release Create consistent releases and changelogs Agent ładuje umiejętność wywołując narzędzie: skill({ name: "git-release" }) * * * [Konfiguracja uprawnień](https://opencode.ai/docs/pl/skills/#konfiguracja-uprawnie%C5%84) ------------------------------------------------------------------------------------------ Kontroluj, do których umiejętności agenci mogą uzyskać dostęp, używając uprawnień opartych na wzorcach w `opencode.json`: { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | Permission | Behavior | | --- | --- | | `allow` | Umiejętność ładuje się natychmiast | | `deny` | Umiejętność ukryta przed agentem, dostęp odrzucony | | `ask` | Użytkownik proszony o zatwierdzenie przed załadowaniem | Wzorce obsługują symbole wieloznaczne: `internal-*` odpowiada `internal-docs`, `internal-tools` itd. * * * [Nadpisywanie dla agenta](https://opencode.ai/docs/pl/skills/#nadpisywanie-dla-agenta) --------------------------------------------------------------------------------------- Nadaj konkretnym agentom inne uprawnienia niż globalne ustawienia domyślne. **Dla agentów niestandardowych** (w temacie agentów): ---permission: skill: "documents-*": "allow"--- **Dla agentów wbudowanych** (w `opencode.json`): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [Wyłączanie narzędzia umiejętności](https://opencode.ai/docs/pl/skills/#wy%C5%82%C4%85czanie-narz%C4%99dzia-umiej%C4%99tno%C5%9Bci) ------------------------------------------------------------------------------------------------------------------------------------ Całkowicie wyłącz umiejętności agentów, którzy nie powinni ich używać: **Dla agentów niestandardowych** (w temacie agentów): ---tools: skill: false--- **W przypadku agentów wbudowanych**: { "agent": { "plan": { "tools": { "skill": false } } }} Jeśli opcja jest wyłączona, sekcja `` jest całkowicie pomijana. * * * [Rozwiązywanie problemów z ładowaniem](https://opencode.ai/docs/pl/skills/#rozwi%C4%85zywanie-problem%C3%B3w-z-%C5%82adowaniem) -------------------------------------------------------------------------------------------------------------------------------- Jeśli umiejętność nie pojawi się: 1. Sprawdź, czy `SKILL.md` jest napisane wielkimi literami 2. Sprawdź, czy frontmatter zawiera `name` i `description` 3. Upewnij się, że nazwy umiejętności są unikalne we wszystkich lokalizacjach 4. Sprawdź uprawnienia — umiejętności z `deny` są ukryte przed agentami --- # Agentfærdigheder | OpenCode [Gå til indhold](https://opencode.ai/docs/da/skills/#_top) Agentfærdigheder ================ Definer gjenbrugbar atferd via SKILL.md-definisjoner Agentferdigheter lar OpenCode oppdage gjenbrugbare instruksjoner fra repo- eller hjemmekatalogen din. Ferdigheter lastes inn på forespørsel via det opprinnelige `skill`\-verktøyet – agenter ser tilgængelige ferdigheter og kan laste inn hele innholdet når det er nødvendig. * * * [Placer filer](https://opencode.ai/docs/da/skills/#placer-filer) ----------------------------------------------------------------- Opret én mappe per ferdighetsnavn og tilføj inn en `SKILL.md` i den. OpenCode søker etter disse stedene: * Prosjektkonfigurasjon: `.opencode/skills//SKILL.md` * Global konfigurasjon: `~/.config/opencode/skills//SKILL.md` * Prosjekt Claude-kompatibel: `.claude/skills//SKILL.md` * Global Claude-kompatibel: `~/.claude/skills//SKILL.md` * Prosjektagent-kompatibel: `.agents/skills//SKILL.md` * Global agent-kompatibel: `~/.agents/skills//SKILL.md` * * * [Forstå opdagelsen](https://opencode.ai/docs/da/skills/#forst%C3%A5-opdagelsen) -------------------------------------------------------------------------------- For prosjektlokale stier går OpenCode opp fra din nåværende arbejdskatalog til den når git-arbeidstreet. Den laster alle matchende `skills/*/SKILL.md` i `.opencode/` og alle matchende `.claude/skills/*/SKILL.md` eller `.agents/skills/*/SKILL.md` underveis. Globale definisjoner lastes også inn fra `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` og `~/.agents/skills/*/SKILL.md`. * * * [Skriv frontmatter](https://opencode.ai/docs/da/skills/#skriv-frontmatter) --------------------------------------------------------------------------- Hver `SKILL.md` må starte med YAML frontmatter. Bare disse feltene gjenkjennes: * `name` (påkrevd) * `description` (påkrevd) * `license` (valgfritt) * `compatibility` (valgfritt) * `metadata` (valgfritt, streng-til-streng kart) Ukjente frontmatter-felter ignoreres. * * * [Bekræft navn](https://opencode.ai/docs/da/skills/#bekr%C3%A6ft-navn) ---------------------------------------------------------------------- `name` må: * Bestå av 1–64 tegn * Vær alfanumerisk med små bokstaver med skilletegn med enkelt bindestrek * Ikke begynne eller slutte med `-` * Ikke inneholde påfølgende `--` * Match katalognavnet som inneholder `SKILL.md` Ekvivalent regulært uttrykk: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [Følg længdereglerne](https://opencode.ai/docs/da/skills/#f%C3%B8lg-l%C3%A6ngdereglerne) ----------------------------------------------------------------------------------------- `description` må bestå av 1-1024 tegn. Hold det spesifikt nok til at agenten kan velge riktig. * * * [Brug et eksempel](https://opencode.ai/docs/da/skills/#brug-et-eksempel) ------------------------------------------------------------------------- Lag `.opencode/skills/git-release/SKILL.md` slik: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [Genkend værktøjsbeskrivelsen](https://opencode.ai/docs/da/skills/#genkend-v%C3%A6rkt%C3%B8jsbeskrivelsen) ----------------------------------------------------------------------------------------------------------- OpenCode viser tilgængelige ferdigheter i `skill` verktøybeskrivelsen. Hver oppføring inneholder ferdighetsnavnet og beskrivelsen: git-release Create consistent releases and changelogs Agenten laster inn en ferdighet ved at kalle verktøyet: skill({ name: "git-release" }) * * * [Konfigurer tilladelser](https://opencode.ai/docs/da/skills/#konfigurer-tilladelser) ------------------------------------------------------------------------------------- Kontroller hvilke ferdigheter agenter har tilgang til ved at bruge mønsterbaserte tillatelser i `opencode.json`: { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | Tillatelse | Atferd | | --- | --- | | `allow` | Ferdigheter lastes umiddelbart | | `deny` | Ferdighet skjult for agent, tilgang avvist | | `ask` | Bruger bedt om godkjenning før lasting | Mønstre støtter jokertegn: `internal-*` samsvarer med `internal-docs`, `internal-tools` osv. * * * [Tilsidesættelse pr. agent](https://opencode.ai/docs/da/skills/#tilsides%C3%A6ttelse-pr-agent) ----------------------------------------------------------------------------------------------- Gi spesifikke agenter andre tillatelser enn de globale standardinnstillingene. **For egendefinerte agenter** (i agent frontmatter): ---permission: skill: "documents-*": "allow"--- **For innebygde agenter** (i `opencode.json`): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [Deaktiver færdighedsværktøjet](https://opencode.ai/docs/da/skills/#deaktiver-f%C3%A6rdighedsv%C3%A6rkt%C3%B8jet) ------------------------------------------------------------------------------------------------------------------ Deaktiver ferdigheter fullstendig for agenter som ikke bør bruge dem: **For egendefinerte agenter**: ---tools: skill: false--- **For innebygde agenter**: { "agent": { "plan": { "tools": { "skill": false } } }} Når den er deaktivert, blir ``\-delen utelatt helt. * * * [Fejlfind indlæsning](https://opencode.ai/docs/da/skills/#fejlfind-indl%C3%A6sning) ------------------------------------------------------------------------------------ Hvis en ferdighet ikke vises: 1. Kontroller at `SKILL.md` er stavet med store bokstaver 2. Tjek at frontmatter inkluderer `name` og `description` 3. Sørg for at ferdighetsnavnene er unike på alle steder 4. Tjek tillatelser – ferdigheter med `deny` er skjult for agenter --- # Habilidades del agente | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/skills/#_top) Habilidades del agente ====================== Defina el comportamiento reutilizable mediante definiciones de SKILL.md Las habilidades del agente permiten a OpenCode descubrir instrucciones reutilizables de su repositorio o directorio de inicio. Las habilidades se cargan bajo demanda a través de la herramienta nativa `skill`: los agentes ven las habilidades disponibles y pueden cargar el contenido completo cuando sea necesario. * * * [Colocar archivos](https://opencode.ai/docs/es/skills/#colocar-archivos) ------------------------------------------------------------------------- Cree una carpeta por nombre de habilidad y coloque un `SKILL.md` dentro de ella. OpenCode busca estas ubicaciones: * Configuración del proyecto: `.opencode/skills//SKILL.md` * Configuración global: `~/.config/opencode/skills//SKILL.md` * Compatible con Proyecto Claude: `.claude/skills//SKILL.md` * Compatible con Claude global: `~/.claude/skills//SKILL.md` * Compatible con agente de proyecto: `.agents/skills//SKILL.md` * Compatible con agentes globales: `~/.agents/skills//SKILL.md` * * * [Entender el descubrimiento](https://opencode.ai/docs/es/skills/#entender-el-descubrimiento) --------------------------------------------------------------------------------------------- Para las rutas locales del proyecto, OpenCode sube desde su directorio de trabajo actual hasta llegar al árbol de trabajo de git. Carga cualquier `skills/*/SKILL.md` coincidente en `.opencode/` y cualquier `.claude/skills/*/SKILL.md` o `.agents/skills/*/SKILL.md` coincidente a lo largo del camino. Las definiciones globales también se cargan desde `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` y `~/.agents/skills/*/SKILL.md`. * * * [Escribir la introducción](https://opencode.ai/docs/es/skills/#escribir-la-introducci%C3%B3n) ---------------------------------------------------------------------------------------------- Cada `SKILL.md` debe comenzar con el frontmatter de YAML. Sólo se reconocen estos campos: * `name` (obligatorio) * `description` (obligatorio) * `license` (opcional) * `compatibility` (opcional) * `metadata` (opcional, mapa de cadena a cadena) Los campos desconocidos se ignoran. * * * [Validar nombres](https://opencode.ai/docs/es/skills/#validar-nombres) ----------------------------------------------------------------------- `name` debe: * Tener entre 1 y 64 caracteres. * Ser alfanuméricos en minúsculas con separadores de guión simple * No comienza ni termina con `-` * No contener `--` consecutivos * Coincide con el nombre del directorio que contiene `SKILL.md` expresión regular equivalente: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [Seguir las reglas de longitud](https://opencode.ai/docs/es/skills/#seguir-las-reglas-de-longitud) --------------------------------------------------------------------------------------------------- `description` debe tener entre 1 y 1024 caracteres. Manténgalo lo suficientemente específico para que el agente elija correctamente. * * * [Usar un ejemplo](https://opencode.ai/docs/es/skills/#usar-un-ejemplo) ----------------------------------------------------------------------- Crea `.opencode/skills/git-release/SKILL.md` así: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [Reconocer la descripción de la herramienta](https://opencode.ai/docs/es/skills/#reconocer-la-descripci%C3%B3n-de-la-herramienta) ---------------------------------------------------------------------------------------------------------------------------------- OpenCode enumera las habilidades disponibles en la descripción de la herramienta `skill`. Cada entrada incluye el nombre y la descripción de la habilidad: git-release Create consistent releases and changelogs El agente carga una habilidad llamando a la herramienta: skill({ name: "git-release" }) * * * [Configurar permisos](https://opencode.ai/docs/es/skills/#configurar-permisos) ------------------------------------------------------------------------------- Controle a qué agentes de habilidades pueden acceder utilizando permisos basados ​​en patrones en `opencode.json`: { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | Permiso | Comportamiento | | --- | --- | | `allow` | La habilidad se carga inmediatamente | | `deny` | Habilidad oculta al agente, acceso rechazado | | `ask` | Se solicita al usuario aprobación antes de cargar | Los patrones admiten comodines: `internal-*` coincide con `internal-docs`, `internal-tools`, etc. * * * [Anulación por agente](https://opencode.ai/docs/es/skills/#anulaci%C3%B3n-por-agente) -------------------------------------------------------------------------------------- Otorgue a agentes específicos permisos diferentes a los predeterminados globales. **Para agentes personalizados** (en el frente del agente): ---permission: skill: "documents-*": "allow"--- **Para agentes integrados** (en `opencode.json`): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [Deshabilitar la herramienta de habilidades](https://opencode.ai/docs/es/skills/#deshabilitar-la-herramienta-de-habilidades) ----------------------------------------------------------------------------------------------------------------------------- Deshabilite completamente las habilidades para los agentes que no deberían usarlas: **Para agentes personalizados**: ---tools: skill: false--- **Para agentes integrados**: { "agent": { "plan": { "tools": { "skill": false } } }} Cuando está deshabilitada, la sección `` se omite por completo. * * * [Solucionar problemas de carga](https://opencode.ai/docs/es/skills/#solucionar-problemas-de-carga) --------------------------------------------------------------------------------------------------- Si una habilidad no aparece: 1. Verifique que `SKILL.md` esté escrito en mayúsculas. 2. Verifique que el frontmatter incluya `name` y `description` 3. Asegúrese de que los nombres de las habilidades sean únicos en todas las ubicaciones 4. Verifique los permisos: las habilidades con `deny` están ocultas para los agentes --- # 에이전트 스킬 | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/skills/#_top) 에이전트 스킬 ======= SKILL.md 정의를 통해 재사용 가능한 동작을 정의합니다. Agent Skill let opencode discover reusable instruction from your repo 또는 홈 디렉토리. Skills are loaded on-demand via native `skill` tool-agents see available skills and can loaded full content when needed. * * * [파일 위치](https://opencode.ai/docs/ko/skills/#%ED%8C%8C%EC%9D%BC-%EC%9C%84%EC%B9%98) ----------------------------------------------------------------------------------- 기술 이름 당 하나의 폴더를 만들고 내부 `SKILL.md`를 넣어. opencode 이 위치를 검색: * 프로젝트 구성: `.opencode/skills//SKILL.md` * 글로벌 구성: `~/.config/opencode/skills//SKILL.md` * 프로젝트 클로드 호환 : `.claude/skills//SKILL.md` * 글로벌 클로드 호환 : `~/.claude/skills//SKILL.md` * 프로젝트 에이전트 호환 : `.agents/skills//SKILL.md` * 글로벌 에이전트 호환 : `~/.agents/skills//SKILL.md` * * * [검색 이해](https://opencode.ai/docs/ko/skills/#%EA%B2%80%EC%83%89-%EC%9D%B4%ED%95%B4) ----------------------------------------------------------------------------------- Project-local paths의 경우, opencode는 git worktree에 도달 할 때까지 현재 작업 디렉토리에서 걷습니다. 그것은 `skills/*/SKILL.md`에 있는 어떤 어울리는 `.opencode/` 및 어떤 어울리는 `.claude/skills/*/SKILL.md` 또는 `.agents/skills/*/SKILL.md`를 방법 적재합니다. 세계적인 정의는 또한 `~/.config/opencode/skills/*/SKILL.md`, `~/.claude/skills/*/SKILL.md` 및 `~/.agents/skills/*/SKILL.md`에서 적재됩니다. * * * [Frontmatter 작성](https://opencode.ai/docs/ko/skills/#frontmatter-%EC%9E%91%EC%84%B1) ------------------------------------------------------------------------------------- 각 `SKILL.md`는 YAML frontmatter로 시작해야 합니다. 이 필드는 인식됩니다: * `name` (필수) * `description` (필수) * (선택) `license` * (선택) `compatibility` * `metadata` (선택 사항, 문자열에 문자열 맵) 알려진 frontmatter 필드는 무시됩니다. * * * [유효한 이름](https://opencode.ai/docs/ko/skills/#%EC%9C%A0%ED%9A%A8%ED%95%9C-%EC%9D%B4%EB%A6%84) --------------------------------------------------------------------------------------------- `name`는 해야 합니다: * 1–64자 * 단 하나 hyphen 분리기를 가진 더 낮은 케이스 alphanumeric가 있으십시오 * `-`로 시작 또는 끝 아닙니다 * 연속 `--` 포함하지 * `SKILL.md`를 포함하는 디렉토리 이름을 일치 동등한 regex: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [길이 규칙 준수](https://opencode.ai/docs/ko/skills/#%EA%B8%B8%EC%9D%B4-%EA%B7%9C%EC%B9%99-%EC%A4%80%EC%88%98) --------------------------------------------------------------------------------------------------------- `description`는 1-1024 특성이어야 합니다. 제대로 선택하기 위해 에이전트에 대해 충분히 유지하십시오. * * * [사용 예제](https://opencode.ai/docs/ko/skills/#%EC%82%AC%EC%9A%A9-%EC%98%88%EC%A0%9C) ----------------------------------------------------------------------------------- 이처럼 `.opencode/skills/git-release/SKILL.md` 만들기: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [도구 설명 인식](https://opencode.ai/docs/ko/skills/#%EB%8F%84%EA%B5%AC-%EC%84%A4%EB%AA%85-%EC%9D%B8%EC%8B%9D) --------------------------------------------------------------------------------------------------------- opencode는 `skill` 도구 설명에서 사용할 수있는 기술을 나열합니다. 각 항목에는 기술 이름 및 설명이 포함됩니다. git-release Create consistent releases and changelogs 에이전트는 도구를 호출하여 기술을로드 : skill({ name: "git-release" }) * * * [권한 구성](https://opencode.ai/docs/ko/skills/#%EA%B6%8C%ED%95%9C-%EA%B5%AC%EC%84%B1) ----------------------------------------------------------------------------------- 기술 에이전트가 `opencode.json`의 패턴 기반 권한을 사용하여 액세스 할 수있는 제어 : { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | 권한 | 동작 | | --- | --- | | `allow` | 기술이 즉시 로드됨 | | `deny` | 에이전트에서 기술 숨김, 접근 거부 | | `ask` | 로드 전에 사용자에게 승인 요청 | 패턴 지원 와일드 카드: `internal-*` 경기 `internal-docs`, `internal-tools`, 등. * * * [에이전트별 재정의](https://opencode.ai/docs/ko/skills/#%EC%97%90%EC%9D%B4%EC%A0%84%ED%8A%B8%EB%B3%84-%EC%9E%AC%EC%A0%95%EC%9D%98) --------------------------------------------------------------------------------------------------------------------------- 글로벌 디폴트보다 특정 에이전트 다른 권한을 부여합니다. \*\*사용자 지정 에이전트 \*\* ( 에이전트 frontmatter): ---permission: skill: "documents-*": "allow"--- \*\* 내장 에이전트 \*\* (`opencode.json`에서): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [스킬 도구 비활성화](https://opencode.ai/docs/ko/skills/#%EC%8A%A4%ED%82%AC-%EB%8F%84%EA%B5%AC-%EB%B9%84%ED%99%9C%EC%84%B1%ED%99%94) ----------------------------------------------------------------------------------------------------------------------------- 그들을 사용하지 않는 에이전트을위한 완전히 비활성화 된 기술 : **사용자 지정 에이전트**: ---tools: skill: false--- \*\* 내장 에이전트 \*\*: { "agent": { "plan": { "tools": { "skill": false } } }} 비활성화 할 때, `` 섹션은 완전히 부유합니다. * * * [로딩 문제 해결](https://opencode.ai/docs/ko/skills/#%EB%A1%9C%EB%94%A9-%EB%AC%B8%EC%A0%9C-%ED%95%B4%EA%B2%B0) --------------------------------------------------------------------------------------------------------- 기술이 나타나지 않는 경우: 1. `SKILL.md`는 모든 모자에서 spelled 2. `name`와 `description`를 포함하는 검사 3. 기술 이름은 모든 위치에서 독특합니다. 4. `deny`를 가진 허가를 검사하십시오 에이전트에서 숨겨집니다 --- # ACP | OpenCode [Przejdź do głównej zawartości](https://opencode.ai/docs/pl/acp/#_top) ACP === Używanie OpenCode z protokołem Agent Client Protocol (ACP). OpenCode obsługuje [Agent Client Protocol](https://agentclientprotocol.com/) (ACP), który umożliwia korzystanie z OpenCode bezpośrednio w edytorach i środowiskach IDE. ACP to otwarty standard, który ujednolica komunikację między edytorami kodu a agentami kodującymi AI. * * * [Konfiguracja](https://opencode.ai/docs/pl/acp/#konfiguracja) -------------------------------------------------------------- Aby używać OpenCode przez ACP, skonfiguruj swój edytor tak, aby uruchamiał polecenie `opencode acp`. Uruchamia to OpenCode jako podproces zgodny z ACP, który komunikuje się z edytorem za pomocą JSON-RPC przez stdio. Poniżej znajdują się przykłady dla edytorów obsługujących ACP. * * * ### [Zed](https://opencode.ai/docs/pl/acp/#zed) Dodaj do konfiguracji [Zed](https://zed.dev/) (`~/.config/zed/settings.json`): { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} Aby użyć, wybierz `agent: new thread` w **Palecie poleceń** (Command Palette). Możesz także przypisać skrót klawiszowy, edytując `keymap.json`: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDE](https://opencode.ai/docs/pl/acp/#jetbrains-ide) Dodaj do swojego [JetBrains IDE](https://www.jetbrains.com/) plik `acp.json` zgodnie z [dokumentacją](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} Następnie wybierz „OpenCode” w selektorze agentów AI Chat. * * * ### [Avante.nvim](https://opencode.ai/docs/pl/acp/#avantenvim) Dodaj do konfiguracji [Avante.nvim](https://github.com/yetone/avante.nvim) : { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} Jeśli potrzebujesz przekazać klucz API: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/pl/acp/#codecompanionnvim) Aby używać OpenCode jako agenta ACP w [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) , dodaj następującą konfigurację do Neovim: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) Ta konfiguracja sprawia, że CodeCompanion używa OpenCode jako agenta ACP do czatu. Jeśli wymagany jest `OPENCODE_API_KEY`, zapoznaj się z sekcją [Konfigurowanie adapterów: Zmienne środowiskowe](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) w dokumentacji CodeCompanion.nvim, aby uzyskać szczegółowe informacje. [Wsparcie](https://opencode.ai/docs/pl/acp/#wsparcie) ------------------------------------------------------ OpenCode działa przez ACP tak samo, jak w terminalu. Obsługiwane są wszystkie główne funkcje: * Narzędzia wbudowane (operacje na plikach, terminal itp.) * Niestandardowe narzędzia i polecenia z ukośnikiem * Serwery MCP zdefiniowane w konfiguracji OpenCode * Zasady projektu z `AGENTS.md` * Niestandardowe formatery i lintery * Agenci systemowi i uprawnienia --- # ACP 支持 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/acp/#_top) ACP 支持 ====== 在任何兼容 ACP 的编辑器中使用 OpenCode。 OpenCode 支持 [Agent Client Protocol](https://agentclientprotocol.com/) (ACP),允许你直接在兼容的编辑器和 IDE 中使用它。 ACP 是一个开放协议,用于标准化代码编辑器与 AI 编码代理之间的通信。 * * * [配置](https://opencode.ai/docs/zh-cn/acp/#%E9%85%8D%E7%BD%AE) ------------------------------------------------------------- 要通过 ACP 使用 OpenCode,请在编辑器中配置运行 `opencode acp` 命令。 该命令会将 OpenCode 作为兼容 ACP 的子进程启动,通过 stdio 上的 JSON-RPC 与编辑器进行通信。 以下是支持 ACP 的常用编辑器的配置示例。 * * * ### [Zed](https://opencode.ai/docs/zh-cn/acp/#zed) 添加到你的 [Zed](https://zed.dev/) 配置文件(`~/.config/zed/settings.json`)中: { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} 打开方式:在**命令面板**中执行 `agent: new thread` 操作。 你也可以通过编辑 `keymap.json` 来绑定键盘快捷键: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDEs](https://opencode.ai/docs/zh-cn/acp/#jetbrains-ides) 根据[文档](https://www.jetbrains.com/help/ai-assistant/acp.html) ,将以下内容添加到你的 [JetBrains IDE](https://www.jetbrains.com/) 的 acp.json 中: { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} 打开方式:在 AI Chat 代理选择器中选择新的 ‘OpenCode’ 代理。 * * * ### [Avante.nvim](https://opencode.ai/docs/zh-cn/acp/#avantenvim) 添加到你的 [Avante.nvim](https://github.com/yetone/avante.nvim) 配置中: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} 如果需要传递环境变量: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/zh-cn/acp/#codecompanionnvim) 要在 [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) 中将 OpenCode 用作 ACP 代理,请将以下内容添加到你的 Neovim 配置中: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) 此配置将 CodeCompanion 设置为使用 OpenCode 作为聊天的 ACP 代理。 如果需要传递环境变量(如 `OPENCODE_API_KEY`),请参阅 CodeCompanion.nvim 文档中的[配置适配器:环境变量](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) 了解详细信息。 [支持](https://opencode.ai/docs/zh-cn/acp/#%E6%94%AF%E6%8C%81) ------------------------------------------------------------- OpenCode 通过 ACP 使用时与在终端中使用的效果完全一致。所有功能均受支持: * 内置工具(文件操作、终端命令等) * 自定义工具和斜杠命令 * 在 OpenCode 配置中配置的 MCP 服务器 * 来自 `AGENTS.md` 的项目级规则 * 自定义格式化工具和代码检查工具 * 代理和权限系统 --- # ACP-understøttelse | OpenCode [Gå til indhold](https://opencode.ai/docs/da/acp/#_top) ACP-understøttelse ================== Brug OpenCode i enhver ACP-kompatibel editor. OpenCode understøtter [Agent Client Protocol](https://agentclientprotocol.com/) eller (ACP), så du kan bruge det direkte i kompatible editorer og IDE’er. ACP er en åben protokol, der standardiserer kommunikation mellem kodeeditorer og AI-kodningsagenter. * * * [Konfiguration](https://opencode.ai/docs/da/acp/#konfiguration) ---------------------------------------------------------------- For at bruge OpenCode via ACP, konfigurer din editor til at køre kommandoen `opencode acp`. Kommandoen starter OpenCode som en ACP-kompatibel underproces, der kommunikerer med din editor over JSON-RPC via stdio. Nedenfor er eksempler på populære editorer, der understøtter ACP. * * * ### [Zed](https://opencode.ai/docs/da/acp/#zed) Føj til din [Zed](https://zed.dev/) \-konfiguration (`~/.config/zed/settings.json`): { "agent_servers": { "OpenCode": { "command": "opencode", "args": ["acp"] } }} For at åbne den skal du bruge handlingen `agent: new thread` i **Kommandopaletten**. Du kan også binde en tastaturgenvej ved at redigere din `keymap.json`: [ { "bindings": { "cmd-alt-o": [ "agent::NewExternalAgentThread", { "agent": { "custom": { "name": "OpenCode", "command": { "command": "opencode", "args": ["acp"] } } } } ] } }] * * * ### [JetBrains IDE’er](https://opencode.ai/docs/da/acp/#jetbrains-ideer) Tilføj til din [JetBrains IDE](https://www.jetbrains.com/) acp.json i henhold til [dokumentationen](https://www.jetbrains.com/help/ai-assistant/acp.html) : { "agent_servers": { "OpenCode": { "command": "/absolute/path/bin/opencode", "args": ["acp"] } }} For at åbne den skal du bruge den nye ‘OpenCode’-agent i AI Chat-agentvælgeren. * * * ### [Avante.nvim](https://opencode.ai/docs/da/acp/#avantenvim) Føj til din [Avante.nvim](https://github.com/yetone/avante.nvim) \-konfiguration: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" } } }} Hvis du har brug for at videregive miljøvariabler: { acp_providers = { ["opencode"] = { command = "opencode", args = { "acp" }, env = { OPENCODE_API_KEY = os.getenv("OPENCODE_API_KEY") } } }} * * * ### [CodeCompanion.nvim](https://opencode.ai/docs/da/acp/#codecompanionnvim) For at bruge OpenCode som en ACP-agent i [CodeCompanion.nvim](https://github.com/olimorris/codecompanion.nvim) , skal du tilføje følgende til din Neovim-konfiguration: require("codecompanion").setup({ interactions = { chat = { adapter = { name = "opencode", model = "claude-sonnet-4", }, }, },}) Denne konfiguration sætter CodeCompanion til at bruge OpenCode som ACP-agent til chat. Hvis du har brug for at sende miljøvariabler (som `OPENCODE_API_KEY`), henvises til [Konfiguration af adaptere: Miljøvariabler](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) i CodeCompanion.nvim-dokumentationen for alle detaljer. [Understøttelse](https://opencode.ai/docs/da/acp/#underst%C3%B8ttelse) ----------------------------------------------------------------------- OpenCode fungerer på samme måde via ACP som i terminalen. Alle funktioner understøtter: * Indbyggede værktøjer (filoperationer, terminalkommandoer osv.) * Brugerdefinerede værktøjer og slash-kommandoer * MCP-servere konfigureret i din OpenCode-konfiguration * Projektspecifikke regler fra `AGENTS.md` * Brugerdefinerede formatere og linters * Agenter og tilladelsessystem --- # エージェントスキル | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/skills/#_top) エージェントスキル ========= SKILL.md 定義による再利用可能な動作の定義 エージェントスキルにより、OpenCode はリポジトリまたはホームディレクトリから再利用可能な命令を検出できます。 スキルはネイティブの `skill` ツールを介してオンデマンドでロードされます。エージェントは利用可能なスキルを確認し、必要に応じて完全なコンテンツをロードできます。 * * * [ファイルの配置](https://opencode.ai/docs/ja/skills/#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E9%85%8D%E7%BD%AE) --------------------------------------------------------------------------------------------------------------- スキル名ごとにフォルダーを 1 つ作成し、その中に `SKILL.md` を置きます。 OpenCode は次の場所を検索します。 * プロジェクト設定: `.opencode/skills//SKILL.md` * グローバル設定: `~/.config/opencode/skills//SKILL.md` * プロジェクト Claude 互換: `.claude/skills//SKILL.md` * グローバル Claude 互換: `~/.claude/skills//SKILL.md` * プロジェクトエージェント互換: `.agents/skills//SKILL.md` * グローバルエージェント互換: `~/.agents/skills//SKILL.md` * * * [検出の仕組み](https://opencode.ai/docs/ja/skills/#%E6%A4%9C%E5%87%BA%E3%81%AE%E4%BB%95%E7%B5%84%E3%81%BF) ----------------------------------------------------------------------------------------------------- プロジェクトのローカルパスの場合、OpenCode は現在の作業ディレクトリから git ワークツリーに到達するまで進みます。 途中で、一致する `skills/*/SKILL.md` を `.opencode/` に読み込み、一致する `.claude/skills/*/SKILL.md` または `.agents/skills/*/SKILL.md` を読み込みます。 グローバル定義は、`~/.config/opencode/skills/*/SKILL.md`、`~/.claude/skills/*/SKILL.md`、および `~/.agents/skills/*/SKILL.md` からもロードされます。 * * * [フロントマターの記述](https://opencode.ai/docs/ja/skills/#%E3%83%95%E3%83%AD%E3%83%B3%E3%83%88%E3%83%9E%E3%82%BF%E3%83%BC%E3%81%AE%E8%A8%98%E8%BF%B0) --------------------------------------------------------------------------------------------------------------------------------------------- 各 `SKILL.md` は YAML フロントマターで始まる必要があります。 次のフィールドのみが認識されます。 * `name` (必須) * `description` (必須) * `license` (オプション) * `compatibility` (オプション) * `metadata` (オプション、文字列間のマップ) 不明なフロントマターフィールドは無視されます。 * * * [名前の検証](https://opencode.ai/docs/ja/skills/#%E5%90%8D%E5%89%8D%E3%81%AE%E6%A4%9C%E8%A8%BC) ------------------------------------------------------------------------------------------- `name` は次のことを行う必要があります。 * 1 ~ 64 文字であること * 単一のハイフンで区切られた小文字の英数字であること * `-` で開始または終了しない * 連続した `--` を含まない * `SKILL.md` を含むディレクトリ名と一致する 同等の正規表現: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [長さのルール](https://opencode.ai/docs/ja/skills/#%E9%95%B7%E3%81%95%E3%81%AE%E3%83%AB%E3%83%BC%E3%83%AB) ----------------------------------------------------------------------------------------------------- `description` は 1 ~ 1024 文字である必要があります。 エージェントが正しく選択できるように、十分具体的な内容にしてください。 * * * [使用例](https://opencode.ai/docs/ja/skills/#%E4%BD%BF%E7%94%A8%E4%BE%8B) ----------------------------------------------------------------------- 次のように `.opencode/skills/git-release/SKILL.md` を作成します。 ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [ツールの説明認識](https://opencode.ai/docs/ja/skills/#%E3%83%84%E3%83%BC%E3%83%AB%E3%81%AE%E8%AA%AC%E6%98%8E%E8%AA%8D%E8%AD%98) ------------------------------------------------------------------------------------------------------------------------- OpenCode では、`skill` ツールの説明に利用可能なスキルがリストされています。 各エントリにはスキル名と説明が含まれます。 git-release Create consistent releases and changelogs エージェントはツールを呼び出してスキルをロードします。 skill({ name: "git-release" }) * * * [権限の設定](https://opencode.ai/docs/ja/skills/#%E6%A8%A9%E9%99%90%E3%81%AE%E8%A8%AD%E5%AE%9A) ------------------------------------------------------------------------------------------- `opencode.json` のパターンベースの権限を使用して、エージェントがアクセスできるスキルを制御します。 { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | 許可 | アクション | | --- | --- | | `allow` | スキルはすぐにロードされます | | `deny` | スキルはエージェントから隠蔽され、アクセスは拒否されました | | `ask` | ロードする前にユーザーに承認を求めるメッセージが表示される | パターンはワイルドカードをサポートしています: `internal-*` は `internal-docs`、`internal-tools` などに一致します。 * * * [エージェントごとの上書き](https://opencode.ai/docs/ja/skills/#%E3%82%A8%E3%83%BC%E3%82%B8%E3%82%A7%E3%83%B3%E3%83%88%E3%81%94%E3%81%A8%E3%81%AE%E4%B8%8A%E6%9B%B8%E3%81%8D) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- 特定のエージェントにグローバルのデフォルトとは異なる権限を与えます。 **カスタムエージェントの場合** (エージェントフロントマター内): ---permission: skill: "documents-*": "allow"--- **組み込みエージェントの場合** (`opencode.json` 内): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [スキルツールの無効化](https://opencode.ai/docs/ja/skills/#%E3%82%B9%E3%82%AD%E3%83%AB%E3%83%84%E3%83%BC%E3%83%AB%E3%81%AE%E7%84%A1%E5%8A%B9%E5%8C%96) --------------------------------------------------------------------------------------------------------------------------------------------- スキルを使用すべきではないエージェントのスキルを完全に無効にします。 **カスタムエージェントの場合**: ---tools: skill: false--- **組み込みエージェントの場合**: { "agent": { "plan": { "tools": { "skill": false } } }} 無効にすると、`` セクションが完全に省略されます。 * * * [読み込みのトラブルシューティング](https://opencode.ai/docs/ja/skills/#%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF%E3%81%AE%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) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- スキルが表示されない場合: 1. `SKILL.md` のスペルがすべて大文字であることを確認してください 2. フロントマターに `name` と `description` が含まれていることを確認します 3. スキル名がすべての場所で一意であることを確認する 4. 権限を確認してください - `deny` のスキルはエージェントから非表示になります --- # References | OpenCode [コンテンツにスキップ](https://opencode.ai/docs/ja/references/#_top) References ========== Add local directories and Git repositories as project references. このコンテンツはまだ日本語訳がありません。 References give OpenCode access to directories outside the current project. Use them to make documentation, shared libraries, examples, or another repository available while you work. References are configured by alias in `opencode.json` or `opencode.jsonc`. { "$schema": "https://opencode.ai/config.json", "references": { "docs": { "path": "../product-docs", "description": "Use for product behavior and documentation conventions", }, "sdk": { "repository": "anomalyco/opencode-sdk-js", "branch": "main", "description": "Use for JavaScript SDK implementation details", }, },} * * * [Local directories](https://opencode.ai/docs/ja/references/#local-directories) ------------------------------------------------------------------------------- Use `path` to reference a local directory. { "references": { "docs": { "path": "../docs", }, },} Paths can be: * Relative to the config file that defines the reference * Absolute, such as `/home/user/docs` * Relative to your home directory, such as `~/docs` You can also use a string shorthand: { "references": { "docs": "../docs", },} * * * [Git repositories](https://opencode.ai/docs/ja/references/#git-repositories) ----------------------------------------------------------------------------- Use `repository` to reference a Git repository. OpenCode materializes the repository in its local repository cache and makes the checked-out source available as a reference directory. { "references": { "effect": { "repository": "Effect-TS/effect", "branch": "main", }, },} `repository` accepts Git URLs, host/path references, and GitHub `owner/repo` shorthand. The optional `branch` field selects a branch or ref. Without `branch`, OpenCode uses the repository’s default branch. You can use string shorthand when you do not need a branch, description, or other options: { "references": { "effect": "Effect-TS/effect", },} * * * [Describe usage](https://opencode.ai/docs/ja/references/#describe-usage) ------------------------------------------------------------------------- Add `description` to explain when an agent should use a reference. { "references": { "design-system": { "path": "../design-system", "description": "Use when implementing UI components or design tokens", }, },} OpenCode includes references with descriptions in agent context. Descriptions should be short and specific enough to distinguish references with similar content. References without descriptions remain available through autocomplete and direct use, but are not advertised to agents. * * * [Hide autocomplete entries](https://opencode.ai/docs/ja/references/#hide-autocomplete-entries) ----------------------------------------------------------------------------------------------- Set `hidden` to `true` to omit a reference from `@` autocomplete in the TUI. { "references": { "internal": { "path": "../internal", "description": "Use for internal implementation details", "hidden": true, }, },} `hidden` only affects autocomplete. A hidden reference with a description remains included in agent context. * * * [Use references](https://opencode.ai/docs/ja/references/#use-references) ------------------------------------------------------------------------- Configured references appear in TUI `@` autocomplete. Type `@alias` to attach the reference root, or `@alias/` to search for files inside it. Compare this implementation with @sdk/src/client.ts Agents also receive the resolved paths and descriptions of configured references that have descriptions in their system context, so they can inspect a reference when it is relevant without you attaching it manually. OpenCode automatically allows reference directories through its external-directory permission boundary. Normal tool permissions still apply; for example, an agent that cannot edit files does not gain edit access because a directory is configured as a reference. * * * [Configure fields](https://opencode.ai/docs/ja/references/#configure-fields) ----------------------------------------------------------------------------- | Field | Local | Git | Description | | --- | --- | --- | --- | | `path` | Yes | No | Local reference directory | | `repository` | No | Yes | Git URL, host/path, or GitHub `owner/repo` value | | `branch` | No | Yes | Optional Git branch or ref | | `description` | Yes | Yes | Guidance describing when to use the reference | | `hidden` | Yes | Yes | Hide the reference from TUI `@` autocomplete | Reference aliases cannot be empty or contain `/`, whitespace, backticks, or commas. --- # References | OpenCode [Saltearse al contenido](https://opencode.ai/docs/es/references/#_top) References ========== Add local directories and Git repositories as project references. Esta página aún no está disponible en tu idioma. References give OpenCode access to directories outside the current project. Use them to make documentation, shared libraries, examples, or another repository available while you work. References are configured by alias in `opencode.json` or `opencode.jsonc`. { "$schema": "https://opencode.ai/config.json", "references": { "docs": { "path": "../product-docs", "description": "Use for product behavior and documentation conventions", }, "sdk": { "repository": "anomalyco/opencode-sdk-js", "branch": "main", "description": "Use for JavaScript SDK implementation details", }, },} * * * [Local directories](https://opencode.ai/docs/es/references/#local-directories) ------------------------------------------------------------------------------- Use `path` to reference a local directory. { "references": { "docs": { "path": "../docs", }, },} Paths can be: * Relative to the config file that defines the reference * Absolute, such as `/home/user/docs` * Relative to your home directory, such as `~/docs` You can also use a string shorthand: { "references": { "docs": "../docs", },} * * * [Git repositories](https://opencode.ai/docs/es/references/#git-repositories) ----------------------------------------------------------------------------- Use `repository` to reference a Git repository. OpenCode materializes the repository in its local repository cache and makes the checked-out source available as a reference directory. { "references": { "effect": { "repository": "Effect-TS/effect", "branch": "main", }, },} `repository` accepts Git URLs, host/path references, and GitHub `owner/repo` shorthand. The optional `branch` field selects a branch or ref. Without `branch`, OpenCode uses the repository’s default branch. You can use string shorthand when you do not need a branch, description, or other options: { "references": { "effect": "Effect-TS/effect", },} * * * [Describe usage](https://opencode.ai/docs/es/references/#describe-usage) ------------------------------------------------------------------------- Add `description` to explain when an agent should use a reference. { "references": { "design-system": { "path": "../design-system", "description": "Use when implementing UI components or design tokens", }, },} OpenCode includes references with descriptions in agent context. Descriptions should be short and specific enough to distinguish references with similar content. References without descriptions remain available through autocomplete and direct use, but are not advertised to agents. * * * [Hide autocomplete entries](https://opencode.ai/docs/es/references/#hide-autocomplete-entries) ----------------------------------------------------------------------------------------------- Set `hidden` to `true` to omit a reference from `@` autocomplete in the TUI. { "references": { "internal": { "path": "../internal", "description": "Use for internal implementation details", "hidden": true, }, },} `hidden` only affects autocomplete. A hidden reference with a description remains included in agent context. * * * [Use references](https://opencode.ai/docs/es/references/#use-references) ------------------------------------------------------------------------- Configured references appear in TUI `@` autocomplete. Type `@alias` to attach the reference root, or `@alias/` to search for files inside it. Compare this implementation with @sdk/src/client.ts Agents also receive the resolved paths and descriptions of configured references that have descriptions in their system context, so they can inspect a reference when it is relevant without you attaching it manually. OpenCode automatically allows reference directories through its external-directory permission boundary. Normal tool permissions still apply; for example, an agent that cannot edit files does not gain edit access because a directory is configured as a reference. * * * [Configure fields](https://opencode.ai/docs/es/references/#configure-fields) ----------------------------------------------------------------------------- | Field | Local | Git | Description | | --- | --- | --- | --- | | `path` | Yes | No | Local reference directory | | `repository` | No | Yes | Git URL, host/path, or GitHub `owner/repo` value | | `branch` | No | Yes | Optional Git branch or ref | | `description` | Yes | Yes | Guidance describing when to use the reference | | `hidden` | Yes | Yes | Hide the reference from TUI `@` autocomplete | Reference aliases cannot be empty or contain `/`, whitespace, backticks, or commas. --- # 代理技能 | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/skills/#_top) 代理技能 ==== 通过 SKILL.md 定义可复用的行为 代理技能让 OpenCode 能够从你的仓库或主目录中发现可复用的指令。 技能通过原生的 `skill` 工具按需加载——代理可以查看可用技能,并在需要时加载完整内容。 * * * [放置文件](https://opencode.ai/docs/zh-cn/skills/#%E6%94%BE%E7%BD%AE%E6%96%87%E4%BB%B6) ------------------------------------------------------------------------------------ 为每个技能名称创建一个文件夹,并在其中放入 `SKILL.md`。 OpenCode 会搜索以下位置: * 项目配置:`.opencode/skills//SKILL.md` * 全局配置:`~/.config/opencode/skills//SKILL.md` * 项目 Claude 兼容:`.claude/skills//SKILL.md` * 全局 Claude 兼容:`~/.claude/skills//SKILL.md` * 项目代理兼容:`.agents/skills//SKILL.md` * 全局代理兼容:`~/.agents/skills//SKILL.md` * * * [了解发现机制](https://opencode.ai/docs/zh-cn/skills/#%E4%BA%86%E8%A7%A3%E5%8F%91%E7%8E%B0%E6%9C%BA%E5%88%B6) -------------------------------------------------------------------------------------------------------- 对于项目本地路径,OpenCode 会从当前工作目录向上遍历,直到到达 git 工作树根目录。 在此过程中,它会加载 `.opencode/` 中所有匹配的 `skills/*/SKILL.md`,以及匹配的 `.claude/skills/*/SKILL.md` 或 `.agents/skills/*/SKILL.md`。 全局定义也会从 `~/.config/opencode/skills/*/SKILL.md`、`~/.claude/skills/*/SKILL.md` 和 `~/.agents/skills/*/SKILL.md` 中加载。 * * * [编写 frontmatter](https://opencode.ai/docs/zh-cn/skills/#%E7%BC%96%E5%86%99-frontmatter) ---------------------------------------------------------------------------------------- 每个 `SKILL.md` 必须以 YAML frontmatter 开头。 仅识别以下字段: * `name`(必填) * `description`(必填) * `license`(可选) * `compatibility`(可选) * `metadata`(可选,字符串到字符串的映射) 未知的 frontmatter 字段会被忽略。 * * * [验证名称](https://opencode.ai/docs/zh-cn/skills/#%E9%AA%8C%E8%AF%81%E5%90%8D%E7%A7%B0) ------------------------------------------------------------------------------------ `name` 必须满足: * 长度为 1–64 个字符 * 仅包含小写字母和数字,可用单个连字符分隔 * 不以 `-` 开头或结尾 * 不包含连续的 `--` * 与包含 `SKILL.md` 的目录名称一致 等效的正则表达式: ^[a-z0-9]+(-[a-z0-9]+)*$ * * * [遵循长度规则](https://opencode.ai/docs/zh-cn/skills/#%E9%81%B5%E5%BE%AA%E9%95%BF%E5%BA%A6%E8%A7%84%E5%88%99) -------------------------------------------------------------------------------------------------------- `description` 必须为 1-1024 个字符。 请保持描述足够具体,以便代理能够正确选择。 * * * [使用示例](https://opencode.ai/docs/zh-cn/skills/#%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B) ------------------------------------------------------------------------------------ 创建 `.opencode/skills/git-release/SKILL.md`,内容如下: ---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata: audience: maintainers workflow: github--- ## What I do - Draft release notes from merged PRs- Propose a version bump- Provide a copy-pasteable `gh release create` command ## When to use me Use this when you are preparing a tagged release.Ask clarifying questions if the target versioning scheme is unclear. * * * [识别工具描述](https://opencode.ai/docs/zh-cn/skills/#%E8%AF%86%E5%88%AB%E5%B7%A5%E5%85%B7%E6%8F%8F%E8%BF%B0) -------------------------------------------------------------------------------------------------------- OpenCode 会在 `skill` 工具描述中列出可用技能。 每个条目包含技能名称和描述: git-release Create consistent releases and changelogs 代理通过调用工具来加载技能: skill({ name: "git-release" }) * * * [配置权限](https://opencode.ai/docs/zh-cn/skills/#%E9%85%8D%E7%BD%AE%E6%9D%83%E9%99%90) ------------------------------------------------------------------------------------ 在 `opencode.json` 中使用基于模式的权限来控制代理可以访问哪些技能: { "permission": { "skill": { "*": "allow", "pr-review": "allow", "internal-*": "deny", "experimental-*": "ask" } }} | 权限 | 行为 | | --- | --- | | `allow` | 技能立即加载 | | `deny` | 对代理隐藏技能,拒绝访问 | | `ask` | 加载前提示用户确认 | 模式支持通配符:`internal-*` 可匹配 `internal-docs`、`internal-tools` 等。 * * * [按代理覆盖权限](https://opencode.ai/docs/zh-cn/skills/#%E6%8C%89%E4%BB%A3%E7%90%86%E8%A6%86%E7%9B%96%E6%9D%83%E9%99%90) ------------------------------------------------------------------------------------------------------------------ 为特定代理授予与全局默认值不同的权限。 **自定义代理**(在代理 frontmatter 中): ---permission: skill: "documents-*": "allow"--- **内置代理**(在 `opencode.json` 中): { "agent": { "plan": { "permission": { "skill": { "internal-*": "allow" } } } }} * * * [禁用技能工具](https://opencode.ai/docs/zh-cn/skills/#%E7%A6%81%E7%94%A8%E6%8A%80%E8%83%BD%E5%B7%A5%E5%85%B7) -------------------------------------------------------------------------------------------------------- 为不需要使用技能的代理完全禁用技能功能: **自定义代理**: ---tools: skill: false--- **内置代理**: { "agent": { "plan": { "tools": { "skill": false } } }} 禁用后,`` 部分将被完全省略。 * * * [排查加载问题](https://opencode.ai/docs/zh-cn/skills/#%E6%8E%92%E6%9F%A5%E5%8A%A0%E8%BD%BD%E9%97%AE%E9%A2%98) -------------------------------------------------------------------------------------------------------- 如果某个技能没有显示: 1. 确认 `SKILL.md` 文件名全部为大写字母 2. 检查 frontmatter 是否包含 `name` 和 `description` 3. 确保技能名称在所有位置中唯一 4. 检查权限设置——设为 `deny` 的技能会对代理隐藏 --- # References | OpenCode [Gå til indhold](https://opencode.ai/docs/da/references/#_top) References ========== Add local directories and Git repositories as project references. Dette indhold er ikke tilgængeligt i dit sprog endnu. References give OpenCode access to directories outside the current project. Use them to make documentation, shared libraries, examples, or another repository available while you work. References are configured by alias in `opencode.json` or `opencode.jsonc`. { "$schema": "https://opencode.ai/config.json", "references": { "docs": { "path": "../product-docs", "description": "Use for product behavior and documentation conventions", }, "sdk": { "repository": "anomalyco/opencode-sdk-js", "branch": "main", "description": "Use for JavaScript SDK implementation details", }, },} * * * [Local directories](https://opencode.ai/docs/da/references/#local-directories) ------------------------------------------------------------------------------- Use `path` to reference a local directory. { "references": { "docs": { "path": "../docs", }, },} Paths can be: * Relative to the config file that defines the reference * Absolute, such as `/home/user/docs` * Relative to your home directory, such as `~/docs` You can also use a string shorthand: { "references": { "docs": "../docs", },} * * * [Git repositories](https://opencode.ai/docs/da/references/#git-repositories) ----------------------------------------------------------------------------- Use `repository` to reference a Git repository. OpenCode materializes the repository in its local repository cache and makes the checked-out source available as a reference directory. { "references": { "effect": { "repository": "Effect-TS/effect", "branch": "main", }, },} `repository` accepts Git URLs, host/path references, and GitHub `owner/repo` shorthand. The optional `branch` field selects a branch or ref. Without `branch`, OpenCode uses the repository’s default branch. You can use string shorthand when you do not need a branch, description, or other options: { "references": { "effect": "Effect-TS/effect", },} * * * [Describe usage](https://opencode.ai/docs/da/references/#describe-usage) ------------------------------------------------------------------------- Add `description` to explain when an agent should use a reference. { "references": { "design-system": { "path": "../design-system", "description": "Use when implementing UI components or design tokens", }, },} OpenCode includes references with descriptions in agent context. Descriptions should be short and specific enough to distinguish references with similar content. References without descriptions remain available through autocomplete and direct use, but are not advertised to agents. * * * [Hide autocomplete entries](https://opencode.ai/docs/da/references/#hide-autocomplete-entries) ----------------------------------------------------------------------------------------------- Set `hidden` to `true` to omit a reference from `@` autocomplete in the TUI. { "references": { "internal": { "path": "../internal", "description": "Use for internal implementation details", "hidden": true, }, },} `hidden` only affects autocomplete. A hidden reference with a description remains included in agent context. * * * [Use references](https://opencode.ai/docs/da/references/#use-references) ------------------------------------------------------------------------- Configured references appear in TUI `@` autocomplete. Type `@alias` to attach the reference root, or `@alias/` to search for files inside it. Compare this implementation with @sdk/src/client.ts Agents also receive the resolved paths and descriptions of configured references that have descriptions in their system context, so they can inspect a reference when it is relevant without you attaching it manually. OpenCode automatically allows reference directories through its external-directory permission boundary. Normal tool permissions still apply; for example, an agent that cannot edit files does not gain edit access because a directory is configured as a reference. * * * [Configure fields](https://opencode.ai/docs/da/references/#configure-fields) ----------------------------------------------------------------------------- | Field | Local | Git | Description | | --- | --- | --- | --- | | `path` | Yes | No | Local reference directory | | `repository` | No | Yes | Git URL, host/path, or GitHub `owner/repo` value | | `branch` | No | Yes | Optional Git branch or ref | | `description` | Yes | Yes | Guidance describing when to use the reference | | `hidden` | Yes | Yes | Hide the reference from TUI `@` autocomplete | Reference aliases cannot be empty or contain `/`, whitespace, backticks, or commas. --- # References | OpenCode [跳转到内容](https://opencode.ai/docs/zh-cn/references/#_top) References ========== Add local directories and Git repositories as project references. 此内容尚不支持你的语言。 References give OpenCode access to directories outside the current project. Use them to make documentation, shared libraries, examples, or another repository available while you work. References are configured by alias in `opencode.json` or `opencode.jsonc`. { "$schema": "https://opencode.ai/config.json", "references": { "docs": { "path": "../product-docs", "description": "Use for product behavior and documentation conventions", }, "sdk": { "repository": "anomalyco/opencode-sdk-js", "branch": "main", "description": "Use for JavaScript SDK implementation details", }, },} * * * [Local directories](https://opencode.ai/docs/zh-cn/references/#local-directories) ---------------------------------------------------------------------------------- Use `path` to reference a local directory. { "references": { "docs": { "path": "../docs", }, },} Paths can be: * Relative to the config file that defines the reference * Absolute, such as `/home/user/docs` * Relative to your home directory, such as `~/docs` You can also use a string shorthand: { "references": { "docs": "../docs", },} * * * [Git repositories](https://opencode.ai/docs/zh-cn/references/#git-repositories) -------------------------------------------------------------------------------- Use `repository` to reference a Git repository. OpenCode materializes the repository in its local repository cache and makes the checked-out source available as a reference directory. { "references": { "effect": { "repository": "Effect-TS/effect", "branch": "main", }, },} `repository` accepts Git URLs, host/path references, and GitHub `owner/repo` shorthand. The optional `branch` field selects a branch or ref. Without `branch`, OpenCode uses the repository’s default branch. You can use string shorthand when you do not need a branch, description, or other options: { "references": { "effect": "Effect-TS/effect", },} * * * [Describe usage](https://opencode.ai/docs/zh-cn/references/#describe-usage) ---------------------------------------------------------------------------- Add `description` to explain when an agent should use a reference. { "references": { "design-system": { "path": "../design-system", "description": "Use when implementing UI components or design tokens", }, },} OpenCode includes references with descriptions in agent context. Descriptions should be short and specific enough to distinguish references with similar content. References without descriptions remain available through autocomplete and direct use, but are not advertised to agents. * * * [Hide autocomplete entries](https://opencode.ai/docs/zh-cn/references/#hide-autocomplete-entries) -------------------------------------------------------------------------------------------------- Set `hidden` to `true` to omit a reference from `@` autocomplete in the TUI. { "references": { "internal": { "path": "../internal", "description": "Use for internal implementation details", "hidden": true, }, },} `hidden` only affects autocomplete. A hidden reference with a description remains included in agent context. * * * [Use references](https://opencode.ai/docs/zh-cn/references/#use-references) ---------------------------------------------------------------------------- Configured references appear in TUI `@` autocomplete. Type `@alias` to attach the reference root, or `@alias/` to search for files inside it. Compare this implementation with @sdk/src/client.ts Agents also receive the resolved paths and descriptions of configured references that have descriptions in their system context, so they can inspect a reference when it is relevant without you attaching it manually. OpenCode automatically allows reference directories through its external-directory permission boundary. Normal tool permissions still apply; for example, an agent that cannot edit files does not gain edit access because a directory is configured as a reference. * * * [Configure fields](https://opencode.ai/docs/zh-cn/references/#configure-fields) -------------------------------------------------------------------------------- | Field | Local | Git | Description | | --- | --- | --- | --- | | `path` | Yes | No | Local reference directory | | `repository` | No | Yes | Git URL, host/path, or GitHub `owner/repo` value | | `branch` | No | Yes | Optional Git branch or ref | | `description` | Yes | Yes | Guidance describing when to use the reference | | `hidden` | Yes | Yes | Hide the reference from TUI `@` autocomplete | Reference aliases cannot be empty or contain `/`, whitespace, backticks, or commas. --- # 自訂工具 | 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. --- # References | OpenCode [콘텐츠로 이동](https://opencode.ai/docs/ko/references/#_top) References ========== Add local directories and Git repositories as project references. 이 콘텐츠는 아직 번역되지 않았습니다. References give OpenCode access to directories outside the current project. Use them to make documentation, shared libraries, examples, or another repository available while you work. References are configured by alias in `opencode.json` or `opencode.jsonc`. { "$schema": "https://opencode.ai/config.json", "references": { "docs": { "path": "../product-docs", "description": "Use for product behavior and documentation conventions", }, "sdk": { "repository": "anomalyco/opencode-sdk-js", "branch": "main", "description": "Use for JavaScript SDK implementation details", }, },} * * * [Local directories](https://opencode.ai/docs/ko/references/#local-directories) ------------------------------------------------------------------------------- Use `path` to reference a local directory. { "references": { "docs": { "path": "../docs", }, },} Paths can be: * Relative to the config file that defines the reference * Absolute, such as `/home/user/docs` * Relative to your home directory, such as `~/docs` You can also use a string shorthand: { "references": { "docs": "../docs", },} * * * [Git repositories](https://opencode.ai/docs/ko/references/#git-repositories) ----------------------------------------------------------------------------- Use `repository` to reference a Git repository. OpenCode materializes the repository in its local repository cache and makes the checked-out source available as a reference directory. { "references": { "effect": { "repository": "Effect-TS/effect", "branch": "main", }, },} `repository` accepts Git URLs, host/path references, and GitHub `owner/repo` shorthand. The optional `branch` field selects a branch or ref. Without `branch`, OpenCode uses the repository’s default branch. You can use string shorthand when you do not need a branch, description, or other options: { "references": { "effect": "Effect-TS/effect", },} * * * [Describe usage](https://opencode.ai/docs/ko/references/#describe-usage) ------------------------------------------------------------------------- Add `description` to explain when an agent should use a reference. { "references": { "design-system": { "path": "../design-system", "description": "Use when implementing UI components or design tokens", }, },} OpenCode includes references with descriptions in agent context. Descriptions should be short and specific enough to distinguish references with similar content. References without descriptions remain available through autocomplete and direct use, but are not advertised to agents. * * * [Hide autocomplete entries](https://opencode.ai/docs/ko/references/#hide-autocomplete-entries) ----------------------------------------------------------------------------------------------- Set `hidden` to `true` to omit a reference from `@` autocomplete in the TUI. { "references": { "internal": { "path": "../internal", "description": "Use for internal implementation details", "hidden": true, }, },} `hidden` only affects autocomplete. A hidden reference with a description remains included in agent context. * * * [Use references](https://opencode.ai/docs/ko/references/#use-references) ------------------------------------------------------------------------- Configured references appear in TUI `@` autocomplete. Type `@alias` to attach the reference root, or `@alias/` to search for files inside it. Compare this implementation with @sdk/src/client.ts Agents also receive the resolved paths and descriptions of configured references that have descriptions in their system context, so they can inspect a reference when it is relevant without you attaching it manually. OpenCode automatically allows reference directories through its external-directory permission boundary. Normal tool permissions still apply; for example, an agent that cannot edit files does not gain edit access because a directory is configured as a reference. * * * [Configure fields](https://opencode.ai/docs/ko/references/#configure-fields) ----------------------------------------------------------------------------- | Field | Local | Git | Description | | --- | --- | --- | --- | | `path` | Yes | No | Local reference directory | | `repository` | No | Yes | Git URL, host/path, or GitHub `owner/repo` value | | `branch` | No | Yes | Optional Git branch or ref | | `description` | Yes | Yes | Guidance describing when to use the reference | | `hidden` | Yes | Yes | Hide the reference from TUI `@` autocomplete | Reference aliases cannot be empty or contain `/`, whitespace, backticks, or commas. --- # 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. --- # 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. --- # 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) 유틸리티를 사용합니다. --- # 自定义工具 | 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 脚本。 --- # 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. ---