From 1c31c2dd977d6e1c3a8e2e33cb6d4717b7897e7a Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Tue, 2 Sep 2025 23:30:26 -0400 Subject: wip: zen --- packages/web/src/content/docs/agents.mdx | 629 +++++++++++++++ packages/web/src/content/docs/cli.mdx | 238 ++++++ packages/web/src/content/docs/commands.mdx | 271 +++++++ packages/web/src/content/docs/config.mdx | 364 +++++++++ packages/web/src/content/docs/docs/agents.mdx | 629 --------------- packages/web/src/content/docs/docs/cli.mdx | 238 ------ packages/web/src/content/docs/docs/commands.mdx | 271 ------- packages/web/src/content/docs/docs/config.mdx | 364 --------- packages/web/src/content/docs/docs/enterprise.mdx | 105 --- packages/web/src/content/docs/docs/formatters.mdx | 108 --- packages/web/src/content/docs/docs/github.mdx | 131 --- packages/web/src/content/docs/docs/gitlab.mdx | 151 ---- packages/web/src/content/docs/docs/ide.mdx | 46 -- packages/web/src/content/docs/docs/index.mdx | 311 -------- packages/web/src/content/docs/docs/keybinds.mdx | 75 -- packages/web/src/content/docs/docs/lsp.mdx | 101 --- packages/web/src/content/docs/docs/mcp-servers.mdx | 128 --- packages/web/src/content/docs/docs/models.mdx | 128 --- packages/web/src/content/docs/docs/modes.mdx | 331 -------- packages/web/src/content/docs/docs/permissions.mdx | 115 --- packages/web/src/content/docs/docs/plugins.mdx | 105 --- packages/web/src/content/docs/docs/providers.mdx | 887 --------------------- packages/web/src/content/docs/docs/rules.mdx | 152 ---- packages/web/src/content/docs/docs/sdk.mdx | 359 --------- packages/web/src/content/docs/docs/server.mdx | 180 ----- packages/web/src/content/docs/docs/share.mdx | 128 --- packages/web/src/content/docs/docs/themes.mdx | 368 --------- .../web/src/content/docs/docs/troubleshooting.mdx | 156 ---- packages/web/src/content/docs/docs/tui.mdx | 315 -------- packages/web/src/content/docs/docs/zen.mdx | 95 --- packages/web/src/content/docs/enterprise.mdx | 105 +++ packages/web/src/content/docs/formatters.mdx | 108 +++ packages/web/src/content/docs/github.mdx | 131 +++ packages/web/src/content/docs/gitlab.mdx | 151 ++++ packages/web/src/content/docs/ide.mdx | 46 ++ packages/web/src/content/docs/index.mdx | 319 +++++++- packages/web/src/content/docs/keybinds.mdx | 75 ++ packages/web/src/content/docs/lsp.mdx | 101 +++ packages/web/src/content/docs/mcp-servers.mdx | 128 +++ packages/web/src/content/docs/models.mdx | 128 +++ packages/web/src/content/docs/modes.mdx | 331 ++++++++ packages/web/src/content/docs/permissions.mdx | 115 +++ packages/web/src/content/docs/plugins.mdx | 105 +++ packages/web/src/content/docs/providers.mdx | 887 +++++++++++++++++++++ packages/web/src/content/docs/rules.mdx | 152 ++++ packages/web/src/content/docs/sdk.mdx | 359 +++++++++ packages/web/src/content/docs/server.mdx | 180 +++++ packages/web/src/content/docs/share.mdx | 128 +++ packages/web/src/content/docs/themes.mdx | 368 +++++++++ packages/web/src/content/docs/troubleshooting.mdx | 156 ++++ packages/web/src/content/docs/tui.mdx | 315 ++++++++ packages/web/src/content/docs/zen.mdx | 95 +++ 52 files changed, 5975 insertions(+), 5987 deletions(-) create mode 100644 packages/web/src/content/docs/agents.mdx create mode 100644 packages/web/src/content/docs/cli.mdx create mode 100644 packages/web/src/content/docs/commands.mdx create mode 100644 packages/web/src/content/docs/config.mdx delete mode 100644 packages/web/src/content/docs/docs/agents.mdx delete mode 100644 packages/web/src/content/docs/docs/cli.mdx delete mode 100644 packages/web/src/content/docs/docs/commands.mdx delete mode 100644 packages/web/src/content/docs/docs/config.mdx delete mode 100644 packages/web/src/content/docs/docs/enterprise.mdx delete mode 100644 packages/web/src/content/docs/docs/formatters.mdx delete mode 100644 packages/web/src/content/docs/docs/github.mdx delete mode 100644 packages/web/src/content/docs/docs/gitlab.mdx delete mode 100644 packages/web/src/content/docs/docs/ide.mdx delete mode 100644 packages/web/src/content/docs/docs/index.mdx delete mode 100644 packages/web/src/content/docs/docs/keybinds.mdx delete mode 100644 packages/web/src/content/docs/docs/lsp.mdx delete mode 100644 packages/web/src/content/docs/docs/mcp-servers.mdx delete mode 100644 packages/web/src/content/docs/docs/models.mdx delete mode 100644 packages/web/src/content/docs/docs/modes.mdx delete mode 100644 packages/web/src/content/docs/docs/permissions.mdx delete mode 100644 packages/web/src/content/docs/docs/plugins.mdx delete mode 100644 packages/web/src/content/docs/docs/providers.mdx delete mode 100644 packages/web/src/content/docs/docs/rules.mdx delete mode 100644 packages/web/src/content/docs/docs/sdk.mdx delete mode 100644 packages/web/src/content/docs/docs/server.mdx delete mode 100644 packages/web/src/content/docs/docs/share.mdx delete mode 100644 packages/web/src/content/docs/docs/themes.mdx delete mode 100644 packages/web/src/content/docs/docs/troubleshooting.mdx delete mode 100644 packages/web/src/content/docs/docs/tui.mdx delete mode 100644 packages/web/src/content/docs/docs/zen.mdx create mode 100644 packages/web/src/content/docs/enterprise.mdx create mode 100644 packages/web/src/content/docs/formatters.mdx create mode 100644 packages/web/src/content/docs/github.mdx create mode 100644 packages/web/src/content/docs/gitlab.mdx create mode 100644 packages/web/src/content/docs/ide.mdx create mode 100644 packages/web/src/content/docs/keybinds.mdx create mode 100644 packages/web/src/content/docs/lsp.mdx create mode 100644 packages/web/src/content/docs/mcp-servers.mdx create mode 100644 packages/web/src/content/docs/models.mdx create mode 100644 packages/web/src/content/docs/modes.mdx create mode 100644 packages/web/src/content/docs/permissions.mdx create mode 100644 packages/web/src/content/docs/plugins.mdx create mode 100644 packages/web/src/content/docs/providers.mdx create mode 100644 packages/web/src/content/docs/rules.mdx create mode 100644 packages/web/src/content/docs/sdk.mdx create mode 100644 packages/web/src/content/docs/server.mdx create mode 100644 packages/web/src/content/docs/share.mdx create mode 100644 packages/web/src/content/docs/themes.mdx create mode 100644 packages/web/src/content/docs/troubleshooting.mdx create mode 100644 packages/web/src/content/docs/tui.mdx create mode 100644 packages/web/src/content/docs/zen.mdx (limited to 'packages/web/src') diff --git a/packages/web/src/content/docs/agents.mdx b/packages/web/src/content/docs/agents.mdx new file mode 100644 index 000000000..1527a1b08 --- /dev/null +++ b/packages/web/src/content/docs/agents.mdx @@ -0,0 +1,629 @@ +--- +title: Agents +description: Configure and use specialized agents. +--- + +Agents are specialized AI assistants that can be configured for specific tasks and workflows. They allow you to create focused tools with custom prompts, models, and tool access. + +:::tip +Use the plan agent to analyze code and review suggestions without making any code changes. +::: + +You can switch between agents during a session or invoke them with the `@` mention. + +--- + +## Types + +There are two types of agents in opencode; primary agents and subagents. + +--- + +### Primary agents + +Primary agents are the main assistants you interact with directly. You can cycle through them using the **Tab** key, or your configured `switch_agent` keybind. These agents handle your main conversation and can access all configured tools. + +:::tip +You can use the **Tab** key to switch between primary agents during a session. +::: + +opencode comes with two built-in primary agents, **Build** and **Plan**. We'll +look at these below. + +--- + +### Subagents + +Subagents are specialized assistants that primary agents can invoke for specific tasks. You can also manually invoke them by **@ mentioning** them in your messages. + +opencode comes with one built-in subagent, **General**. We'll look at this below. + +--- + +## Built-in + +opencode comes with two built-in primary agents and one built-in subagent. + +--- + +### Build + +_Mode_: `primary` + +Build is the **default** primary agent with all tools enabled. This is the standard agent for development work where you need full access to file operations and system commands. + +--- + +### Plan + +_Mode_: `primary` + +A restricted agent designed for planning and analysis. We use a permission system to give you more control and prevent unintended changes. +By default, all of the following are set to `ask`: + +- `file edits`: All writes, patches, and edits +- `bash`: All bash commands + +This agent is useful when you want the LLM to analyze code, suggest changes, or create plans without making any actual modifications to your codebase. + +--- + +### General + +_Mode_: `subagent` + +A general-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. Use when searching for keywords or files and you're not confident you'll find the right match in the first few tries. + +--- + +## Usage + +1. For primary agents, use the **Tab** key to cycle through them during a session. You can also use your configured `switch_agent` keybind. + +2. Subagents can be invoked: + + - **Automatically** by primary agents for specialized tasks based on their descriptions. + - Manually by **@ mentioning** a subagent in your message. For example. + + ```txt frame="none" + @general help me search for this function + ``` + +3. **Navigation between sessions**: When subagents create their own child sessions, you can navigate between the parent session and all child sessions using: + + - **Ctrl+Right** (or your configured `session_child_cycle` keybind) to cycle forward through parent → child1 → child2 → ... → parent + - **Ctrl+Left** (or your configured `session_child_cycle_reverse` keybind) to cycle backward through parent ← child1 ← child2 ← ... ← parent + + This allows you to seamlessly switch between the main conversation and specialized subagent work. + +--- + +## Configure + +You can customize the built-in agents or create your own through configuration. Agents can be configured in two ways: + +--- + +### JSON + +Configure agents in your `opencode.json` config file: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "mode": "primary", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "mode": "primary", + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + }, + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "mode": "subagent", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + "write": false, + "edit": false + } + } + } +} +``` + +--- + +### Markdown + +You can also define agents using markdown files. Place them in: + +- Global: `~/.config/opencode/agent/` +- Per-project: `.opencode/agent/` + +```markdown title="~/.config/opencode/agent/review.md" +--- +description: Reviews code for quality and best practices +mode: subagent +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +The markdown file name becomes the agent name. For example, `review.md` creates a `review` agent. + +--- + +## Options + +Let's look at these configuration options in detail. + +--- + +### Description + +Use the `description` option to provide a brief description of what the agent does and when to use it. + +```json title="opencode.json" +{ + "agent": { + "review": { + "description": "Reviews code for best practices and potential issues" + } + } +} +``` + +This is a **required** config option. + +--- + +### Temperature + +Control the randomness and creativity of the LLM's responses with the `temperature` config. + +Lower values make responses more focused and deterministic, while higher values increase creativity and variability. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperature values typically range from 0.0 to 1.0: + +- **0.0-0.2**: Very focused and deterministic responses, ideal for code analysis and planning +- **0.3-0.5**: Balanced responses with some creativity, good for general development tasks +- **0.6-1.0**: More creative and varied responses, useful for brainstorming and exploration + +```json title="opencode.json" +{ + "agent": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +If no temperature is specified, opencode uses model-specific defaults; typically 0 for most models, 0.55 for Qwen models. + +--- + +### Disable + +Set to `true` to disable the agent. + +```json title="opencode.json" +{ + "agent": { + "review": { + "disable": true + } + } +} +``` + +--- + +### Prompt + +Specify a custom system prompt file for this agent with the `prompt` config. The prompt file should contain instructions specific to the agent's purpose. + +```json title="opencode.json" +{ + "agent": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +This path is relative to where the config file is located. So this works for both the global opencode config and the project specific config. + +--- + +### Model + +Use the `model` config to override the default model for this agent. Useful for using different models optimized for different tasks. For example, a faster model for planning, a more capable model for implementation. + +```json title="opencode.json" +{ + "agent": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Tools + +Control which tools are available in this agent with the `tools` config. You can enable or disable specific tools by setting them to `true` or `false`. + +```json title="opencode.json" +{ + "agent": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +You can also use wildcards to control multiple tools at once. For example, to disable all tools from an MCP server: + +```json title="opencode.json" +{ + "agent": { + "readonly": { + "tools": { + "mymcp_*": false, + "write": false, + "edit": false + } + } + } +} +``` + +If no tools are specified, all tools are enabled by default. + +--- + +#### Available tools + +Here are all the tools can be controlled through the agent config. + +| Tool | Description | +| ----------- | ----------------------- | +| `bash` | Execute shell commands | +| `edit` | Modify existing files | +| `write` | Create new files | +| `read` | Read file contents | +| `grep` | Search file contents | +| `glob` | Find files by pattern | +| `list` | List directory contents | +| `patch` | Apply patches to files | +| `todowrite` | Manage todo lists | +| `todoread` | Read todo lists | +| `webfetch` | Fetch web content | + +--- + +### Permissions + +Permissions control what actions an agent can take. + +- edit, bash, webfetch + +Each permission can be set to allow, ask, or deny. + +- allow, ask, deny + +Configure permissions globally in opencode.json. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "allow", + "webfetch": "deny" + } +} +``` + +You can override permissions per agent in JSON. + +```json title="opencode.json" {7-18} +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "build": { + "permission": { + "edit": "allow", + "bash": { + "*": "allow", + "git push": "ask", + "terraform *": "deny" + }, + "webfetch": "ask" + } + } + } +} +``` + +You can also set permissions in Markdown agents. + +```markdown title="~/.config/opencode/agent/review.md" +--- +description: Code review without edits +mode: subagent +permission: + edit: deny + bash: ask + webfetch: deny +--- + +Only analyze code and suggest changes. +``` + +Bash permissions support granular patterns for fine-grained control. + +```json title="Allow most, ask for risky, deny terraform" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "*": "allow", + "git push": "ask", + "terraform *": "deny" + } + } +} +``` + +If you provide a granular bash map, the default becomes ask unless you set \* explicitly. + +```json title="Granular defaults to ask" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "git status": "allow" + } + } +} +``` + +Agent-level permissions merge over global settings. + +- Global sets defaults; agent overrides when specified + +Specific bash rules can override a global default. + +```json title="Global ask, agent allows safe commands" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { "bash": "ask" }, + "agent": { + "build": { + "permission": { + "bash": { "git status": "allow", "*": "ask" } + } + } + } +} +``` + +Permissions affect tool availability and prompts differently. + +- deny hides tools (edit also hides write/patch); ask prompts; allow runs + +For quick reference, here are common setups. + +```json title="Read-only reviewer" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "review": { + "permission": { "edit": "deny", "bash": "deny", "webfetch": "allow" } + } + } +} +``` + +```json title="Planning agent that can browse but cannot change code" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "plan": { + "permission": { "edit": "deny", "bash": "deny", "webfetch": "ask" } + } + } +} +``` + +See the full permissions guide for more patterns. + +- /docs/permissions + +--- + +### Mode + +Control the agent's mode with the `mode` config. The `mode` option is used to determine how the agent can be used. + +```json title="opencode.json" +{ + "agent": { + "review": { + "mode": "subagent" + } + } +} +``` + +The `mode` option can be set to `primary`, `subagent`, or `all`. If no `mode` is specified, it defaults to `all`. + +--- + +### Additional + +Any other options you specify in your agent configuration will be **passed through directly** to the provider as model options. This allows you to use provider-specific features and parameters. + +For example, with OpenAI's reasoning models, you can control the reasoning effort: + +```json title="opencode.json" {6,7} +{ + "agent": { + "deep-thinker": { + "description": "Agent that uses high reasoning effort for complex problems", + "model": "openai/gpt-5", + "reasoningEffort": "high", + "textVerbosity": "low" + } + } +} +``` + +These additional options are model and provider-specific. Check your provider's documentation for available parameters. + +--- + +## Create agents + +You can create new agents using the following command: + +```bash +opencode agent create +``` + +This interactive command will: + +1. Ask where to save the agent; global or project-specific. +2. Description of what the agent should do. +3. Generate an appropriate system prompt and identifier. +4. Let you select which tools the agent can access. +5. Finally, create a markdown file with the agent configuration. + +--- + +## Use cases + +Here are some common use cases for different agents. + +- **Build agent**: Full development work with all tools enabled +- **Plan agent**: Analysis and planning without making changes +- **Review agent**: Code review with read-only access plus documentation tools +- **Debug agent**: Focused on investigation with bash and read tools enabled +- **Docs agent**: Documentation writing with file operations but no system commands + +--- + +## Examples + +Here are some examples agents you might find useful. + +:::tip +Do you have an agent you'd like to share? [Submit a PR](https://github.com/sst/opencode). +::: + +--- + +### Documentation agent + +```markdown title="~/.config/opencode/agent/docs-writer.md" +--- +description: Writes and maintains project documentation +mode: subagent +tools: + bash: false +--- + +You are a technical writer. Create clear, comprehensive documentation. + +Focus on: + +- Clear explanations +- Proper structure +- Code examples +- User-friendly language +``` + +--- + +### Security auditor + +```markdown title="~/.config/opencode/agent/security-auditor.md" +--- +description: Performs security audits and identifies vulnerabilities +mode: subagent +tools: + write: false + edit: false +--- + +You are a security expert. Focus on identifying potential security issues. + +Look for: + +- Input validation vulnerabilities +- Authentication and authorization flaws +- Data exposure risks +- Dependency vulnerabilities +- Configuration security issues +``` diff --git a/packages/web/src/content/docs/cli.mdx b/packages/web/src/content/docs/cli.mdx new file mode 100644 index 000000000..903c3638d --- /dev/null +++ b/packages/web/src/content/docs/cli.mdx @@ -0,0 +1,238 @@ +--- +title: CLI +description: opencode CLI options and commands. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +The opencode CLI by default starts the [TUI](/docs/tui) when run without any arguments. + +```bash +opencode +``` + +But it also accepts commands as documented on this page. This allows you to interact with opencode programmatically. + +```bash +opencode run "Explain how closures work in JavaScript" +``` + + + +--- + +## Commands + +The opencode CLI also has the following commands. + +--- + +### agent + +Manage agents for opencode. + +```bash +opencode agent [command] +``` + +--- + +#### create + +Create a new agent with custom configuration. + +```bash +opencode agent create +``` + +This command will guide you through creating a new agent with a custom system prompt and tool configuration. + +--- + +### auth + +Command to manage credentials and login for providers. + +```bash +opencode auth [command] +``` + +--- + +#### login + +opencode is powered by the provider list at [Models.dev](https://models.dev), so you can use `opencode auth login` to configure API keys for any provider you'd like to use. This is stored in `~/.local/share/opencode/auth.json`. + +```bash +opencode auth login +``` + +When opencode starts up it loads the providers from the credentials file. And if there are any keys defined in your environments or a `.env` file in your project. + +--- + +#### list + +Lists all the authenticated providers as stored in the credentials file. + +```bash +opencode auth list +``` + +Or the short version. + +```bash +opencode auth ls +``` + +--- + +#### logout + +Logs you out of a provider by clearing it from the credentials file. + +```bash +opencode auth logout +``` + +--- + +### github + +Manage the GitHub agent for repository automation. + +```bash +opencode github [command] +``` + +--- + +#### install + +Install the GitHub agent in your repository. + +```bash +opencode github install +``` + +This sets up the necessary GitHub Actions workflow and guides you through the configuration process. [Learn more](/docs/github). + +--- + +#### run + +Run the GitHub agent. This is typically used in GitHub Actions. + +```bash +opencode github run +``` + +##### Flags + +| Flag | Description | +| --------- | -------------------------------------- | +| `--event` | GitHub mock event to run the agent for | +| `--token` | GitHub personal access token | + +--- + +### models + +List all available models from configured providers. + +```bash +opencode models +``` + +This command displays all models available across your configured providers in the format `provider/model`. + +--- + +### run + +Run opencode in non-interactive mode by passing a prompt directly. + +```bash +opencode run [message..] +``` + +This is useful for scripting, automation, or when you want a quick answer without launching the full TUI. For example. + +```bash "opencode run" +opencode run Explain the use of context in Go +``` + +#### Flags + +| Flag | Short | Description | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Continue the last session | +| `--session` | `-s` | Session ID to continue | +| `--share` | | Share the session | +| `--model` | `-m` | Model to use in the form of provider/model | +| `--agent` | | Agent to use | + +--- + +### serve + +Start a headless opencode server for API access. Check out the [server docs](/docs/server) for the full HTTP interface. + +```bash +opencode serve +``` + +This starts an HTTP server that provides API access to opencode functionality without the TUI interface. + +#### Flags + +| Flag | Short | Description | +| ------------ | ----- | --------------------- | +| `--port` | `-p` | Port to listen on | +| `--hostname` | `-h` | Hostname to listen on | + +--- + +### upgrade + +Updates opencode to the latest version or a specific version. + +```bash +opencode upgrade [target] +``` + +To upgrade to the latest version. + +```bash +opencode upgrade +``` + +To upgrade to a specific version. + +```bash +opencode upgrade v0.1.48 +``` + +#### Flags + +| Flag | Short | Description | +| ---------- | ----- | ----------------------------------------------------------------- | +| `--method` | `-m` | The installation method that was used; curl, npm, pnpm, bun, brew | + +--- + +## Flags + +The opencode CLI takes the following global flags. + +| Flag | Short | Description | +| -------------- | ----- | ------------------------------------------ | +| `--help` | `-h` | Display help | +| `--version` | | Print version number | +| `--print-logs` | | Print logs to stderr | +| `--log-level` | | Log level (DEBUG, INFO, WARN, ERROR) | +| `--prompt` | `-p` | Prompt to use | +| `--model` | `-m` | Model to use in the form of provider/model | +| `--agent` | | Agent to use | +| `--port` | | Port to listen on | +| `--hostname` | | Hostname to listen on | diff --git a/packages/web/src/content/docs/commands.mdx b/packages/web/src/content/docs/commands.mdx new file mode 100644 index 000000000..59c9536ac --- /dev/null +++ b/packages/web/src/content/docs/commands.mdx @@ -0,0 +1,271 @@ +--- +title: Commands +description: Create custom commands for repetitive tasks. +--- + +Custom commands let you specify a prompt you want to run when that command is executed in the TUI. + +```bash frame="none" +/my-command +``` + +Custom commands are in addition to the built-in commands like `/init`, `/undo`, `/redo`, `/share`, `/help`. [Learn more](/docs/tui#commands). + +--- + +## Create command files + +Create markdown files in the `command/` directory to define custom commands. + +Create `.opencode/command/test.md`: + +```md title=".opencode/command/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +The frontmatter defines command properties. The content becomes the template. + +Use the command by typing `/` followed by the command name. + +```bash frame="none" +"/test" +``` + +--- + +## Configure + +You can add custom commands through the opencode config or by creating markdown files in the `command/` directory. + +--- + +### JSON + +Use the `command` option in your opencode [config](/docs/config): + +```json title="opencode.jsonc" {4-12} +{ + "$schema": "https://opencode.ai/config.json", + "command": { + // This becomes the name of the command + "test": { + // This is the prompt that will be sent to the LLM + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + // This is show as the description in the TUI + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + }, + } +} +``` + +Now you can run this command in the TUI: + +```bash frame="none" +/test +``` + +--- + +### Markdown + +You can also define commands using markdown files. Place them in: + +- Global: `~/.config/opencode/command/` +- Per-project: `.opencode/command/` + +```markdown title="~/.config/opencode/command/test.md" +--- +description: Run tests with coverage +agent: build +model: anthropic/claude-3-5-sonnet-20241022 +--- + +Run the full test suite with coverage report and show any failures. +Focus on the failing tests and suggest fixes. +``` + +The markdown file name becomes the command name. For example, `test.md` lets +you run: + +```bash frame="none" +/test +``` + +--- + +## Prompt config + +The prompts for the custom commands support several special placeholders and syntax. + +--- + +### Arguments + +Pass arguments to commands using the `$ARGUMENTS` placeholder. + +```md title=".opencode/command/component.md" +--- +description: Create a new component +--- + +Create a new React component named $ARGUMENTS with TypeScript support. +Include proper typing and basic structure. +``` + +Run the command with arguments: + +```bash frame="none" +/component Button +``` + +And `$ARGUMENTS` will be replaced with `Button`. + +--- + +### Shell output + +Use _!`command`_ to inject [bash command](/docs/tui#bash-commands) output into your prompt. + +For example, to create a custom command that analyzes test coverage: + +```md title=".opencode/command/analyze-coverage.md" +--- +description: Analyze test coverage +--- + +Here are the current test results: +!`npm test` + +Based on these results, suggest improvements to increase coverage. +``` + +Or to review recent changes: + +```md title=".opencode/command/review-changes.md" +--- +description: Review recent changes +--- + +Recent git commits: +!`git log --oneline -10` + +Review these changes and suggest any improvements. +``` + +Commands run in your project's root directory and their output becomes part of the prompt. + +--- + +### File references + +Include files in your command using `@` followed by the filename. + +```md title=".opencode/command/review-component.md" +--- +description: Review component +--- + +Review the component in @src/components/Button.tsx. +Check for performance issues and suggest improvements. +``` + +The file content gets included in the prompt automatically. + +--- + +## Options + +Let's look at the configuration options in detail. + +--- + +### Template + +The `template` option defines the prompt that will be sent to the LLM when the command is executed. + +```json title="opencode.json" +{ + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." + } + } +} +``` + +This is a **required** config option. + +--- + +### Description + +Use the `description` option to provide a brief description of what the command does. + +```json title="opencode.json" +{ + "command": { + "test": { + "description": "Run tests with coverage" + } + } +} +``` + +This is shown as the description in the TUI when you type in the command. + +--- + +### Agent + +Use the `agent` config to optionally specify which [agent](/docs/agents) should execute this command. + +```json title="opencode.json" +{ + "command": { + "review": { + "agent": "plan" + } + } +} +``` + +This is an **optional** config option. If not specified, defaults to "build". + +--- + +### Model + +Use the `model` config to override the default model for this command. + +```json title="opencode.json" +{ + "command": { + "analyze": { + "model": "anthropic/claude-3-5-sonnet-20241022" + } + } +} +``` + +This is an **optional** config option. + +--- + +## Built-in + +opencode includes several built-in commands like `/init`, `/undo`, `/redo`, `/share`, `/help`; [learn more](/docs/tui#commands). + +:::note +Custom commands can override built-in commands. +::: + +If you define a custom command with the same name, it will override the built-in command. diff --git a/packages/web/src/content/docs/config.mdx b/packages/web/src/content/docs/config.mdx new file mode 100644 index 000000000..045bc596c --- /dev/null +++ b/packages/web/src/content/docs/config.mdx @@ -0,0 +1,364 @@ +--- +title: Config +description: Using the opencode JSON config. +--- + +You can configure opencode using a JSON config file. + +--- + +## Format + +opencode supports both **JSON** and **JSONC** (JSON with Comments) formats. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + // Theme configuration + "theme": "opencode", + "model": "anthropic/claude-sonnet-4-20250514", + "autoupdate": true, +} +``` + +With JSONC, you can use comments in your configuration files: + +--- + +## Locations + +You can place your config in a couple of different locations and they have a +different order of precedence. + +--- + +### Global + +Place your global opencode config in `~/.config/opencode/opencode.json`. You'll want to use the global config for things like themes, providers, or keybinds. + +--- + +### Per project + +You can also add a `opencode.json` in your project. It takes precedence over the global config. This is useful for configuring providers or modes specific to your project. + +:::tip +Place project specific config in the root of your project. +::: + +When opencode starts up, it looks for a config file in the current directory or traverse up to the nearest Git directory. + +This is also safe to be checked into Git and uses the same schema as the global one. + +--- + +### Custom path + +You can also specify a custom config file path using the `OPENCODE_CONFIG` environment variable. This takes precedence over the global and project configs. + +```bash +export OPENCODE_CONFIG=/path/to/my/custom-config.json +opencode run "Hello world" +``` + +--- + +## Schema + +The config file has a schema that's defined in [**`opencode.ai/config.json`**](https://opencode.ai/config.json). + +Your editor should be able to validate and autocomplete based on the schema. + +--- + +### Models + +You can configure the providers and models you want to use in your opencode config through the `provider`, `model` and `small_model` options. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "provider": {}, + "model": "anthropic/claude-sonnet-4-20250514", + "small_model": "anthropic/claude-3-5-haiku-20241022" +} +``` + +The `small_model` option configures a separate model for lightweight tasks like title generation. By default, opencode tries to use a cheaper model if one is available from your provider, otherwise it falls back to your main model. + +You can also configure [local models](/docs/models#local). [Learn more](/docs/models). + +--- + +### Themes + +You can configure the theme you want to use in your opencode config through the `theme` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "theme": "" +} +``` + +[Learn more here](/docs/themes). + +--- + +### Agents + +You can configure specialized agents for specific tasks through the `agent` option. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "agent": { + "code-reviewer": { + "description": "Reviews code for best practices and potential issues", + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", + "tools": { + // Disable file modification tools for review-only agent + "write": false, + "edit": false, + }, + }, + }, +} +``` + +You can also define agents using markdown files in `~/.config/opencode/agent/` or `.opencode/agent/`. [Learn more here](/docs/agents). + +--- + +### Sharing + +You can configure the [share](/docs/share) feature through the `share` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +This takes: + +- `"manual"` - Allow manual sharing via commands (default) +- `"auto"` - Automatically share new conversations +- `"disabled"` - Disable sharing entirely + +By default, sharing is set to manual mode where you need to explicitly share conversations using the `/share` command. + +--- + +### Commands + +You can configure custom commands for repetitive tasks through the `command` option. + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "command": { + "test": { + "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", + "description": "Run tests with coverage", + "agent": "build", + "model": "anthropic/claude-3-5-sonnet-20241022" + }, + "component": { + "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", + "description": "Create a new component" + } + } +} +``` + +You can also define commands using markdown files in `~/.config/opencode/command/` or `.opencode/command/`. [Learn more here](/docs/commands). + +--- + +### Keybinds + +You can customize your keybinds through the `keybinds` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": {} +} +``` + +[Learn more here](/docs/keybinds). + +--- + +### Autoupdate + +opencode will automatically download any new updates when it starts up. You can disable this with the `autoupdate` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "autoupdate": false +} +``` + +--- + +### Formatters + +You can configure code formatters through the `formatter` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + }, + "custom-prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + } + } +} +``` + +[Learn more about formatters here](/docs/formatters). + +--- + +### Permissions + +You can configure permissions to control what AI agents can do in your codebase through the `permission` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask", + "bash": "ask" + } +} +``` + +This allows you to configure explicit approval requirements for sensitive operations: + +- `edit` - Controls whether file editing operations require user approval (`"ask"` or `"allow"`) +- `bash` - Controls whether bash commands require user approval (can be `"ask"`/`"allow"` or a pattern map) + +[Learn more about permissions here](/docs/permissions). + +--- + +### MCP servers + +You can configure MCP servers you want to use through the `mcp` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": {} +} +``` + +[Learn more here](/docs/mcp-servers). + +--- + +### Instructions + +You can configure the instructions for the model you're using through the `instructions` option. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +This takes an array of paths and glob patterns to instruction files. [Learn more +about rules here](/docs/rules). + +--- + +### Disabled providers + +You can disable providers that are loaded automatically through the `disabled_providers` option. This is useful when you want to prevent certain providers from being loaded even if their credentials are available. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "disabled_providers": ["openai", "gemini"] +} +``` + +The `disabled_providers` option accepts an array of provider IDs. When a provider is disabled: + +- It won't be loaded even if environment variables are set. +- It won't be loaded even if API keys are configured through `opencode auth login`. +- The provider's models won't appear in the model selection list. + +--- + +## Variables + +You can use variable substitution in your config files to reference environment variables and file contents. + +--- + +### Env vars + +Use `{env:VARIABLE_NAME}` to substitute environment variables: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "model": "{env:OPENCODE_MODEL}", + "provider": { + "anthropic": { + "models": {}, + "options": { + "apiKey": "{env:ANTHROPIC_API_KEY}" + } + } + } +} +``` + +If the environment variable is not set, it will be replaced with an empty string. + +--- + +### Files + +Use `{file:path/to/file}` to substitute the contents of a file: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["./custom-instructions.md"], + "provider": { + "openai": { + "options": { + "apiKey": "{file:~/.secrets/openai-key}" + } + } + } +} +``` + +File paths can be: + +- Relative to the config file directory +- Or absolute paths starting with `/` or `~` + +These are useful for: + +- Keeping sensitive data like API keys in separate files. +- Including large instruction files without cluttering your config. +- Sharing common configuration snippets across multiple config files. diff --git a/packages/web/src/content/docs/docs/agents.mdx b/packages/web/src/content/docs/docs/agents.mdx deleted file mode 100644 index 1527a1b08..000000000 --- a/packages/web/src/content/docs/docs/agents.mdx +++ /dev/null @@ -1,629 +0,0 @@ ---- -title: Agents -description: Configure and use specialized agents. ---- - -Agents are specialized AI assistants that can be configured for specific tasks and workflows. They allow you to create focused tools with custom prompts, models, and tool access. - -:::tip -Use the plan agent to analyze code and review suggestions without making any code changes. -::: - -You can switch between agents during a session or invoke them with the `@` mention. - ---- - -## Types - -There are two types of agents in opencode; primary agents and subagents. - ---- - -### Primary agents - -Primary agents are the main assistants you interact with directly. You can cycle through them using the **Tab** key, or your configured `switch_agent` keybind. These agents handle your main conversation and can access all configured tools. - -:::tip -You can use the **Tab** key to switch between primary agents during a session. -::: - -opencode comes with two built-in primary agents, **Build** and **Plan**. We'll -look at these below. - ---- - -### Subagents - -Subagents are specialized assistants that primary agents can invoke for specific tasks. You can also manually invoke them by **@ mentioning** them in your messages. - -opencode comes with one built-in subagent, **General**. We'll look at this below. - ---- - -## Built-in - -opencode comes with two built-in primary agents and one built-in subagent. - ---- - -### Build - -_Mode_: `primary` - -Build is the **default** primary agent with all tools enabled. This is the standard agent for development work where you need full access to file operations and system commands. - ---- - -### Plan - -_Mode_: `primary` - -A restricted agent designed for planning and analysis. We use a permission system to give you more control and prevent unintended changes. -By default, all of the following are set to `ask`: - -- `file edits`: All writes, patches, and edits -- `bash`: All bash commands - -This agent is useful when you want the LLM to analyze code, suggest changes, or create plans without making any actual modifications to your codebase. - ---- - -### General - -_Mode_: `subagent` - -A general-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. Use when searching for keywords or files and you're not confident you'll find the right match in the first few tries. - ---- - -## Usage - -1. For primary agents, use the **Tab** key to cycle through them during a session. You can also use your configured `switch_agent` keybind. - -2. Subagents can be invoked: - - - **Automatically** by primary agents for specialized tasks based on their descriptions. - - Manually by **@ mentioning** a subagent in your message. For example. - - ```txt frame="none" - @general help me search for this function - ``` - -3. **Navigation between sessions**: When subagents create their own child sessions, you can navigate between the parent session and all child sessions using: - - - **Ctrl+Right** (or your configured `session_child_cycle` keybind) to cycle forward through parent → child1 → child2 → ... → parent - - **Ctrl+Left** (or your configured `session_child_cycle_reverse` keybind) to cycle backward through parent ← child1 ← child2 ← ... ← parent - - This allows you to seamlessly switch between the main conversation and specialized subagent work. - ---- - -## Configure - -You can customize the built-in agents or create your own through configuration. Agents can be configured in two ways: - ---- - -### JSON - -Configure agents in your `opencode.json` config file: - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "agent": { - "build": { - "mode": "primary", - "model": "anthropic/claude-sonnet-4-20250514", - "prompt": "{file:./prompts/build.txt}", - "tools": { - "write": true, - "edit": true, - "bash": true - } - }, - "plan": { - "mode": "primary", - "model": "anthropic/claude-haiku-4-20250514", - "tools": { - "write": false, - "edit": false, - "bash": false - } - }, - "code-reviewer": { - "description": "Reviews code for best practices and potential issues", - "mode": "subagent", - "model": "anthropic/claude-sonnet-4-20250514", - "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", - "tools": { - "write": false, - "edit": false - } - } - } -} -``` - ---- - -### Markdown - -You can also define agents using markdown files. Place them in: - -- Global: `~/.config/opencode/agent/` -- Per-project: `.opencode/agent/` - -```markdown title="~/.config/opencode/agent/review.md" ---- -description: Reviews code for quality and best practices -mode: subagent -model: anthropic/claude-sonnet-4-20250514 -temperature: 0.1 -tools: - write: false - edit: false - bash: false ---- - -You are in code review mode. Focus on: - -- Code quality and best practices -- Potential bugs and edge cases -- Performance implications -- Security considerations - -Provide constructive feedback without making direct changes. -``` - -The markdown file name becomes the agent name. For example, `review.md` creates a `review` agent. - ---- - -## Options - -Let's look at these configuration options in detail. - ---- - -### Description - -Use the `description` option to provide a brief description of what the agent does and when to use it. - -```json title="opencode.json" -{ - "agent": { - "review": { - "description": "Reviews code for best practices and potential issues" - } - } -} -``` - -This is a **required** config option. - ---- - -### Temperature - -Control the randomness and creativity of the LLM's responses with the `temperature` config. - -Lower values make responses more focused and deterministic, while higher values increase creativity and variability. - -```json title="opencode.json" -{ - "agent": { - "plan": { - "temperature": 0.1 - }, - "creative": { - "temperature": 0.8 - } - } -} -``` - -Temperature values typically range from 0.0 to 1.0: - -- **0.0-0.2**: Very focused and deterministic responses, ideal for code analysis and planning -- **0.3-0.5**: Balanced responses with some creativity, good for general development tasks -- **0.6-1.0**: More creative and varied responses, useful for brainstorming and exploration - -```json title="opencode.json" -{ - "agent": { - "analyze": { - "temperature": 0.1, - "prompt": "{file:./prompts/analysis.txt}" - }, - "build": { - "temperature": 0.3 - }, - "brainstorm": { - "temperature": 0.7, - "prompt": "{file:./prompts/creative.txt}" - } - } -} -``` - -If no temperature is specified, opencode uses model-specific defaults; typically 0 for most models, 0.55 for Qwen models. - ---- - -### Disable - -Set to `true` to disable the agent. - -```json title="opencode.json" -{ - "agent": { - "review": { - "disable": true - } - } -} -``` - ---- - -### Prompt - -Specify a custom system prompt file for this agent with the `prompt` config. The prompt file should contain instructions specific to the agent's purpose. - -```json title="opencode.json" -{ - "agent": { - "review": { - "prompt": "{file:./prompts/code-review.txt}" - } - } -} -``` - -This path is relative to where the config file is located. So this works for both the global opencode config and the project specific config. - ---- - -### Model - -Use the `model` config to override the default model for this agent. Useful for using different models optimized for different tasks. For example, a faster model for planning, a more capable model for implementation. - -```json title="opencode.json" -{ - "agent": { - "plan": { - "model": "anthropic/claude-haiku-4-20250514" - } - } -} -``` - ---- - -### Tools - -Control which tools are available in this agent with the `tools` config. You can enable or disable specific tools by setting them to `true` or `false`. - -```json title="opencode.json" -{ - "agent": { - "readonly": { - "tools": { - "write": false, - "edit": false, - "bash": false, - "read": true, - "grep": true, - "glob": true - } - } - } -} -``` - -You can also use wildcards to control multiple tools at once. For example, to disable all tools from an MCP server: - -```json title="opencode.json" -{ - "agent": { - "readonly": { - "tools": { - "mymcp_*": false, - "write": false, - "edit": false - } - } - } -} -``` - -If no tools are specified, all tools are enabled by default. - ---- - -#### Available tools - -Here are all the tools can be controlled through the agent config. - -| Tool | Description | -| ----------- | ----------------------- | -| `bash` | Execute shell commands | -| `edit` | Modify existing files | -| `write` | Create new files | -| `read` | Read file contents | -| `grep` | Search file contents | -| `glob` | Find files by pattern | -| `list` | List directory contents | -| `patch` | Apply patches to files | -| `todowrite` | Manage todo lists | -| `todoread` | Read todo lists | -| `webfetch` | Fetch web content | - ---- - -### Permissions - -Permissions control what actions an agent can take. - -- edit, bash, webfetch - -Each permission can be set to allow, ask, or deny. - -- allow, ask, deny - -Configure permissions globally in opencode.json. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "permission": { - "edit": "ask", - "bash": "allow", - "webfetch": "deny" - } -} -``` - -You can override permissions per agent in JSON. - -```json title="opencode.json" {7-18} -{ - "$schema": "https://opencode.ai/config.json", - "agent": { - "build": { - "permission": { - "edit": "allow", - "bash": { - "*": "allow", - "git push": "ask", - "terraform *": "deny" - }, - "webfetch": "ask" - } - } - } -} -``` - -You can also set permissions in Markdown agents. - -```markdown title="~/.config/opencode/agent/review.md" ---- -description: Code review without edits -mode: subagent -permission: - edit: deny - bash: ask - webfetch: deny ---- - -Only analyze code and suggest changes. -``` - -Bash permissions support granular patterns for fine-grained control. - -```json title="Allow most, ask for risky, deny terraform" -{ - "$schema": "https://opencode.ai/config.json", - "permission": { - "bash": { - "*": "allow", - "git push": "ask", - "terraform *": "deny" - } - } -} -``` - -If you provide a granular bash map, the default becomes ask unless you set \* explicitly. - -```json title="Granular defaults to ask" -{ - "$schema": "https://opencode.ai/config.json", - "permission": { - "bash": { - "git status": "allow" - } - } -} -``` - -Agent-level permissions merge over global settings. - -- Global sets defaults; agent overrides when specified - -Specific bash rules can override a global default. - -```json title="Global ask, agent allows safe commands" -{ - "$schema": "https://opencode.ai/config.json", - "permission": { "bash": "ask" }, - "agent": { - "build": { - "permission": { - "bash": { "git status": "allow", "*": "ask" } - } - } - } -} -``` - -Permissions affect tool availability and prompts differently. - -- deny hides tools (edit also hides write/patch); ask prompts; allow runs - -For quick reference, here are common setups. - -```json title="Read-only reviewer" -{ - "$schema": "https://opencode.ai/config.json", - "agent": { - "review": { - "permission": { "edit": "deny", "bash": "deny", "webfetch": "allow" } - } - } -} -``` - -```json title="Planning agent that can browse but cannot change code" -{ - "$schema": "https://opencode.ai/config.json", - "agent": { - "plan": { - "permission": { "edit": "deny", "bash": "deny", "webfetch": "ask" } - } - } -} -``` - -See the full permissions guide for more patterns. - -- /docs/permissions - ---- - -### Mode - -Control the agent's mode with the `mode` config. The `mode` option is used to determine how the agent can be used. - -```json title="opencode.json" -{ - "agent": { - "review": { - "mode": "subagent" - } - } -} -``` - -The `mode` option can be set to `primary`, `subagent`, or `all`. If no `mode` is specified, it defaults to `all`. - ---- - -### Additional - -Any other options you specify in your agent configuration will be **passed through directly** to the provider as model options. This allows you to use provider-specific features and parameters. - -For example, with OpenAI's reasoning models, you can control the reasoning effort: - -```json title="opencode.json" {6,7} -{ - "agent": { - "deep-thinker": { - "description": "Agent that uses high reasoning effort for complex problems", - "model": "openai/gpt-5", - "reasoningEffort": "high", - "textVerbosity": "low" - } - } -} -``` - -These additional options are model and provider-specific. Check your provider's documentation for available parameters. - ---- - -## Create agents - -You can create new agents using the following command: - -```bash -opencode agent create -``` - -This interactive command will: - -1. Ask where to save the agent; global or project-specific. -2. Description of what the agent should do. -3. Generate an appropriate system prompt and identifier. -4. Let you select which tools the agent can access. -5. Finally, create a markdown file with the agent configuration. - ---- - -## Use cases - -Here are some common use cases for different agents. - -- **Build agent**: Full development work with all tools enabled -- **Plan agent**: Analysis and planning without making changes -- **Review agent**: Code review with read-only access plus documentation tools -- **Debug agent**: Focused on investigation with bash and read tools enabled -- **Docs agent**: Documentation writing with file operations but no system commands - ---- - -## Examples - -Here are some examples agents you might find useful. - -:::tip -Do you have an agent you'd like to share? [Submit a PR](https://github.com/sst/opencode). -::: - ---- - -### Documentation agent - -```markdown title="~/.config/opencode/agent/docs-writer.md" ---- -description: Writes and maintains project documentation -mode: subagent -tools: - bash: false ---- - -You are a technical writer. Create clear, comprehensive documentation. - -Focus on: - -- Clear explanations -- Proper structure -- Code examples -- User-friendly language -``` - ---- - -### Security auditor - -```markdown title="~/.config/opencode/agent/security-auditor.md" ---- -description: Performs security audits and identifies vulnerabilities -mode: subagent -tools: - write: false - edit: false ---- - -You are a security expert. Focus on identifying potential security issues. - -Look for: - -- Input validation vulnerabilities -- Authentication and authorization flaws -- Data exposure risks -- Dependency vulnerabilities -- Configuration security issues -``` diff --git a/packages/web/src/content/docs/docs/cli.mdx b/packages/web/src/content/docs/docs/cli.mdx deleted file mode 100644 index 903c3638d..000000000 --- a/packages/web/src/content/docs/docs/cli.mdx +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: CLI -description: opencode CLI options and commands. ---- - -import { Tabs, TabItem } from "@astrojs/starlight/components" - -The opencode CLI by default starts the [TUI](/docs/tui) when run without any arguments. - -```bash -opencode -``` - -But it also accepts commands as documented on this page. This allows you to interact with opencode programmatically. - -```bash -opencode run "Explain how closures work in JavaScript" -``` - - - ---- - -## Commands - -The opencode CLI also has the following commands. - ---- - -### agent - -Manage agents for opencode. - -```bash -opencode agent [command] -``` - ---- - -#### create - -Create a new agent with custom configuration. - -```bash -opencode agent create -``` - -This command will guide you through creating a new agent with a custom system prompt and tool configuration. - ---- - -### auth - -Command to manage credentials and login for providers. - -```bash -opencode auth [command] -``` - ---- - -#### login - -opencode is powered by the provider list at [Models.dev](https://models.dev), so you can use `opencode auth login` to configure API keys for any provider you'd like to use. This is stored in `~/.local/share/opencode/auth.json`. - -```bash -opencode auth login -``` - -When opencode starts up it loads the providers from the credentials file. And if there are any keys defined in your environments or a `.env` file in your project. - ---- - -#### list - -Lists all the authenticated providers as stored in the credentials file. - -```bash -opencode auth list -``` - -Or the short version. - -```bash -opencode auth ls -``` - ---- - -#### logout - -Logs you out of a provider by clearing it from the credentials file. - -```bash -opencode auth logout -``` - ---- - -### github - -Manage the GitHub agent for repository automation. - -```bash -opencode github [command] -``` - ---- - -#### install - -Install the GitHub agent in your repository. - -```bash -opencode github install -``` - -This sets up the necessary GitHub Actions workflow and guides you through the configuration process. [Learn more](/docs/github). - ---- - -#### run - -Run the GitHub agent. This is typically used in GitHub Actions. - -```bash -opencode github run -``` - -##### Flags - -| Flag | Description | -| --------- | -------------------------------------- | -| `--event` | GitHub mock event to run the agent for | -| `--token` | GitHub personal access token | - ---- - -### models - -List all available models from configured providers. - -```bash -opencode models -``` - -This command displays all models available across your configured providers in the format `provider/model`. - ---- - -### run - -Run opencode in non-interactive mode by passing a prompt directly. - -```bash -opencode run [message..] -``` - -This is useful for scripting, automation, or when you want a quick answer without launching the full TUI. For example. - -```bash "opencode run" -opencode run Explain the use of context in Go -``` - -#### Flags - -| Flag | Short | Description | -| ------------ | ----- | ------------------------------------------ | -| `--continue` | `-c` | Continue the last session | -| `--session` | `-s` | Session ID to continue | -| `--share` | | Share the session | -| `--model` | `-m` | Model to use in the form of provider/model | -| `--agent` | | Agent to use | - ---- - -### serve - -Start a headless opencode server for API access. Check out the [server docs](/docs/server) for the full HTTP interface. - -```bash -opencode serve -``` - -This starts an HTTP server that provides API access to opencode functionality without the TUI interface. - -#### Flags - -| Flag | Short | Description | -| ------------ | ----- | --------------------- | -| `--port` | `-p` | Port to listen on | -| `--hostname` | `-h` | Hostname to listen on | - ---- - -### upgrade - -Updates opencode to the latest version or a specific version. - -```bash -opencode upgrade [target] -``` - -To upgrade to the latest version. - -```bash -opencode upgrade -``` - -To upgrade to a specific version. - -```bash -opencode upgrade v0.1.48 -``` - -#### Flags - -| Flag | Short | Description | -| ---------- | ----- | ----------------------------------------------------------------- | -| `--method` | `-m` | The installation method that was used; curl, npm, pnpm, bun, brew | - ---- - -## Flags - -The opencode CLI takes the following global flags. - -| Flag | Short | Description | -| -------------- | ----- | ------------------------------------------ | -| `--help` | `-h` | Display help | -| `--version` | | Print version number | -| `--print-logs` | | Print logs to stderr | -| `--log-level` | | Log level (DEBUG, INFO, WARN, ERROR) | -| `--prompt` | `-p` | Prompt to use | -| `--model` | `-m` | Model to use in the form of provider/model | -| `--agent` | | Agent to use | -| `--port` | | Port to listen on | -| `--hostname` | | Hostname to listen on | diff --git a/packages/web/src/content/docs/docs/commands.mdx b/packages/web/src/content/docs/docs/commands.mdx deleted file mode 100644 index 59c9536ac..000000000 --- a/packages/web/src/content/docs/docs/commands.mdx +++ /dev/null @@ -1,271 +0,0 @@ ---- -title: Commands -description: Create custom commands for repetitive tasks. ---- - -Custom commands let you specify a prompt you want to run when that command is executed in the TUI. - -```bash frame="none" -/my-command -``` - -Custom commands are in addition to the built-in commands like `/init`, `/undo`, `/redo`, `/share`, `/help`. [Learn more](/docs/tui#commands). - ---- - -## Create command files - -Create markdown files in the `command/` directory to define custom commands. - -Create `.opencode/command/test.md`: - -```md title=".opencode/command/test.md" ---- -description: Run tests with coverage -agent: build -model: anthropic/claude-3-5-sonnet-20241022 ---- - -Run the full test suite with coverage report and show any failures. -Focus on the failing tests and suggest fixes. -``` - -The frontmatter defines command properties. The content becomes the template. - -Use the command by typing `/` followed by the command name. - -```bash frame="none" -"/test" -``` - ---- - -## Configure - -You can add custom commands through the opencode config or by creating markdown files in the `command/` directory. - ---- - -### JSON - -Use the `command` option in your opencode [config](/docs/config): - -```json title="opencode.jsonc" {4-12} -{ - "$schema": "https://opencode.ai/config.json", - "command": { - // This becomes the name of the command - "test": { - // This is the prompt that will be sent to the LLM - "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", - // This is show as the description in the TUI - "description": "Run tests with coverage", - "agent": "build", - "model": "anthropic/claude-3-5-sonnet-20241022" - }, - } -} -``` - -Now you can run this command in the TUI: - -```bash frame="none" -/test -``` - ---- - -### Markdown - -You can also define commands using markdown files. Place them in: - -- Global: `~/.config/opencode/command/` -- Per-project: `.opencode/command/` - -```markdown title="~/.config/opencode/command/test.md" ---- -description: Run tests with coverage -agent: build -model: anthropic/claude-3-5-sonnet-20241022 ---- - -Run the full test suite with coverage report and show any failures. -Focus on the failing tests and suggest fixes. -``` - -The markdown file name becomes the command name. For example, `test.md` lets -you run: - -```bash frame="none" -/test -``` - ---- - -## Prompt config - -The prompts for the custom commands support several special placeholders and syntax. - ---- - -### Arguments - -Pass arguments to commands using the `$ARGUMENTS` placeholder. - -```md title=".opencode/command/component.md" ---- -description: Create a new component ---- - -Create a new React component named $ARGUMENTS with TypeScript support. -Include proper typing and basic structure. -``` - -Run the command with arguments: - -```bash frame="none" -/component Button -``` - -And `$ARGUMENTS` will be replaced with `Button`. - ---- - -### Shell output - -Use _!`command`_ to inject [bash command](/docs/tui#bash-commands) output into your prompt. - -For example, to create a custom command that analyzes test coverage: - -```md title=".opencode/command/analyze-coverage.md" ---- -description: Analyze test coverage ---- - -Here are the current test results: -!`npm test` - -Based on these results, suggest improvements to increase coverage. -``` - -Or to review recent changes: - -```md title=".opencode/command/review-changes.md" ---- -description: Review recent changes ---- - -Recent git commits: -!`git log --oneline -10` - -Review these changes and suggest any improvements. -``` - -Commands run in your project's root directory and their output becomes part of the prompt. - ---- - -### File references - -Include files in your command using `@` followed by the filename. - -```md title=".opencode/command/review-component.md" ---- -description: Review component ---- - -Review the component in @src/components/Button.tsx. -Check for performance issues and suggest improvements. -``` - -The file content gets included in the prompt automatically. - ---- - -## Options - -Let's look at the configuration options in detail. - ---- - -### Template - -The `template` option defines the prompt that will be sent to the LLM when the command is executed. - -```json title="opencode.json" -{ - "command": { - "test": { - "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes." - } - } -} -``` - -This is a **required** config option. - ---- - -### Description - -Use the `description` option to provide a brief description of what the command does. - -```json title="opencode.json" -{ - "command": { - "test": { - "description": "Run tests with coverage" - } - } -} -``` - -This is shown as the description in the TUI when you type in the command. - ---- - -### Agent - -Use the `agent` config to optionally specify which [agent](/docs/agents) should execute this command. - -```json title="opencode.json" -{ - "command": { - "review": { - "agent": "plan" - } - } -} -``` - -This is an **optional** config option. If not specified, defaults to "build". - ---- - -### Model - -Use the `model` config to override the default model for this command. - -```json title="opencode.json" -{ - "command": { - "analyze": { - "model": "anthropic/claude-3-5-sonnet-20241022" - } - } -} -``` - -This is an **optional** config option. - ---- - -## Built-in - -opencode includes several built-in commands like `/init`, `/undo`, `/redo`, `/share`, `/help`; [learn more](/docs/tui#commands). - -:::note -Custom commands can override built-in commands. -::: - -If you define a custom command with the same name, it will override the built-in command. diff --git a/packages/web/src/content/docs/docs/config.mdx b/packages/web/src/content/docs/docs/config.mdx deleted file mode 100644 index 045bc596c..000000000 --- a/packages/web/src/content/docs/docs/config.mdx +++ /dev/null @@ -1,364 +0,0 @@ ---- -title: Config -description: Using the opencode JSON config. ---- - -You can configure opencode using a JSON config file. - ---- - -## Format - -opencode supports both **JSON** and **JSONC** (JSON with Comments) formats. - -```jsonc title="opencode.jsonc" -{ - "$schema": "https://opencode.ai/config.json", - // Theme configuration - "theme": "opencode", - "model": "anthropic/claude-sonnet-4-20250514", - "autoupdate": true, -} -``` - -With JSONC, you can use comments in your configuration files: - ---- - -## Locations - -You can place your config in a couple of different locations and they have a -different order of precedence. - ---- - -### Global - -Place your global opencode config in `~/.config/opencode/opencode.json`. You'll want to use the global config for things like themes, providers, or keybinds. - ---- - -### Per project - -You can also add a `opencode.json` in your project. It takes precedence over the global config. This is useful for configuring providers or modes specific to your project. - -:::tip -Place project specific config in the root of your project. -::: - -When opencode starts up, it looks for a config file in the current directory or traverse up to the nearest Git directory. - -This is also safe to be checked into Git and uses the same schema as the global one. - ---- - -### Custom path - -You can also specify a custom config file path using the `OPENCODE_CONFIG` environment variable. This takes precedence over the global and project configs. - -```bash -export OPENCODE_CONFIG=/path/to/my/custom-config.json -opencode run "Hello world" -``` - ---- - -## Schema - -The config file has a schema that's defined in [**`opencode.ai/config.json`**](https://opencode.ai/config.json). - -Your editor should be able to validate and autocomplete based on the schema. - ---- - -### Models - -You can configure the providers and models you want to use in your opencode config through the `provider`, `model` and `small_model` options. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "provider": {}, - "model": "anthropic/claude-sonnet-4-20250514", - "small_model": "anthropic/claude-3-5-haiku-20241022" -} -``` - -The `small_model` option configures a separate model for lightweight tasks like title generation. By default, opencode tries to use a cheaper model if one is available from your provider, otherwise it falls back to your main model. - -You can also configure [local models](/docs/models#local). [Learn more](/docs/models). - ---- - -### Themes - -You can configure the theme you want to use in your opencode config through the `theme` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "theme": "" -} -``` - -[Learn more here](/docs/themes). - ---- - -### Agents - -You can configure specialized agents for specific tasks through the `agent` option. - -```jsonc title="opencode.jsonc" -{ - "$schema": "https://opencode.ai/config.json", - "agent": { - "code-reviewer": { - "description": "Reviews code for best practices and potential issues", - "model": "anthropic/claude-sonnet-4-20250514", - "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", - "tools": { - // Disable file modification tools for review-only agent - "write": false, - "edit": false, - }, - }, - }, -} -``` - -You can also define agents using markdown files in `~/.config/opencode/agent/` or `.opencode/agent/`. [Learn more here](/docs/agents). - ---- - -### Sharing - -You can configure the [share](/docs/share) feature through the `share` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "share": "manual" -} -``` - -This takes: - -- `"manual"` - Allow manual sharing via commands (default) -- `"auto"` - Automatically share new conversations -- `"disabled"` - Disable sharing entirely - -By default, sharing is set to manual mode where you need to explicitly share conversations using the `/share` command. - ---- - -### Commands - -You can configure custom commands for repetitive tasks through the `command` option. - -```jsonc title="opencode.jsonc" -{ - "$schema": "https://opencode.ai/config.json", - "command": { - "test": { - "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.", - "description": "Run tests with coverage", - "agent": "build", - "model": "anthropic/claude-3-5-sonnet-20241022" - }, - "component": { - "template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.", - "description": "Create a new component" - } - } -} -``` - -You can also define commands using markdown files in `~/.config/opencode/command/` or `.opencode/command/`. [Learn more here](/docs/commands). - ---- - -### Keybinds - -You can customize your keybinds through the `keybinds` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "keybinds": {} -} -``` - -[Learn more here](/docs/keybinds). - ---- - -### Autoupdate - -opencode will automatically download any new updates when it starts up. You can disable this with the `autoupdate` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "autoupdate": false -} -``` - ---- - -### Formatters - -You can configure code formatters through the `formatter` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "formatter": { - "prettier": { - "disabled": true - }, - "custom-prettier": { - "command": ["npx", "prettier", "--write", "$FILE"], - "environment": { - "NODE_ENV": "development" - }, - "extensions": [".js", ".ts", ".jsx", ".tsx"] - } - } -} -``` - -[Learn more about formatters here](/docs/formatters). - ---- - -### Permissions - -You can configure permissions to control what AI agents can do in your codebase through the `permission` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "permission": { - "edit": "ask", - "bash": "ask" - } -} -``` - -This allows you to configure explicit approval requirements for sensitive operations: - -- `edit` - Controls whether file editing operations require user approval (`"ask"` or `"allow"`) -- `bash` - Controls whether bash commands require user approval (can be `"ask"`/`"allow"` or a pattern map) - -[Learn more about permissions here](/docs/permissions). - ---- - -### MCP servers - -You can configure MCP servers you want to use through the `mcp` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "mcp": {} -} -``` - -[Learn more here](/docs/mcp-servers). - ---- - -### Instructions - -You can configure the instructions for the model you're using through the `instructions` option. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] -} -``` - -This takes an array of paths and glob patterns to instruction files. [Learn more -about rules here](/docs/rules). - ---- - -### Disabled providers - -You can disable providers that are loaded automatically through the `disabled_providers` option. This is useful when you want to prevent certain providers from being loaded even if their credentials are available. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "disabled_providers": ["openai", "gemini"] -} -``` - -The `disabled_providers` option accepts an array of provider IDs. When a provider is disabled: - -- It won't be loaded even if environment variables are set. -- It won't be loaded even if API keys are configured through `opencode auth login`. -- The provider's models won't appear in the model selection list. - ---- - -## Variables - -You can use variable substitution in your config files to reference environment variables and file contents. - ---- - -### Env vars - -Use `{env:VARIABLE_NAME}` to substitute environment variables: - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "model": "{env:OPENCODE_MODEL}", - "provider": { - "anthropic": { - "models": {}, - "options": { - "apiKey": "{env:ANTHROPIC_API_KEY}" - } - } - } -} -``` - -If the environment variable is not set, it will be replaced with an empty string. - ---- - -### Files - -Use `{file:path/to/file}` to substitute the contents of a file: - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "instructions": ["./custom-instructions.md"], - "provider": { - "openai": { - "options": { - "apiKey": "{file:~/.secrets/openai-key}" - } - } - } -} -``` - -File paths can be: - -- Relative to the config file directory -- Or absolute paths starting with `/` or `~` - -These are useful for: - -- Keeping sensitive data like API keys in separate files. -- Including large instruction files without cluttering your config. -- Sharing common configuration snippets across multiple config files. diff --git a/packages/web/src/content/docs/docs/enterprise.mdx b/packages/web/src/content/docs/docs/enterprise.mdx deleted file mode 100644 index 3e4b281e0..000000000 --- a/packages/web/src/content/docs/docs/enterprise.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Enterprise -description: Using opencode in your organization. ---- - -import config from "../../../../config.mjs" -export const email = `mailto:${config.email}` - -opencode does not store any of your code or context data. This makes it easy for -you to use opencode at your organization. - -To get started, we recommend: - -1. Do a trial internally with your team. -2. **Contact us** to discuss pricing and implementation options. - ---- - -## Trial - -Since opencode is open source and does not store any of your code or context data, your developers can simply [get started](/docs/) and carry out a trial. - ---- - -### Data handling - -**opencode does not store your code or context data.** All processing happens locally or through direct API calls to your AI provider. - -The only caveat here is the optional `/share` feature. - ---- - -#### Sharing conversations - -If a user enables the `/share` feature, the conversation and the data associated with it are sent to the service we use to host these shares pages at opencode.ai. - -The data is currently served through our CDN's edge network, and is cached on the edge near your users. - -We recommend you disable this for your trial. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "share": "disabled" -} -``` - -[Learn more about sharing](/docs/share). - ---- - -### Code ownership - -**You own all code produced by opencode.** There are no licensing restrictions or ownership claims. - ---- - -## Deployment - -Once you have completed your trial and you are ready to self-host opencode at -your organization, you can **contact us** to discuss -pricing and implementation options. - ---- - -### SSO - -SSO integration can be implemented for enterprise deployments after your trial. -This will allow your team's session data and shared conversations to be protected -by your enterprise's authentication system. - ---- - -### Private NPM - -opencode supports private npm registries through Bun's native `.npmrc` file support. If your organization uses a private registry, such as JFrog Artifactory, Nexus, or similar, ensure developers are authenticated before running opencode. - -To set up authentication with your private registry: - -```bash -npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ -``` - -This creates `~/.npmrc` with authentication details. opencode will automatically -pick this up. - -:::caution -You must be logged into the private registry before running opencode. -::: - -Alternatively, you can manually configure a `.npmrc` file: - -```bash title="~/.npmrc" -registry=https://your-company.jfrog.io/api/npm/npm-virtual/ -//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} -``` - -Developers must be logged into the private registry before running opencode to ensure packages can be installed from your enterprise registry. - ---- - -### Self-hosting - -The share feature can be self-hosted and the share pages can be made accessible -only after the user has been authenticated. diff --git a/packages/web/src/content/docs/docs/formatters.mdx b/packages/web/src/content/docs/docs/formatters.mdx deleted file mode 100644 index 9c9411aeb..000000000 --- a/packages/web/src/content/docs/docs/formatters.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Formatters -description: opencode uses language specific formatters. ---- - -opencode automatically formats files after they are written or edited using language-specific formatters. This ensures that the code that is generated follows the code styles of your project. - ---- - -## Built-in - -opencode comes with several built-in formatters for popular languages and frameworks. Below is a list of the formatters, supported file extensions, and commands or config options it needs. - -| Formatter | Extensions | Requirements | -| -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------- | -| gofmt | .go | `gofmt` command available | -| mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` command available | -| prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://prettier.io/docs/en/index.html) | `prettier` dependency in `package.json` | -| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://biomejs.dev/) | `biome.json(c)` config file | -| zig | .zig, .zon | `zig` command available | -| clang-format | .c, .cpp, .h, .hpp, .ino, and [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` config file | -| ktlint | .kt, .kts | `ktlint` command available | -| ruff | .py, .pyi | `ruff` command available with config | -| rubocop | .rb, .rake, .gemspec, .ru | `rubocop` command available | -| standardrb | .rb, .rake, .gemspec, .ru | `standardrb` command available | -| htmlbeautifier | .erb, .html.erb | `htmlbeautifier` command available | - -So if your project has `prettier` in your `package.json`, opencode will automatically use it. - ---- - -## How it works - -When opencode writes or edits a file, it: - -1. Checks the file extension against all enabled formatters. -2. Runs the appropriate formatter command on the file. -3. Applies the formatting changes automatically. - -This process happens in the background, ensuring your code styles are maintained without any manual steps. - ---- - -## Configure - -You can customize formatters through the `formatter` section in your opencode config. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "formatter": { } -} -``` - -Each formatter configuration supports the following: - -| Property | Type | Description | -| ------------- | -------- | ------------------------------------------------------- | -| `disabled` | boolean | Set this to `true` to disable the formatter | -| `command` | string[] | The command to run for formatting | -| `environment` | object | Environment variables to set when running the formatter | -| `extensions` | string[] | File extensions this formatter should handle | - -Let's look at some examples. - ---- - -### Disabling formatters - -To disable a specific formatter, set `disabled` to `true`: - -```json title="opencode.json" {5} -{ - "$schema": "https://opencode.ai/config.json", - "formatter": { - "prettier": { - "disabled": true - } - } -} -``` - ---- - -### Custom formatters - -You can override the built-in formatters or add new ones by specifying the command, environment variables, and file extensions: - -```json title="opencode.json" {4-14} -{ - "$schema": "https://opencode.ai/config.json", - "formatter": { - "prettier": { - "command": ["npx", "prettier", "--write", "$FILE"], - "environment": { - "NODE_ENV": "development" - }, - "extensions": [".js", ".ts", ".jsx", ".tsx"] - }, - "custom-markdown-formatter": { - "command": ["deno", "fmt", "$FILE"], - "extensions": [".md"] - } - } -} -``` - -The **`$FILE` placeholder** in the command will be replaced with the path to the file being formatted. diff --git a/packages/web/src/content/docs/docs/github.mdx b/packages/web/src/content/docs/docs/github.mdx deleted file mode 100644 index d592fc84f..000000000 --- a/packages/web/src/content/docs/docs/github.mdx +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: GitHub -description: Use opencode in GitHub issues and pull-requests. ---- - -opencode integrates with your GitHub workflow. Mention `/opencode` or `/oc` in your comment, and opencode will execute tasks within your GitHub Actions runner. - ---- - -## Features - -- **Triage issues**: Ask opencode to look into an issue and explain it to you. -- **Fix and implement**: Ask opencode to fix an issue or implement a feature. And it will work in a new branch and submits a PR with all the changes. -- **Secure**: opencode runs inside your GitHub's runners. - ---- - -## Installation - -Run the following command in a project that is in a GitHub repo: - -```bash -opencode github install -``` - -This will walk you through installing the GitHub app, creating the workflow, and setting up secrets. - ---- - -### Manual Setup - -Or you can set it up manually. - -1. **Install the GitHub app** - - Head over to [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Make sure it's installed on the target repository. - -2. **Add the workflow** - - Add the following workflow file to `.github/workflows/opencode.yml` in your repo. Make sure to set the appropriate `model` and required API keys in `env`. - - ```yml title=".github/workflows/opencode.yml" {24,26} - name: opencode - - on: - issue_comment: - types: [created] - - 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@v4 - with: - fetch-depth: 1 - - - name: Run opencode - uses: sst/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** - - In your organization or project **settings**, expand **Secrets and variables** on the left and select **Actions**. And add the required API keys. - ---- - -## Configuration - -- `model`: The model to use with opencode. Takes the format of `provider/model`. This is **required**. -- `share`: Whether to share the opencode session. Defaults to **true** for public repositories. -- `token`: Optional GitHub access token for performing operations such as creating comments, commiting changes, and opening pull requests. By default, opencode uses the installation access token from the opencode GitHub App, so commits, comments, and pull requests appear as coming from the app. - - Alternatively, you can use the GitHub Action runner's [built-in `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) without installing the opencode GitHub App. Just make sure to grant the required permissions in your workflow: - - ```yaml - permissions: - id-token: write - contents: write - pull-requests: write - issues: write - ``` - - You can also use a [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) if preferred. - ---- - -## Examples - -Here are some examples of how you can use opencode in GitHub. - -- **Explain an issue** - - Add this comment in a GitHub issue. - - ``` - /opencode explain this issue - ``` - - opencode will read the entire thread, including all comments, and reply with a clear explanation. - -- **Fix an issue** - - In a GitHub issue, say: - - ``` - /opencode fix this - ``` - - And opencode will create a new branch, implement the changes, and open a PR with the changes. - -- **Review PRs and make changes** - - Leave the following comment on a GitHub PR. - - ``` - Delete the attachment from S3 when the note is removed /oc - ``` - - opencode will implement the requested change and commit it to the same PR. diff --git a/packages/web/src/content/docs/docs/gitlab.mdx b/packages/web/src/content/docs/docs/gitlab.mdx deleted file mode 100644 index 023ac678e..000000000 --- a/packages/web/src/content/docs/docs/gitlab.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: GitLab -description: Use opencode in GitLab issues and merge requests. ---- - -opencode integrates with your GitLab workflow. -Mention `@opencode` in a comment, and opencode will execute tasks within your GitLab CI pipeline. - ---- - -## Features - -- **Triage issues**: Ask opencode to look into an issue and explain it to you. -- **Fix and implement**: Ask opencode to fix an issue or implement a feature. - It will work create a new branch and raised a merge request with the changes. -- **Secure**: opencode runs on your GitLab runners. - ---- - -## Setup - -opencode runs in your GitLab CI/CD pipeline, here's what you'll need to set it up: - -:::tip -Check out the [**GitLab docs**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for up to date instructions. -::: - -1. Configure your GitLab environment -2. Set up CI/CD -3. Get an AI model provider API key -4. Create a service account -5. Configure CI/CD variables -6. Create a flow config file, here's an example: - -
- Flow configuration - - ```yaml - image: node:22-slim - commands: - - echo "Installing opencode" - - npm install --global opencode-ai - - echo "Installing glab" - - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE - - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* - - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash - - apt-get install --yes glab - - echo "Configuring glab" - - echo $GITLAB_HOST - - echo "Creating opencode auth configuration" - - mkdir --parents ~/.local/share/opencode - - | - cat > ~/.local/share/opencode/auth.json << EOF - { - "anthropic": { - "type": "api", - "key": "$ANTHROPIC_API_KEY" - } - } - EOF - - echo "Configuring git" - - git config --global user.email "opencode@gitlab.com" - - git config --global user.name "Opencode" - - echo "Testing glab" - - glab issue list - - echo "Running Opencode" - - | - opencode run " - You are an AI assistant helping with GitLab operations. - - Context: $AI_FLOW_CONTEXT - Task: $AI_FLOW_INPUT - Event: $AI_FLOW_EVENT - - Please execute the requested task using the available GitLab tools. - Be thorough in your analysis and provide clear explanations. - - - Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. - - If you are asked to summarise an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. - You don't need to commit or push up changes, those will be done automatically based on the file changes you make. - - " - - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF - - echo "Checking for git changes and pushing if any exist" - - | - if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then - echo "Git changes detected, adding and pushing..." - git add . - if git diff --cached --quiet; then - echo "No staged changes to commit" - else - echo "Committing changes to branch: $CI_WORKLOAD_REF" - git commit --message "Codex changes" - echo "Pushing changes up to $CI_WORKLOAD_REF" - git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF - echo "Changes successfully pushed" - fi - else - echo "No git changes detected, skipping push" - fi - variables: - - ANTHROPIC_API_KEY - - GITLAB_TOKEN_OPENCODE - - GITLAB_HOST - ``` - -
- -You can refer to the [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for detailed instructions. - ---- - -## Examples - -Here are some examples of how you can use opencode in GitLab. - -:::tip -You can configure to use a different trigger phrase than `@opencode`. -::: - -- **Explain an issue** - - Add this comment in a GitLab issue. - - ``` - @opencode explain this issue - ``` - - opencode will read the issue and reply with a clear explanation. - -- **Fix an issue** - - In a GitLab issue, say: - - ``` - @opencode fix this - ``` - - opencode will create a new branch, implement the changes, and open a merge request with the changes. - -- **Review merge requests** - - Leave the following comment on a GitLab merge request. - - ``` - @opencode review this merge request - ``` - - opencode will review the merge request and provide feedback. diff --git a/packages/web/src/content/docs/docs/ide.mdx b/packages/web/src/content/docs/docs/ide.mdx deleted file mode 100644 index b2f7d1e10..000000000 --- a/packages/web/src/content/docs/docs/ide.mdx +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: IDE -description: The opencode extension for VS Code, Cursor, and other IDEs ---- - -opencode integrates with VS Code, Cursor, or any IDE that supports a terminal. Just run `opencode` in the terminal to get started. - ---- - -## Usage - -- **Quick Launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open opencode in a split terminal view, or focus an existing terminal session if one is already running. -- **New Session**: Use `Cmd+Shift+Esc` (Mac) or `Ctrl+Shift+Esc` (Windows/Linux) to start a new opencode terminal session, even if one is already open. You can also click the opencode button in the UI. -- **Context Awareness**: Automatically share your current selection or tab with opencode. -- **File Reference Shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references. For example, `@File#L37-42`. - ---- - -## Installation - -To install opencode on VS Code and popular forks like Cursor, Windsurf, VSCodium: - -1. Open VS Code -2. Open the integrated terminal -3. Run `opencode` - the extension installs automatically - ---- - -### Manual Install - -Search for **opencode** in the Extension Marketplace and click **Install**. - ---- - -### Troubleshooting - -If the extension fails to install automatically: - -- Ensure you’re running `opencode` in the integrated terminal. -- Confirm the CLI for your IDE is installed: - - For VS Code: `code` command - - For Cursor: `cursor` command - - For Windsurf: `windsurf` command - - For VSCodium: `codium` command - - If not, run `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux) and search for "Shell Command: Install 'code' command in PATH" (or the equivalent for your IDE) -- Ensure VS Code has permission to install extensions diff --git a/packages/web/src/content/docs/docs/index.mdx b/packages/web/src/content/docs/docs/index.mdx deleted file mode 100644 index 97910e0e5..000000000 --- a/packages/web/src/content/docs/docs/index.mdx +++ /dev/null @@ -1,311 +0,0 @@ ---- -title: Intro -description: Get started with opencode. ---- - -import { Tabs, TabItem } from "@astrojs/starlight/components" - -[**opencode**](/) is an AI coding agent built for the terminal. - -![opencode TUI with the opencode theme](../../../assets/lander/screenshot.png) - -Let's get started. - ---- - -#### Prerequisites - -To use opencode, 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 - -The easiest way to install opencode is through the install script. - -```bash -curl -fsSL https://opencode.ai/install | bash -``` - -You can also install it with the following: - -- **Using Node.js** - - - - ```bash - npm install -g opencode-ai - ``` - - - ```bash - bun install -g opencode-ai - ``` - - - ```bash - pnpm install -g opencode-ai - ``` - - - ```bash - yarn global add opencode-ai - ``` - - - -- **Using Homebrew on macOS and Linux** - - ```bash - brew install sst/tap/opencode - ``` - -- **Using Paru on Arch Linux** - - ```bash - paru -S opencode-bin - ``` - -#### Windows - -Right now the automatic installation methods do not work properly on Windows. However you can grab the binary from the [Releases](https://github.com/sst/opencode/releases). - ---- - -## Configure - -With opencode you can use any LLM provider by configuring their API keys. - -We recommend signing up for [Claude Pro](https://www.anthropic.com/news/claude-pro) or [Max](https://www.anthropic.com/max), it's the most cost-effective way to use opencode. - -Once you've signed up, run `opencode auth login` and select Anthropic. - -```bash -$ opencode auth login - -┌ Add credential -│ -◆ Select provider -│ ● Anthropic (recommended) -│ ○ OpenAI -│ ○ Google -│ ○ Amazon Bedrock -│ ○ Azure -│ ○ DeepSeek -│ ○ Groq -│ ... -└ -``` - -Alternatively, you can select one of the other providers. [Learn more](/docs/providers#directory). - ---- - -## Initialize - -Now that you've configured a provider, you can navigate to a project that -you want to work on. - -```bash -cd /path/to/project -``` - -And run opencode. - -```bash -opencode -``` - -Next, initialize opencode for the project by running the following command. - -```bash frame="none" -/init -``` - -This will get opencode to analyze your project and create an `AGENTS.md` file in -the project root. - -:::tip -You should commit your project's `AGENTS.md` file to Git. -::: - -This helps opencode understand the project structure and the coding patterns -used. - ---- - -## Usage - -You are now ready to use opencode to work on your project. Feel free to ask it -anything! - -If you are new to using an AI coding agent, here are some examples that might -help. - ---- - -### Ask questions - -You can ask opencode to explain the codebase to you. - -:::tip -Use the `@` key to fuzzy search for files in the project. -::: - -```txt frame="none" "@packages/functions/src/api/index.ts" -How is authentication handled in @packages/functions/src/api/index.ts -``` - -This is helpful if there's a part of the codebase that you didn't work on. - ---- - -### Add features - -You can ask opencode to add new features to your project. Though we first recommend asking it to create a plan. - -1. **Create a plan** - - opencode has a _Plan mode_ that disables its ability to make changes and - instead suggest _how_ it'll implement the feature. - - Switch to it using the **Tab** key. You'll see an indicator for this in the lower right corner. - - ```bash frame="none" title="Switch to Plan mode" - - ``` - - Now let's describe what we want it to do. - - ```txt frame="none" - When a user deletes a note, we'd like to flag it as deleted in the database. - Then create a screen that shows all the recently deleted notes. - From this screen, the user can undelete a note or permanently delete it. - ``` - - You want to give opencode enough details to understand what you want. It helps - to talk to it like you are talking to a junior developer on your team. - - :::tip - Give opencode plenty of context and examples to help it understand what you - want. - ::: - -2. **Iterate on the plan** - - Once it gives you a plan, you can give it feedback or add more details. - - ```txt frame="none" - We'd like to design this new screen using a design I've used before. - [Image #1] Take a look at this image and use it as a reference. - ``` - - :::tip - Drag and drop images into the terminal to add them to the prompt. - ::: - - opencode can scan any images you give it and add them to the prompt. You can - do this by dragging and dropping an image into the terminal. - -3. **Build the feature** - - Once you feel comfortable with the plan, switch back to _Build mode_ by - hitting the **Tab** key again. - - ```bash frame="none" - - ``` - - And asking it to make the changes. - - ```bash frame="none" - Sounds good! Go ahead and make the changes. - ``` - ---- - -### Make changes - -For more straightforward changes, you can ask opencode to directly build it -without having to review the plan first. - -```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" -We need to add authentication to the /settings route. Take a look at how this is -handled in the /notes route in @packages/functions/src/notes.ts and implement -the same logic in @packages/functions/src/settings.ts -``` - -You want to make sure you provide a good amount of detail so opencode makes the right -changes. - ---- - -### Undo changes - -Let's say you ask opencode to make some changes. - -```txt frame="none" "@packages/functions/src/api/index.ts" -Can you refactor the function in @packages/functions/src/api/index.ts? -``` - -But you realize that it is not what you wanted. You **can undo** the changes -using the `/undo` command. - -```bash frame="none" -/undo -``` - -opencode will now revert the changes you made and show your original message -again. - -```txt frame="none" "@packages/functions/src/api/index.ts" -Can you refactor the function in @packages/functions/src/api/index.ts? -``` - -From here you can tweak the prompt and ask opencode to try again. - -:::tip -You can run `/undo` multiple times to undo multiple changes. -::: - -Or you **can redo** the changes using the `/redo` command. - -```bash frame="none" -/redo -``` - ---- - -## Share - -The conversations that you have with opencode can be [shared with your -team](/docs/share). - -```bash frame="none" -/share -``` - -This will create a link to the current conversation and copy it to your clipboard. - -:::note -Conversations are not shared by default. -::: - -Here's an [example conversation](https://opencode.ai/s/4XP1fce5) with opencode. - ---- - -## Customize - -And that's it! You are now a pro at using opencode. - -To make it your own, we recommend [picking a theme](/docs/themes), [customizing the keybinds](/docs/keybinds), [configuring code formatters](/docs/formatters), [creating custom commands](/docs/commands), or playing around with the [opencode config](/docs/config). diff --git a/packages/web/src/content/docs/docs/keybinds.mdx b/packages/web/src/content/docs/docs/keybinds.mdx deleted file mode 100644 index 6fd6148e1..000000000 --- a/packages/web/src/content/docs/docs/keybinds.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Keybinds -description: Customize your keybinds. ---- - -opencode has a list of keybinds that you can customize through the opencode config. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "keybinds": { - "leader": "ctrl+x", - "app_help": "h", - "app_exit": "ctrl+c,q", - "editor_open": "e", - "theme_list": "t", - "project_init": "i", - "tool_details": "d", - "thinking_blocks": "b", - "session_export": "x", - "session_new": "n", - "session_list": "l", - "session_share": "s", - "session_unshare": "none", - "session_interrupt": "esc", - "session_compact": "c", - "session_child_cycle": "ctrl+right", - "session_child_cycle_reverse": "ctrl+left", - "messages_page_up": "pgup", - "messages_page_down": "pgdown", - "messages_half_page_up": "ctrl+alt+u", - "messages_half_page_down": "ctrl+alt+d", - "messages_first": "ctrl+g", - "messages_last": "ctrl+alt+g", - "messages_copy": "y", - "messages_undo": "u", - "messages_redo": "r", - "model_list": "m", - "model_cycle_recent": "f2", - "model_cycle_recent_reverse": "shift+f2", - "agent_list": "a", - "agent_cycle": "tab", - "agent_cycle_reverse": "shift+tab", - "input_clear": "ctrl+c", - "input_paste": "ctrl+v", - "input_submit": "enter", - "input_newline": "shift+enter,ctrl+j" - } -} -``` - ---- - -## Leader key - -opencode uses a `leader` key for most keybinds. This avoids conflicts in your terminal. - -By default, `ctrl+x` is the leader key and most actions require you to first press the leader key and then the shortcut. For example, to start a new session you first press `ctrl+x` and then press `n`. - -You don't need to use a leader key for your keybinds but we recommend doing so. - ---- - -## Disable keybind - -You can disable a keybind by adding the key to your config with a value of "none". - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "keybinds": { - "session_compact": "none" - } -} -``` diff --git a/packages/web/src/content/docs/docs/lsp.mdx b/packages/web/src/content/docs/docs/lsp.mdx deleted file mode 100644 index 6a661521c..000000000 --- a/packages/web/src/content/docs/docs/lsp.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: LSP Servers -description: opencode integrates with your LSP servers. ---- - -opencode integrates with your Language Server Protocol (LSP) to help the LLM interacts with your codebase. It uses diagnostics to provide feedback to the LLM. And _go-to-definition_ and _find-references_ to help navigate your codebase. - ---- - -## Built-in - -opencode comes with several built-in LSP servers for popular languages: - -| LSP Server | Extensions | Requirements | -| ---------- | ---------------------------------------------------- | ----------------------------------- | -| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project | -| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` dependency in project | -| gopls | .go | `go` command available | -| ruby-lsp | .rb, .rake, .gemspec, .ru | `ruby` and `gem` commands available | -| pyright | .py, .pyi | `pyright` dependency installed | -| elixir-ls | .ex, .exs | `elixir` command available | -| zls | .zig, .zon | `zig` command available | -| csharp | .cs | `.NET SDK` installed | -| vue | .vue | Auto-installs for Vue projects | -| rust | .rs | `rust-analyzer` command available | -| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Auto-installs for C/C++ projects | - -LSP servers are automatically enabled when one of the above file extensions are detected and the requirements are met. - -:::note -You can disable automatic LSP server downloads by setting the `OPENCODE_DISABLE_LSP_DOWNLOAD` environment variable to `true`. -::: - ---- - -## How It Works - -When opencode opens a file, it: - -1. Checks the file extension against all enabled LSP servers. -2. Starts the appropriate LSP server if not already running. - ---- - -## Configure - -You can customize LSP servers through the `lsp` section in your opencode config. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "lsp": {} -} -``` - -Each LSP server supports the following: - -| Property | Type | Description | -| ---------------- | -------- | ------------------------------------------------- | -| `disabled` | boolean | Set this to `true` to disable the LSP server | -| `command` | string[] | The command to start the LSP server | -| `extensions` | string[] | File extensions this LSP server should handle | -| `env` | object | Environment variables to set when starting server | -| `initialization` | object | Initialization options to send to the LSP server | - -Let's look at some examples. - ---- - -### Disabling LSP servers - -To disable a specific LSP server, set `disabled` to `true`: - -```json title="opencode.json" {5} -{ - "$schema": "https://opencode.ai/config.json", - "lsp": { - "typescript": { - "disabled": true - } - } -} -``` - ---- - -### Custom LSP servers - -You can add custom LSP servers by specifying the command and file extensions: - -```json title="opencode.json" {4-7} -{ - "$schema": "https://opencode.ai/config.json", - "lsp": { - "custom-lsp": { - "command": ["custom-lsp-server", "--stdio"], - "extensions": [".custom"] - } - } -} -``` diff --git a/packages/web/src/content/docs/docs/mcp-servers.mdx b/packages/web/src/content/docs/docs/mcp-servers.mdx deleted file mode 100644 index 0ceeb47a3..000000000 --- a/packages/web/src/content/docs/docs/mcp-servers.mdx +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: MCP servers -description: Add local and remote MCP tools. ---- - -You can add external tools to opencode using the _Model Context Protocol_, or MCP. opencode supports both: - -- Local servers -- And remote servers - -Once added, MCP tools are automatically available to the LLM alongside built-in tools. - ---- - -## Configure - -You can define MCP servers in your opencode config under `mcp`. - ---- - -### Local - -Add local MCP servers using `"type": "local"` within the MCP object. Multiple MCP servers can be added. The key string for each server can be any arbitrary name. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "mcp": { - "my-local-mcp-server": { - "type": "local", - "command": ["bun", "x", "my-mcp-command"], - "enabled": true, - "environment": { - "MY_ENV_VAR": "my_env_var_value" - } - }, - "my-different-local-mcp-server": { - "type": "local", - "command": ["bun", "x", "my-other-mcp-command"], - "enabled": true - } - } -} -``` - -You can also disable a server by setting `enabled` to `false`. This is useful if you want to temporarily disable a server without removing it from your config. - ---- - -### Remote - -Add remote MCP servers under `mcp` with `"type": "remote"`. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "mcp": { - "my-remote-mcp": { - "type": "remote", - "url": "https://my-mcp-server.com", - "enabled": true, - "headers": { - "Authorization": "Bearer MY_API_KEY" - } - } - } -} -``` - -Local and remote servers can be used together within the same `mcp` config object. - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "mcp": { - "my-local-mcp-server": { - "type": "local", - "command": ["bun", "x", "my-mcp-command"], - "enabled": true, - "environment": { - "MY_ENV_VAR": "my_env_var_value" - } - }, - "my-remote-mcp": { - "type": "remote", - "url": "https://my-mcp-server.com", - "enabled": true, - "headers": { - "Authorization": "Bearer MY_API_KEY" - } - } - } -} -``` - ---- - -## Per agent - -If you have a large number of MCP servers you may want to only enable them per -agent and disable them globally. To do this: - -1. Configure the MCP server. -2. Disable it as a tool globally. -3. In your [agent config](/docs/agents#tools) enable the MCP server as a tool. - -```json title="opencode.json" {11, 14-17} -{ - "$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 - } - } - } -} -``` diff --git a/packages/web/src/content/docs/docs/models.mdx b/packages/web/src/content/docs/docs/models.mdx deleted file mode 100644 index efebc5cb4..000000000 --- a/packages/web/src/content/docs/docs/models.mdx +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: Models -description: Configuring an LLM provider and model. ---- - -opencode uses the [AI SDK](https://ai-sdk.dev/) and [Models.dev](https://models.dev) to support for **75+ LLM providers** and it supports running local models. - ---- - -## Providers - -Most popular providers are preloaded by default. If you've added the credentials for a provider through `opencode auth login`, they'll be available when you start opencode. - -Learn more about [providers](/docs/providers). - ---- - -## Select a model - -Once you've configured your provider you can select the model you want by typing in: - -```bash frame="none" -/models -``` - ---- - -## Recommended models - -There are a lot of models out there, with new models coming out every week. - -:::tip -Consider using one of the models we recommend. -::: - -However, there are a only a few of them that are good at both generating code and tool calling. - -Here are the ones we recommend with opencode: - -- Claude Sonnet 4 -- Claude Opus 4 -- Kimi K2 -- Qwen3 Coder -- GPT 4.1 -- Gemini 2.5 Pro - ---- - -## Set a default - -To set one of these as the default model, you can set the `model` key in your -opencode config. - -```json title="opencode.json" {3} -{ - "$schema": "https://opencode.ai/config.json", - "model": "lmstudio/google/gemma-3n-e4b" -} -``` - -Here the full ID is `provider_id/model_id`. - -If you've configured a [custom provider](/docs/providers#custom), the `provider_id` is key from the `provider` part of your config, and the `model_id` is the key from `provider.models`. - ---- - -## Configure models - -You can globally configure a model's options through the config. - -```jsonc title="opencode.jsonc" {7-12,19-24} -{ - "$schema": "https://opencode.ai/config.json", - "provider": { - "openai": { - "models": { - "gpt-5": { - "options": { - "reasoningEffort": "high", - "textVerbosity": "low", - "reasoningSummary": "auto", - "include": ["reasoning.encrypted_content"], - }, - }, - }, - }, - "anthropic": { - "models": { - "claude-sonnet-4-20250514": { - "options": { - "thinking": { - "type": "enabled", - "budgetTokens": 16000, - }, - }, - }, - }, - }, - }, -} -``` - -Here we're configuring global settings for two models: `gpt-5` when accessed via the `openai` provider, and `claude-sonnet-4-20250514` when accessed via the `anthropic` provider. - -You can also configure these options for any agents that you are using. The agent config overrides any global options here. [Learn more](/docs/agents/#additional). - ---- - -## Loading models - -When opencode starts up, it checks for models in the following priority order: - -1. The `--model` or `-m` command line flag. The format is the same as in the config file: `provider_id/model_id`. - -2. The model list in the opencode config. - - ```json title="opencode.json" - { - "$schema": "https://opencode.ai/config.json", - "model": "anthropic/claude-sonnet-4-20250514" - } - ``` - - The format here is `provider/model`. - -3. The last used model. - -4. The first model using an internal priority. diff --git a/packages/web/src/content/docs/docs/modes.mdx b/packages/web/src/content/docs/docs/modes.mdx deleted file mode 100644 index ae14c2f32..000000000 --- a/packages/web/src/content/docs/docs/modes.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Modes -description: Different modes for different use cases. ---- - -:::caution -Modes are now configured through the `agent` option in the opencode config. The -`mode` option is now deprecated. [Learn more](/docs/agents). -::: - -Modes in opencode allow you to customize the behavior, tools, and prompts for different use cases. - -It comes with two built-in modes: **build** and **plan**. You can customize -these or configure your own through the opencode config. - -You can switch between modes during a session or configure them in your config file. - ---- - -## Built-in - -opencode comes with two built-in modes. - ---- - -### Build - -Build is the **default** mode with all tools enabled. This is the standard mode for development work where you need full access to file operations and system commands. - ---- - -### Plan - -A restricted mode designed for planning and analysis. In plan mode, the following tools are disabled by default: - -- `write` - Cannot create new files -- `edit` - Cannot modify existing files -- `patch` - Cannot apply patches -- `bash` - Cannot execute shell commands - -This mode is useful when you want the AI to analyze code, suggest changes, or create plans without making any actual modifications to your codebase. - ---- - -## Switching - -You can switch between modes during a session using the _Tab_ key. Or your configured `switch_mode` keybind. - -See also: [Formatters](/docs/formatters) for information about code formatting configuration. - ---- - -## Configure - -You can customize the built-in modes or create your own through configuration. Modes can be configured in two ways: - -### JSON Configuration - -Configure modes in your `opencode.json` config file: - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "mode": { - "build": { - "model": "anthropic/claude-sonnet-4-20250514", - "prompt": "{file:./prompts/build.txt}", - "tools": { - "write": true, - "edit": true, - "bash": true - } - }, - "plan": { - "model": "anthropic/claude-haiku-4-20250514", - "tools": { - "write": false, - "edit": false, - "bash": false - } - } - } -} -``` - -### Markdown Configuration - -You can also define modes using markdown files. Place them in: - -- Global: `~/.config/opencode/mode/` -- Project: `.opencode/mode/` - -```markdown title="~/.config/opencode/mode/review.md" ---- -model: anthropic/claude-sonnet-4-20250514 -temperature: 0.1 -tools: - write: false - edit: false - bash: false ---- - -You are in code review mode. Focus on: - -- Code quality and best practices -- Potential bugs and edge cases -- Performance implications -- Security considerations - -Provide constructive feedback without making direct changes. -``` - -The markdown file name becomes the mode name (e.g., `review.md` creates a `review` mode). - -Let's look at these configuration options in detail. - ---- - -### Model - -Use the `model` config to override the default model for this mode. Useful for using different models optimized for different tasks. For example, a faster model for planning, a more capable model for implementation. - -```json title="opencode.json" -{ - "mode": { - "plan": { - "model": "anthropic/claude-haiku-4-20250514" - } - } -} -``` - ---- - -### Temperature - -Control the randomness and creativity of the AI's responses with the `temperature` config. Lower values make responses more focused and deterministic, while higher values increase creativity and variability. - -```json title="opencode.json" -{ - "mode": { - "plan": { - "temperature": 0.1 - }, - "creative": { - "temperature": 0.8 - } - } -} -``` - -Temperature values typically range from 0.0 to 1.0: - -- **0.0-0.2**: Very focused and deterministic responses, ideal for code analysis and planning -- **0.3-0.5**: Balanced responses with some creativity, good for general development tasks -- **0.6-1.0**: More creative and varied responses, useful for brainstorming and exploration - -```json title="opencode.json" -{ - "mode": { - "analyze": { - "temperature": 0.1, - "prompt": "{file:./prompts/analysis.txt}" - }, - "build": { - "temperature": 0.3 - }, - "brainstorm": { - "temperature": 0.7, - "prompt": "{file:./prompts/creative.txt}" - } - } -} -``` - -If no temperature is specified, opencode uses model-specific defaults (typically 0 for most models, 0.55 for Qwen models). - ---- - -### Prompt - -Specify a custom system prompt file for this mode with the `prompt` config. The prompt file should contain instructions specific to the mode's purpose. - -```json title="opencode.json" -{ - "mode": { - "review": { - "prompt": "{file:./prompts/code-review.txt}" - } - } -} -``` - -This path is relative to where the config file is located. So this works for -both the global opencode config and the project specific config. - ---- - -### Tools - -Control which tools are available in this mode with the `tools` config. You can enable or disable specific tools by setting them to `true` or `false`. - -```json -{ - "mode": { - "readonly": { - "tools": { - "write": false, - "edit": false, - "bash": false, - "read": true, - "grep": true, - "glob": true - } - } - } -} -``` - -If no tools are specified, all tools are enabled by default. - ---- - -#### Available tools - -Here are all the tools can be controlled through the mode config. - -| Tool | Description | -| ----------- | ----------------------- | -| `bash` | Execute shell commands | -| `edit` | Modify existing files | -| `write` | Create new files | -| `read` | Read file contents | -| `grep` | Search file contents | -| `glob` | Find files by pattern | -| `list` | List directory contents | -| `patch` | Apply patches to files | -| `todowrite` | Manage todo lists | -| `todoread` | Read todo lists | -| `webfetch` | Fetch web content | - ---- - -## Custom modes - -You can create your own custom modes by adding them to the configuration. Here are examples using both approaches: - -### Using JSON configuration - -```json title="opencode.json" {4-14} -{ - "$schema": "https://opencode.ai/config.json", - "mode": { - "docs": { - "prompt": "{file:./prompts/documentation.txt}", - "tools": { - "write": true, - "edit": true, - "bash": false, - "read": true, - "grep": true, - "glob": true - } - } - } -} -``` - -### Using markdown files - -Create mode files in `.opencode/mode/` for project-specific modes or `~/.config/opencode/mode/` for global modes: - -```markdown title=".opencode/mode/debug.md" ---- -temperature: 0.1 -tools: - bash: true - read: true - grep: true - write: false - edit: false ---- - -You are in debug mode. Your primary goal is to help investigate and diagnose issues. - -Focus on: - -- Understanding the problem through careful analysis -- Using bash commands to inspect system state -- Reading relevant files and logs -- Searching for patterns and anomalies -- Providing clear explanations of findings - -Do not make any changes to files. Only investigate and report. -``` - -```markdown title="~/.config/opencode/mode/refactor.md" ---- -model: anthropic/claude-sonnet-4-20250514 -temperature: 0.2 -tools: - edit: true - read: true - grep: true - glob: true ---- - -You are in refactoring mode. Focus on improving code quality without changing functionality. - -Priorities: - -- Improve code readability and maintainability -- Apply consistent naming conventions -- Reduce code duplication -- Optimize performance where appropriate -- Ensure all tests continue to pass -``` - ---- - -### Use cases - -Here are some common use cases for different modes. - -- **Build mode**: Full development work with all tools enabled -- **Plan mode**: Analysis and planning without making changes -- **Review mode**: Code review with read-only access plus documentation tools -- **Debug mode**: Focused on investigation with bash and read tools enabled -- **Docs mode**: Documentation writing with file operations but no system commands - -You might also find different models are good for different use cases. diff --git a/packages/web/src/content/docs/docs/permissions.mdx b/packages/web/src/content/docs/docs/permissions.mdx deleted file mode 100644 index 44dbc92ef..000000000 --- a/packages/web/src/content/docs/docs/permissions.mdx +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: Permissions -description: Control what agents can do in your codebase. ---- - -By default, opencode **allows all operations** without requiring explicit approval. - -The permissions system provides granular control to restrict what actions AI agents can perform in your codebase, allowing you to configure explicit approval requirements for sensitive operations like file editing, bash commands, and more. - ---- - -## Configure - -Permissions are configured in your `opencode.json` file under the `permission` key. Here are the available options. - -### Tool Permission Support - -| Tool | Description | -| ---------- | ------------------------------- | -| `edit` | Control file editing operations | -| `bash` | Control bash command execution | -| `webfetch` | Control web content fetching | - -They can also be configured per agent, see [Agent Configuration](/docs/agents#agent-configuration) for more details. - ---- - -### edit - -Use the `permission.edit` key to control whether file editing operations require user approval. - -- `"ask"` - Prompt for approval before editing files -- `"allow"` - Allow all file editing operations without approval -- `"deny"` - Make all file editing tools disabled and unavailable - -```json title="opencode.json" {4} -{ - "$schema": "https://opencode.ai/config.json", - "permission": { - "edit": "ask" - } -} -``` - ---- - -### bash - -Controls whether bash commands require user approval. - -:::tip -You can specify which commands you want to have run without approval. -::: - -This can be configured globally or with specific patterns. Setting this to `"ask"`, requiring approval for all bash commands. -Setting this to `"deny"` is the strictest option, blocking LLM from running that command or command pattern. - -For example. - -- **Ask for approval for all commands** - - ```json title="opencode.json" - { - "$schema": "https://opencode.ai/config.json", - "permission": { - "bash": "ask" - } - } - ``` - -- **Disable all Terraform commands** - - ```json title="opencode.json" - { - "$schema": "https://opencode.ai/config.json", - "permission": { - "bash": { - "terraform *": "deny" - } - } - } - ``` - -- **Approve specific commands** - - ```json title="opencode.json" - { - "$schema": "https://opencode.ai/config.json", - "permission": { - "bash": { - "git status": "allow", - "git diff": "allow", - "npm run build": "allow", - "ls": "allow", - "pwd": "allow" - } - } - } - ``` - -- **Use wildcard patterns to restrict specific commands** - - ```json title="opencode.json" - { - "$schema": "https://opencode.ai/config.json", - "permission": { - "bash": { - "git push": "ask", - "*": "allow" - } - } - } - ``` - - This configuration allows all commands by default (`"*": "allow"`) but requires approval for `git push` commands. diff --git a/packages/web/src/content/docs/docs/plugins.mdx b/packages/web/src/content/docs/docs/plugins.mdx deleted file mode 100644 index 071f1d427..000000000 --- a/packages/web/src/content/docs/docs/plugins.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Plugins -description: Write your own plugins to extend opencode. ---- - -Plugins allow you to extend opencode by hooking into various events and customizing behavior. You can create plugins to add new features, integrate with external services, or modify opencode's default behavior. - ---- - -## Create a plugin - -A plugin is a **JavaScript/TypeScript module** that exports one or more plugin -functions. Each function receives a context object and returns a hooks object. - ---- - -### Location - -Plugins are loaded from: - -1. `.opencode/plugin` directory either in your project -2. Or, globally in `~/.config/opencode/plugin` - ---- - -### Basic structure - -```js title=".opencode/plugin/example.js" -export const MyPlugin = async ({ project, client, $, directory, worktree }) => { - console.log("Plugin initialized!") - - return { - // Hook implementations go here - } -} -``` - -The plugin function receives: - -- `project`: The current project information. -- `directory`: The current working directory. -- `worktree`: The git worktree path. -- `client`: An opencode SDK client for interacting with the AI. -- `$`: Bun's [shell API](https://bun.com/docs/runtime/shell) for executing commands. - ---- - -### TypeScript support - -For TypeScript plugins, you can import types from the plugin package: - -```ts title="my-plugin.ts" {1} -import type { Plugin } from "@opencode-ai/plugin" - -export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { - return { - // Type-safe hook implementations - } -} -``` - ---- - -## Examples - -Here are some examples of plugins you can use to extend opencode. - ---- - -### Send notifications - -Send notifications when certain events occur: - -```js title=".opencode/plugin/notification.js" -export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { - return { - event: async ({ event }) => { - // Send notification on session completion - if (event.type === "session.idle") { - await $`osascript -e 'display notification "Session completed!" with title "opencode"'` - } - }, - } -} -``` - -We are using `osascript` to run AppleScript on macOS. Here we are using it to send notifications. - ---- - -### .env protection - -Prevent opencode from reading `.env` files: - -```javascript title=".opencode/plugin/env-protection.js" -export const EnvProtection = async ({ project, client, $, directory, worktree }) => { - return { - "tool.execute.before": async (input, output) => { - if (input.tool === "read" && output.args.filePath.includes(".env")) { - throw new Error("Do not read .env files") - } - }, - } -} -``` diff --git a/packages/web/src/content/docs/docs/providers.mdx b/packages/web/src/content/docs/docs/providers.mdx deleted file mode 100644 index 2e8a3b5a3..000000000 --- a/packages/web/src/content/docs/docs/providers.mdx +++ /dev/null @@ -1,887 +0,0 @@ ---- -title: Providers -description: Using any LLM provider in opencode. ---- - -import config from "../../../../config.mjs" -export const console = config.console - -opencode uses the [AI SDK](https://ai-sdk.dev/) and [Models.dev](https://models.dev) to support for **75+ LLM providers** and it supports running local models. - -To add a provider you need to: - -1. Add the API keys for the provider using `opencode auth login`. -2. Configure the provider in your opencode config. - ---- - -### Credentials - -When you add a provider's API keys with `opencode auth login`, they are stored -in `~/.local/share/opencode/auth.json`. - ---- - -### Config - -You can customize the providers through the `provider` section in your opencode -config. - ---- - -#### Base URL - -You can customize the base URL for any provider by setting the `baseURL` option. This is useful when using proxy services or custom endpoints. - -```json title="opencode.json" {6} -{ - "$schema": "https://opencode.ai/config.json", - "provider": { - "anthropic": { - "options": { - "baseURL": "https://api.anthropic.com/v1" - } - } - } -} -``` - ---- - -## opencode zen - -opencode zen is a list of models provided by the opencode team that have been -tested and verified to work well with opencode. [Learn more](/docs/zen). - -:::tip -If you are new, we recommend starting with opencode zen. -::: - -1. You sign in to **opencode zen** and get your API key. -2. You run `opencode auth login` and select opencode zen and add your API key. -3. Run `/models` in the TUI to see the list of models we recommend. - -It works like any other provider in opencode. And is completely optional to use -it. - ---- - -## Directory - -Let's look at some of the providers in detail. If you'd like to add a provider to the -list, feel free to open a PR. - -:::note -Don't see a provider here? Submit a PR. -::: - ---- - -### Amazon Bedrock - -To use Amazon Bedrock with opencode: - -1. Head over to the **Model catalog** in the Amazon Bedrock console and request - access to the models you want. - - :::tip - You need to have access to the model you want in Amazon Bedrock. - ::: - -1. You'll need either to set one of the following environment variables: - - - `AWS_ACCESS_KEY_ID`: You can get this by creating an IAM user and generating - an access key for it. - - `AWS_PROFILE`: First login through AWS IAM Identity Center (or AWS SSO) using - `aws sso login`. Then get the name of the profile you want to use. - - `AWS_BEARER_TOKEN_BEDROCK`: You can generate a long-term API key from the - Amazon Bedrock console. - - Once you have one of the above, set it while running opencode. - - ```bash - AWS_ACCESS_KEY_ID=XXX opencode - ``` - - Or add it to a `.env` file in the project root. - - ```bash title=".env" - AWS_ACCESS_KEY_ID=XXX - ``` - - Or add it to your bash profile. - - ```bash title="~/.bash_profile" - export AWS_ACCESS_KEY_ID=XXX - ``` - -1. Run the `/models` command to select the model you want. - ---- - -### Anthropic - -We recommend signing up for [Claude Pro](https://www.anthropic.com/news/claude-pro) or [Max](https://www.anthropic.com/max), it's the most cost-effective way to use opencode. - -Once you've singed up, run `opencode auth login` and select Anthropic. - -```bash -$ opencode auth login - -┌ Add credential -│ -◆ Select provider -│ ● Anthropic (recommended) -│ ○ OpenAI -│ ○ Google -│ ... -└ -``` - -Here you can select the **Claude Pro/Max** option and it'll open your browser -and ask you to authenticate. - -```bash -$ opencode auth login -┌ Add credential -│ -◇ Select provider -│ Anthropic -│ -◆ Login method -│ ● Claude Pro/Max -│ ○ Create API Key -│ ○ Manually enter API Key -└ -``` - -Now all the the Anthropic models should be available when you use the `/models` command. - -##### Using API keys - -You can also select **Create API Key** if you don't have a Pro/Max subscription. It'll also open your browser and ask you to login to Anthropic and give you a code you can paste in your terminal. - -Or if you already have an API key, you can select **Manually enter API Key** and paste it in your terminal. - ---- - -### Azure OpenAI - -1. Head over to the [Azure portal](https://portal.azure.com/) and create an **Azure OpenAI** resource. You'll need: - - - **Resource name**: This becomes part of your API endpoint (`https://RESOURCE_NAME.openai.azure.com/`) - - **API key**: Either `KEY 1` or `KEY 2` from your resource - -2. Go to [Azure AI Foundry](https://ai.azure.com/) and deploy a model. - - :::note - The deployment name must match the model name for opencode to work properly. - ::: - -3. Run `opencode auth login` and select **Azure**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● Azure - │ ... - └ - ``` - -4. Enter your API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ Azure - │ - ◇ Enter your API key - │ _ - └ - ``` - -5. Set your resource name as an environment variable: - - ```bash - AZURE_RESOURCE_NAME=XXX opencode - ``` - - Or add it to a `.env` file in the project root: - - ```bash title=".env" - AZURE_RESOURCE_NAME=XXX - ``` - - Or add it to your bash profile: - - ```bash title="~/.bash_profile" - export AZURE_RESOURCE_NAME=XXX - ``` - -6. Run the `/models` command to select your deployed model. - ---- - -### Cerebras - -1. Head over to the [Cerebras console](https://inference.cerebras.ai/), create an account, and generate an API key. - -2. Run `opencode auth login` and select **Cerebras**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● Cerebras - │ ... - └ - ``` - -3. Enter your Cerebras API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ Cerebras - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select a model like _Qwen 3 Coder 480B_. - ---- - -### DeepSeek - -1. Head over to the [DeepSeek console](https://platform.deepseek.com/), create an account, and click **Create new API key**. - -2. Run `opencode auth login` and select **DeepSeek**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● DeepSeek - │ ... - └ - ``` - -3. Enter your DeepSeek API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ DeepSeek - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select a DeepSeek model like _DeepSeek Reasoner_. - ---- - -### Fireworks AI - -1. Head over to the [Fireworks AI console](https://app.fireworks.ai/), create an account, and click **Create API Key**. - -2. Run `opencode auth login` and select **Fireworks AI**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● Fireworks AI - │ ... - └ - ``` - -3. Enter your Fireworks AI API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ Fireworks AI - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select a model like _Kimi K2 Instruct_. - ---- - -### GitHub Copilot - -To use your GitHub Copilot subscription with opencode: - -:::note -Some models might need a [Pro+ -subscription](https://github.com/features/copilot/plans) to use. -::: - -1. Run `opencode auth login` and select GitHub Copilot. - - ```bash - $ opencode auth login - ┌ Add credential - - │ - ◇ Select provider - │ GitHub Copilot - │ - ◇ ──────────────────────────────────────────────╮ - │ │ - │ Please visit: https://github.com/login/device │ - │ Enter code: 8F43-6FCF │ - │ │ - ├─────────────────────────────────────────────────╯ - │ - ◓ Waiting for authorization... - ``` - -2. Navigate to [github.com/login/device](https://github.com/login/device) and enter the code. - -3. Now run the `/models` command to select the model you want. - ---- - -### Groq - -1. Head over to the [Groq console](https://console.groq.com/), click **Create API Key**, and copy the key. - -2. Run `opencode auth login` and select Groq. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● Groq - │ ... - └ - ``` - -3. Enter the API key for the provider. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ Groq - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select the one you want. - ---- - -### LM Studio - -You can configure opencode to use local models through LM Studio. - -```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} -{ - "$schema": "https://opencode.ai/config.json", - "provider": { - "lmstudio": { - "npm": "@ai-sdk/openai-compatible", - "name": "LM Studio (local)", - "options": { - "baseURL": "http://127.0.0.1:1234/v1" - }, - "models": { - "google/gemma-3n-e4b": { - "name": "Gemma 3n-e4b (local)" - } - } - } - } -} -``` - -In this example: - -- `lmstudio` is the custom provider ID. This can be any string you want. -- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. -- `name` is the display name for the provider in the UI. -- `options.baseURL` is the endpoint for the local server. -- `models` is a map of model IDs to their configurations. The model name will be displayed in the model selection list. - ---- - -### Moonshot AI - -To use Kimi K2 from Moonshot AI: - -1. Head over to the [Moonshot AI console](https://platform.moonshot.ai/console), create an account, and click **Create API key**. - -2. Run `opencode auth login` and select **Moonshot AI**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ... - │ ● Moonshot AI - └ - ``` - -3. Enter your Moonshot API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ Moonshot AI - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select _Kimi K2_. - ---- - -### Ollama - -You can configure opencode to use local models through Ollama. - -```json title="opencode.json" "ollama" {5, 6, 8, 10-14} -{ - "$schema": "https://opencode.ai/config.json", - "provider": { - "ollama": { - "npm": "@ai-sdk/openai-compatible", - "name": "Ollama (local)", - "options": { - "baseURL": "http://localhost:11434/v1" - }, - "models": { - "llama2": { - "name": "Llama 2" - } - } - } - } -} -``` - -In this example: - -- `ollama` is the custom provider ID. This can be any string you want. -- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. -- `name` is the display name for the provider in the UI. -- `options.baseURL` is the endpoint for the local server. -- `models` is a map of model IDs to their configurations. The model name will be displayed in the model selection list. - ---- - -### OpenAI - -1. Head over to the [OpenAI Platform console](https://platform.openai.com/api-keys), click **Create new secret key**, and copy the key. - -2. Run `opencode auth login` and select OpenAI. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● OpenAI - │ ... - └ - ``` - -3. Enter the API key for the provider. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ OpenAI - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select the one you want. - ---- - -### opencode zen - -opencode zen is a list of tested and verified models provided by the opencode team. [Learn more](/docs/zen). - -1. Sign in to **opencode zen** and click **Create API Key**. - -2. Run `opencode auth login` and select **opencode zen**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● opencode zen - │ ... - └ - ``` - -3. Enter your opencode API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ opencode zen - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select a model like _Qwen 3 Coder 480B_. - ---- - -### OpenRouter - -1. Head over to the [OpenRouter dashboard](https://openrouter.ai/settings/keys), click **Create API Key**, and copy the key. - -2. Run `opencode auth login` and select OpenRouter. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● OpenRouter - │ ○ Anthropic - │ ○ Google - │ ... - └ - ``` - -3. Enter the API key for the provider. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ OpenRouter - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Many OpenRouter models are preloaded by default, run the `/models` command to select the one you want. - - You can also add additional models through your opencode config. - - ```json title="opencode.json" {6} - { - "$schema": "https://opencode.ai/config.json", - "provider": { - "openrouter": { - "models": { - "somecoolnewmodel": {} - } - } - } - } - ``` - -5. You can also customize them through your opencode config. Here's an example of specifying a provider - - ```json title="opencode.json" - { - "$schema": "https://opencode.ai/config.json", - "provider": { - "openrouter": { - "models": { - "moonshotai/kimi-k2": { - "options": { - "provider": { - "order": ["baseten"], - "allow_fallbacks": false - } - } - } - } - } - } - } - ``` - ---- - -### Together AI - -1. Head over to the [Together AI console](https://api.together.ai), create an account, and click **Add Key**. - -2. Run `opencode auth login` and select **Together AI**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● Together AI - │ ... - └ - ``` - -3. Enter your Together AI API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ Together AI - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select a model like _Kimi K2 Instruct_. - ---- - -### xAI - -For a limited time, you can use xAI's Grok Code for free with opencode. - -:::tip -Grok Code is available for free for a limited time on opencode. -::: - -1. Make sure you are on the latest version of opencode. - -2. Run the `/models` command and select **Grok Code Free**. - -As a part of the trial period, the xAI team will be using the request logs to -monitor and improve Grok Code. - ---- - -### Z.AI - -1. Head over to the [Z.AI API console](https://z.ai/manage-apikey/apikey-list), create an account, and click **Create a new API key**. - -2. Run `opencode auth login` and select **Z.AI**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ● Z.AI - │ ... - └ - ``` - -3. Enter your Z.AI API key. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Select provider - │ Z.AI - │ - ◇ Enter your API key - │ _ - └ - ``` - -4. Run the `/models` command to select a model like _GLM-4.5_. - ---- - -## Custom provider - -To add any **OpenAI-compatible** provider that's not listed in `opencode auth login`: - -:::tip -You can use any OpenAI-compatible provider with opencode. Most modern AI providers offer OpenAI-compatible APIs. -::: - -1. Run `opencode auth login` and scroll down to **Other**. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◆ Select provider - │ ... - │ ● Other - └ - ``` - -2. Enter a unique ID for the provider. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ◇ Enter provider id - │ myprovider - └ - ``` - - :::note - Choose a memorable ID, you'll use this in your config file. - ::: - -3. Enter your API key for the provider. - - ```bash - $ opencode auth login - - ┌ Add credential - │ - ▲ This only stores a credential for myprovider - you will need configure it in opencode.json, check the docs for examples. - │ - ◇ Enter your API key - │ sk-... - └ - ``` - -4. Create or update your `opencode.json` file in your project directory: - - ```json title="opencode.json" ""myprovider"" {5-15} - { - "$schema": "https://opencode.ai/config.json", - "provider": { - "myprovider": { - "npm": "@ai-sdk/openai-compatible", - "name": "My AI ProviderDisplay Name", - "options": { - "baseURL": "https://api.myprovider.com/v1" - }, - "models": { - "my-model-name": { - "name": "My Model Display Name" - } - } - } - } - } - ``` - - Here are the configuration options: - - - **npm**: AI SDK package to use, `@ai-sdk/openai-compatible` for OpenAI-compatible providers - - **name**: Display name in UI. - - **models**: Available models. - - **options.baseURL**: API endpoint URL. - - **options.apiKey**: Optionally set the API key, if not using auth. - - **options.headers**: Optionally set custom headers. - - More on the advanced options in the example below. - -5. Run the `/models` command and your custom provider and models will appear in the selection list. - ---- - -##### Example - -Here's an example setting the `apiKey` and `headers` options. - -```json title="opencode.json" {9,11} -{ - "$schema": "https://opencode.ai/config.json", - "provider": { - "myprovider": { - "npm": "@ai-sdk/openai-compatible", - "name": "My AI ProviderDisplay Name", - "options": { - "baseURL": "https://api.myprovider.com/v1", - "apiKey": "{env:ANTHROPIC_API_KEY}", - "headers": { - "Authorization": "Bearer custom-token" - } - }, - "models": { - "my-model-name": { - "name": "My Model Display Name" - } - } - } - } -} -``` - -We are setting the `apiKey` using the `env` variable syntax, [learn more](/docs/config#env-vars). - ---- - -## Troubleshooting - -If you are having trouble with configuring a provider, check the following: - -1. **Check the auth setup**: Run `opencode auth list` to see if the credentials - for the provider are added to your config. - - This doesn't apply to providers like Amazon Bedrock, that rely on environment variables for their auth. - -2. For custom providers, check the opencode config and: - - - Make sure the provider ID used in `opencode auth login` matches the ID in your opencode config. - - The right npm package is used for the provider. For example, use `@ai-sdk/cerebras` for Cerebras. And for all other OpenAI-compatible providers, use `@ai-sdk/openai-compatible`. - - Check correct API endpoint is used in the `options.baseURL` field. diff --git a/packages/web/src/content/docs/docs/rules.mdx b/packages/web/src/content/docs/docs/rules.mdx deleted file mode 100644 index aa5590bb5..000000000 --- a/packages/web/src/content/docs/docs/rules.mdx +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Rules -description: Set custom instructions for opencode. ---- - -You can provide custom instructions to opencode by creating an `AGENTS.md` file. This is similar to `CLAUDE.md` or Cursor's rules. It contains instructions that will be included in the LLM's context to customize its behavior for your specific project. - ---- - -## Initialize - -To create a new `AGENTS.md` file, you can run the `/init` command in opencode. - -:::tip -You should commit your project's `AGENTS.md` file to Git. -::: - -This will scan your project and all its contents to understand what the project is about and generate an `AGENTS.md` file with it. This helps opencode to navigate the project better. - -If you have an existing `AGENTS.md` file, this will try to add to it. - ---- - -## Example - -You can also just create this file manually. Here's an example of some things you can put into an `AGENTS.md` file. - -```markdown title="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` -``` - -We are adding project-specific instructions here and this will be shared across your team. - ---- - -## Types - -opencode also supports reading the `AGENTS.md` file from multiple locations. And this serves different purposes. - -### Project - -The ones we have seen above, where the `AGENTS.md` is placed in the project root, are project-specific rules. These only apply when you are working in this directory or its sub-directories. - -### Global - -You can also have global rules in a `~/.config/opencode/AGENTS.md` file. This gets applied across all opencode sessions. - -Since this isn't committed to Git or shared with your team, we recommend using this to specify any personal rules that the LLM should follow. - ---- - -## Precedence - -So when opencode starts, it looks for: - -1. **Local files** by traversing up from the current directory -2. **Global file** by checking `~/.config/opencode/AGENTS.md` - -If you have both global and project-specific rules, opencode will combine them together. - ---- - -## Custom Instructions - -You can specify custom instruction files in your `opencode.json` or the global `~/.config/opencode/opencode.json`. This allows you and your team to reuse existing rules rather than having to duplicate them to AGENTS.md. - -Example: - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] -} -``` - -All instruction files are combined with your `AGENTS.md` files. - ---- - -## Referencing External Files - -While opencode doesn't automatically parse file references in `AGENTS.md`, you can achieve similar functionality in two ways: - -### Using opencode.json - -The recommended approach is to use the `instructions` field in `opencode.json`: - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] -} -``` - -### Manual Instructions in AGENTS.md - -You can teach opencode to read external files by providing explicit instructions in your `AGENTS.md`. Here's a practical example: - -```markdown title="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.md -For React component architecture and hooks patterns: @docs/react-patterns.md -For REST API design and error handling: @docs/api-standards.md -For 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. -``` - -This approach allows you to: - -- Create modular, reusable rule files -- Share rules across projects via symlinks or git submodules -- Keep AGENTS.md concise while referencing detailed guidelines -- Ensure opencode loads files only when needed for the specific task - -:::tip -For monorepos or projects with shared standards, using `opencode.json` with glob patterns (like `packages/*/AGENTS.md`) is more maintainable than manual instructions. -::: diff --git a/packages/web/src/content/docs/docs/sdk.mdx b/packages/web/src/content/docs/docs/sdk.mdx deleted file mode 100644 index aaf218cc7..000000000 --- a/packages/web/src/content/docs/docs/sdk.mdx +++ /dev/null @@ -1,359 +0,0 @@ ---- -title: SDK -description: Type-safe JS client for opencode server. ---- - -import config from "../../../../config.mjs" -export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` - -The opencode JS/TS SDK provides a type-safe client for interacting with the server. -Use it to build integrations and control opencode programmatically. - -[Learn more](/docs/server) about how the server works. - ---- - -## Install - -Install the SDK from npm: - -```bash -npm install @opencode-ai/sdk -``` - ---- - -## Create client - -Create a client instance to connect to your server: - -```javascript -import { createOpencodeClient } from "@opencode-ai/sdk" - -const client = createOpencodeClient({ - baseUrl: "http://localhost:4096", - responseStyle: "data", -}) -``` - -#### Options - -| Option | Type | Description | Default | -| --------------- | ---------- | -------------------------------- | ----------------------- | -| `baseUrl` | `string` | URL of the server | `http://localhost:4096` | -| `fetch` | `function` | Custom fetch implementation | `globalThis.fetch` | -| `parseAs` | `string` | Response parsing method | `auto` | -| `responseStyle` | `string` | Return style: `data` or `fields` | `fields` | -| `throwOnError` | `boolean` | Throw errors instead of return | `false` | - ---- - -## Start server - -You can also programmatically start an opencode server: - -```javascript -import { createOpencodeServer } from "@opencode-ai/sdk" - -const server = await createOpencodeServer({ - hostname: "127.0.0.1", - port: 4096, -}) - -console.log(`Server running at ${server.url}`) - -server.close() -``` - -You can pass a configuration object to customize server behavior. The server still picks up your `opencode.json`, but you can override or add configuration inline: - -```javascript -import { createOpencodeServer } from "@opencode-ai/sdk" - -const server = await createOpencodeServer({ - hostname: "127.0.0.1", - port: 4096, - config: { - model: "anthropic/claude-3-5-sonnet-20241022", - }, -}) - -console.log(`Server running at ${server.url}`) - -server.close() -``` - -#### Options - -| Option | Type | Description | Default | -| ---------- | ------------- | ------------------------------ | ----------- | -| `hostname` | `string` | Server hostname | `127.0.0.1` | -| `port` | `number` | Server port | `4096` | -| `signal` | `AbortSignal` | Abort signal for cancellation | `undefined` | -| `timeout` | `number` | Timeout in ms for server start | `5000` | -| `config` | `Config` | Configuration object | `{}` | - ---- - -## Types - -The SDK includes TypeScript definitions for all API types. Import them directly: - -```typescript -import type { Session, Message, Part } from "@opencode-ai/sdk" -``` - -All types are generated from the server's OpenAPI specification and available in the types file. - ---- - -## Errors - -The SDK can throw errors that you can catch and handle: - -```typescript -try { - await client.session.get({ path: { id: "invalid-id" } }) -} catch (error) { - console.error("Failed to get session:", (error as Error).message) -} -``` - ---- - -## APIs - -The SDK exposes all server APIs through a type-safe client. - ---- - -### App - -| Method | Description | Response | -| -------------- | ------------------------- | ------------------------------------------- | -| `app.log()` | Write a log entry | `boolean` | -| `app.agents()` | List all available agents | Agent[] | - ---- - -#### Examples - -```javascript -// Write a log entry -await client.app.log({ - body: { - service: "my-app", - level: "info", - message: "Operation completed", - }, -}) - -// List available agents -const agents = await client.app.agents() -``` - ---- - -### Project - -| Method | Description | Response | -| ------------------- | ------------------- | --------------------------------------------- | -| `project.list()` | List all projects | Project[] | -| `project.current()` | Get current project | Project | - ---- - -#### Examples - -```javascript -// List all projects -const projects = await client.project.list() - -// Get current project -const currentProject = await client.project.current() -``` - ---- - -### Path - -| Method | Description | Response | -| ------------ | ---------------- | ---------------------------------------- | -| `path.get()` | Get current path | Path | - ---- - -#### Examples - -```javascript -// Get current path information -const pathInfo = await client.path.get() -``` - ---- - -### Config - -| Method | Description | Response | -| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | -| `config.get()` | Get config info | Config | -| `config.providers()` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | - ---- - -#### Examples - -```javascript -const config = await client.config.get() - -const { providers, default: defaults } = await client.config.providers() -``` - ---- - -### Sessions - -| Method | Description | Notes | -| ---------------------------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| `session.list()` | List sessions | Returns Session[] | -| `session.get({ path })` | Get session | Returns Session | -| `session.children({ path })` | List child sessions | Returns Session[] | -| `session.create({ body })` | Create session | Returns Session | -| `session.delete({ path })` | Delete session | Returns `boolean` | -| `session.update({ path, body })` | Update session properties | Returns Session | -| `session.init({ path, body })` | Analyze app and create `AGENTS.md` | Returns `boolean` | -| `session.abort({ path })` | Abort a running session | Returns `boolean` | -| `session.share({ path })` | Share session | Returns Session | -| `session.unshare({ path })` | Unshare session | Returns Session | -| `session.summarize({ path, body })` | Summarize session | Returns `boolean` | -| `session.messages({ path })` | List messages in a session | Returns `{ info: `Message`, parts: `Part[]`}[]` | -| `session.message({ path })` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | -| `session.prompt({ path, body })` | Send prompt message | Returns `{ info: `AssistantMessage`, parts: `Part[]`}` | -| `session.command({ path, body })` | Send command to session | Returns `{ info: `AssistantMessage`, parts: `Part[]`}` | -| `session.shell({ path, body })` | Run a shell command | Returns AssistantMessage | -| `session.revert({ path, body })` | Revert a message | Returns Session | -| `session.unrevert({ path })` | Restore reverted messages | Returns Session | -| `postSessionByIdPermissionsByPermissionId({ path, body })` | Respond to a permission request | Returns `boolean` | - ---- - -#### Examples - -```javascript -// Create and manage sessions -const session = await client.session.create({ - body: { title: "My session" }, -}) - -const sessions = await client.session.list() - -// Send a prompt message -const result = await client.session.prompt({ - path: { id: session.id }, - body: { - model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, - parts: [{ type: "text", text: "Hello!" }], - }, -}) -``` - ---- - -### Files - -| Method | Description | Response | -| ------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------- | -| `find.text({ query })` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | -| `find.files({ query })` | Find files by name | `string[]` (file paths) | -| `find.symbols({ query })` | Find workspace symbols | Symbol[] | -| `file.read({ query })` | Read a file | `{ type: "raw" \| "patch", content: string }` | -| `file.status({ query? })` | Get status for tracked files | File[] | - ---- - -#### Examples - -```javascript -// Search and read files -const textResults = await client.find.text({ - query: { pattern: "function.*opencode" }, -}) - -const files = await client.find.files({ - query: { query: "*.ts" }, -}) - -const content = await client.file.read({ - query: { path: "src/index.ts" }, -}) -``` - ---- - -### TUI - -| Method | Description | Response | -| ------------------------------ | ------------------------- | --------- | -| `tui.appendPrompt({ body })` | Append text to the prompt | `boolean` | -| `tui.openHelp()` | Open the help dialog | `boolean` | -| `tui.openSessions()` | Open the session selector | `boolean` | -| `tui.openThemes()` | Open the theme selector | `boolean` | -| `tui.openModels()` | Open the model selector | `boolean` | -| `tui.submitPrompt()` | Submit the current prompt | `boolean` | -| `tui.clearPrompt()` | Clear the prompt | `boolean` | -| `tui.executeCommand({ body })` | Execute a command | `boolean` | -| `tui.showToast({ body })` | Show toast notification | `boolean` | - ---- - -#### Examples - -```javascript -// Control TUI interface -await client.tui.appendPrompt({ - body: { text: "Add this to prompt" }, -}) - -await client.tui.showToast({ - body: { message: "Task completed", variant: "success" }, -}) -``` - ---- - -### Auth - -| Method | Description | Response | -| ------------------- | ------------------------------ | --------- | -| `auth.set({ ... })` | Set authentication credentials | `boolean` | - ---- - -#### Examples - -```javascript -await client.auth.set({ - path: { id: "anthropic" }, - body: { type: "api", key: "your-api-key" }, -}) -``` - ---- - -### Events - -| Method | Description | Response | -| ------------------- | ------------------------- | ------------------------- | -| `event.subscribe()` | Server-sent events stream | Server-sent events stream | - ---- - -#### Examples - -```javascript -// Listen to real-time events -const events = await client.event.subscribe() -for await (const event of events.stream) { - console.log("Event:", event.type, event.properties) -} -``` diff --git a/packages/web/src/content/docs/docs/server.mdx b/packages/web/src/content/docs/docs/server.mdx deleted file mode 100644 index f63adb6c4..000000000 --- a/packages/web/src/content/docs/docs/server.mdx +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: Server -description: Interact with opencode server over HTTP. ---- - -import config from "../../../../config.mjs" -export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` - -The `opencode serve` command runs a headless HTTP server that exposes an OpenAPI endpoint that an opencode client can use. - ---- - -### Usage - -```bash -opencode serve [--port ] [--hostname ] -``` - -#### Options - -| Flag | Short | Description | Default | -| ------------ | ----- | --------------------- | ----------- | -| `--port` | `-p` | Port to listen on | `4096` | -| `--hostname` | `-h` | Hostname to listen on | `127.0.0.1` | - ---- - -### How it works - -When you run `opencode` it starts a TUI and a server. Where the TUI is the -client that talks to the server. The server exposes an OpenAPI 3.1 spec -endpoint. This endpoint is also used to generate an [SDK](/docs/sdk). - -:::tip -Use the opencode server to interact with opencode programmatically. -::: - -This architecture lets opencode support multiple clients and allows you to interact with opencode programmatically. - -You can run `opencode serve` to start a standalone server. If you have the -opencode TUI running, `opencode serve` will start a new server. - ---- - -#### Connect to an existing server - -When you start the TUI it randomly assigns a port and hostname. You can instead pass in the `--hostname` and `--port` [flags](/docs/cli). Then use this to connect to its server. - -The [`/tui`](#tui) endpoint can be used to drive the TUI through the server. For example, you can prefill or run a prompt. This setup is used by the opencode [IDE](/docs/ide) plugins. - ---- - -## Spec - -The server publishes an OpenAPI 3.1 spec that can be viewed at: - -``` -http://:/doc -``` - -For example, `http://localhost:4096/doc`. Use the spec to generate clients or inspect request and response types. Or view it in a Swagger explorer. - ---- - -## APIs - -The opencode server exposes the following APIs. - ---- - -### App - -| Method | Path | Description | Response | -| ------ | ----------- | ------------------ | --------------------------------------- | -| `GET` | `/app` | Get app info | App | -| `POST` | `/app/init` | Initialize the app | `boolean` | - ---- - -### Config - -| Method | Path | Description | Response | -| ------ | ------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | -| `GET` | `/config` | Get config info | Config | -| `GET` | `/config/providers` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | - ---- - -### Sessions - -| Method | Path | Description | Notes | -| -------- | ---------------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `GET` | `/session` | List sessions | Returns Session[] | -| `GET` | `/session/:id` | Get session | Returns Session | -| `GET` | `/session/:id/children` | List child sessions | Returns Session[] | -| `POST` | `/session` | Create session | body: `{ parentID?, title? }`, returns Session | -| `DELETE` | `/session/:id` | Delete session | | -| `PATCH` | `/session/:id` | Update session properties | body: `{ title? }`, returns Session | -| `POST` | `/session/:id/init` | Analyze app and create `AGENTS.md` | body: `{ messageID, providerID, modelID }` | -| `POST` | `/session/:id/abort` | Abort a running session | | -| `POST` | `/session/:id/share` | Share session | Returns Session | -| `DELETE` | `/session/:id/share` | Unshare session | Returns Session | -| `POST` | `/session/:id/summarize` | Summarize session | | -| `GET` | `/session/:id/message` | List messages in a session | Returns `{ info: `Message`, parts: `Part[]`}[]` | -| `GET` | `/session/:id/message/:messageID` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | -| `POST` | `/session/:id/message` | Send chat message | body matches [`ChatInput`](https://github.com/sst/opencode/blob/main/packages/opencode/src/session/index.ts#L358), returns Message | -| `POST` | `/session/:id/shell` | Run a shell command | body matches [`CommandInput`](https://github.com/sst/opencode/blob/main/packages/opencode/src/session/index.ts#L1007), returns Message | -| `POST` | `/session/:id/revert` | Revert a message | body: `{ messageID }` | -| `POST` | `/session/:id/unrevert` | Restore reverted messages | | -| `POST` | `/session/:id/permissions/:permissionID` | Respond to a permission request | body: `{ response }` | - ---- - -### Files - -| Method | Path | Description | Response | -| ------ | ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------- | -| `GET` | `/find?pattern=` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | -| `GET` | `/find/file?query=` | Find files by name | `string[]` (file paths) | -| `GET` | `/find/symbol?query=` | Find workspace symbols | Symbol[] | -| `GET` | `/file?path=` | Read a file | `{ type: "raw" \| "patch", content: string }` | -| `GET` | `/file/status` | Get status for tracked files | File[] | - ---- - -### Logging - -| Method | Path | Description | Response | -| ------ | ------ | ------------------------------------------------------------ | --------- | -| `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | - ---- - -### Agents - -| Method | Path | Description | Response | -| ------ | -------- | ------------------------- | ------------------------------------------- | -| `GET` | `/agent` | List all available agents | Agent[] | - ---- - -### TUI - -| Method | Path | Description | Response | -| ------ | ----------------------- | ------------------------------------------- | ---------------------- | -| `POST` | `/tui/append-prompt` | Append text to the prompt | `boolean` | -| `POST` | `/tui/open-help` | Open the help dialog | `boolean` | -| `POST` | `/tui/open-sessions` | Open the session selector | `boolean` | -| `POST` | `/tui/open-themes` | Open the theme selector | `boolean` | -| `POST` | `/tui/open-models` | Open the model selector | `boolean` | -| `POST` | `/tui/submit-prompt` | Submit the current prompt | `boolean` | -| `POST` | `/tui/clear-prompt` | Clear the prompt | `boolean` | -| `POST` | `/tui/execute-command` | Execute a command (`{ command }`) | `boolean` | -| `POST` | `/tui/show-toast` | Show toast (`{ title?, message, variant }`) | `boolean` | -| `GET` | `/tui/control/next` | Wait for the next control request | Control request object | -| `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | - ---- - -### Auth - -| Method | Path | Description | Response | -| ------ | ----------- | --------------------------------------------------------------- | --------- | -| `PUT` | `/auth/:id` | Set authentication credentials. Body must match provider schema | `boolean` | - ---- - -### Events - -| Method | Path | Description | Response | -| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | -| `GET` | `/event` | Server-sent events stream. First event is `server.connected`, then bus events | Server-sent events stream | - ---- - -### Docs - -| Method | Path | Description | Response | -| ------ | ------ | -------------------------------------- | ------------------------------------------ | -| `GET` | `/doc` | OpenAPI 3.1 specification | HTML page with OpenAPI spec | diff --git a/packages/web/src/content/docs/docs/share.mdx b/packages/web/src/content/docs/docs/share.mdx deleted file mode 100644 index efb54c2d5..000000000 --- a/packages/web/src/content/docs/docs/share.mdx +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: Share -description: Share your opencode conversations. ---- - -opencode's share feature allows you to create public links to your opencode conversations, so you can collaborate with teammates or get help from others. - -:::note -Shared conversations are publicly accessible to anyone with the link. -::: - ---- - -## How it works - -When you share a conversation, opencode: - -1. Creates a unique public URL for your session -2. Syncs your conversation history to our servers -3. Makes the conversation accessible via the shareable link — `opencode.ai/s/` - ---- - -## Sharing - -opencode supports three sharing modes that control how conversations are shared: - ---- - -### Manual (default) - -By default, opencode uses manual sharing mode. Sessions are not shared automatically, but you can manually share them using the `/share` command: - -``` -/share -``` - -This will generate a unique URL that'll be copied to your clipboard. - -To explicitly set manual mode in your [config file](/docs/config): - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "share": "manual" -} -``` - ---- - -### Auto-share - -You can enable automatic sharing for all new conversations by setting the `share` option to `"auto"` in your [config file](/docs/config): - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "share": "auto" -} -``` - -With auto-share enabled, every new conversation will automatically be shared and a link will be generated. - ---- - -### Disabled - -You can disable sharing entirely by setting the `share` option to `"disabled"` in your [config file](/docs/config): - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "share": "disabled" -} -``` - -To enforce this across your team for a given project, add it to the `opencode.json` in your project and check into Git. - ---- - -## Un-sharing - -To stop sharing a conversation and remove it from public access: - -``` -/unshare -``` - -This will remove the share link and delete the data related to the conversation. - ---- - -## Privacy - -There are a few things to keep in mind when sharing a conversation. - ---- - -### Data retention - -Shared conversations remain accessible until you explicitly unshare them. This -includes: - -- Full conversation history -- All messages and responses -- Session metadata - ---- - -### Recommendations - -- Only share conversations that don't contain sensitive information. -- Review conversation content before sharing. -- Unshare conversations when collaboration is complete. -- Avoid sharing conversations with proprietary code or confidential data. -- For sensitive projects, disable sharing entirely. - ---- - -## For enterprises - -For enterprise deployments, the share feature can be: - -- **Disabled** entirely for security compliance -- **Restricted** to users authenticated through SSO only -- **Self-hosted** on your own infrastructure - -[Learn more](/docs/enterprise) about using opencode in your organization. diff --git a/packages/web/src/content/docs/docs/themes.mdx b/packages/web/src/content/docs/docs/themes.mdx deleted file mode 100644 index 3defceaea..000000000 --- a/packages/web/src/content/docs/docs/themes.mdx +++ /dev/null @@ -1,368 +0,0 @@ ---- -title: Themes -description: Select a built-in theme or define your own. ---- - -With opencode you can select from one of several built-in themes, use a theme that adapts to your terminal theme, or define your own custom theme. - -By default, opencode uses our own `opencode` theme. - ---- - -## Terminal requirements - -For themes to display correctly with their full color palette, your terminal must support **truecolor** (24-bit color). Most modern terminals support this by default, but you may need to enable it: - -- **Check support**: Run `echo $COLORTERM` - it should output `truecolor` or `24bit` -- **Enable truecolor**: Set the environment variable `COLORTERM=truecolor` in your shell profile -- **Terminal compatibility**: Ensure your terminal emulator supports 24-bit color (most modern terminals like iTerm2, Alacritty, Kitty, Windows Terminal, and recent versions of GNOME Terminal do) - -Without truecolor support, themes may appear with reduced color accuracy or fall back to the nearest 256-color approximation. - ---- - -## Built-in themes - -opencode comes with several built-in themes. - -| Name | Description | -| ------------ | ------------------------------------------ | -| `system` | Adapts to your terminal's background color | -| `tokyonight` | Based on the Tokyonight theme | -| `everforest` | Based on the Everforest theme | -| `ayu` | Based on the Ayu dark theme | -| `catppuccin` | Based on the Catppuccin theme | -| `gruvbox` | Based on the Gruvbox theme | -| `kanagawa` | Based on the Kanagawa theme | -| `nord` | Based on the Nord theme | -| `matrix` | Hacker-style green on black theme | -| `one-dark` | Based on the Atom One Dark theme | - -And more, we are constantly adding new themes. - ---- - -## System theme - -The `system` theme is designed to automatically adapt to your terminal's color scheme. Unlike traditional themes that use fixed colors, the _system_ theme: - -- **Generates gray scale**: Creates a custom gray scale based on your terminal's background color, ensuring optimal contrast. -- **Uses ANSI colors**: Leverages standard ANSI colors (0-15) for syntax highlighting and UI elements, which respect your terminal's color palette. -- **Preserves terminal defaults**: Uses `none` for text and background colors to maintain your terminal's native appearance. - -The system theme is for users who: - -- Want opencode to match their terminal's appearance -- Use custom terminal color schemes -- Prefer a consistent look across all terminal applications - ---- - -## Using a theme - -You can select a theme by bringing up the theme select with the `/theme` command. Or you can specify it in your [config](/docs/config). - -```json title="opencode.json" {3} -{ - "$schema": "https://opencode.ai/config.json", - "theme": "tokyonight" -} -``` - ---- - -## Custom themes - -opencode supports a flexible JSON-based theme system that allows users to create and customize themes easily. - ---- - -### Hierarchy - -Themes are loaded from multiple directories in the following order where later directories override earlier ones: - -1. **Built-in themes** - These are embedded in the binary -2. **User config directory** - Defined in `~/.config/opencode/themes/*.json` or `$XDG_CONFIG_HOME/opencode/themes/*.json` -3. **Project root directory** - Defined in the `/.opencode/themes/*.json` -4. **Current working directory** - Defined in `./.opencode/themes/*.json` - -If multiple directories contain a theme with the same name, the theme from the directory with higher priority will be used. - ---- - -### Creating a theme - -To create a custom theme, create a JSON file in one of the theme directories. - -For user-wide themes: - -```bash no-frame -mkdir -p ~/.config/opencode/themes -vim ~/.config/opencode/themes/my-theme.json -``` - -And for project-specific themes. - -```bash no-frame -mkdir -p .opencode/themes -vim .opencode/themes/my-theme.json -``` - ---- - -### JSON format - -Themes use a flexible JSON format with support for: - -- **Hex colors**: `"#ffffff"` -- **ANSI colors**: `3` (0-255) -- **Color references**: `"primary"` or custom definitions -- **Dark/light variants**: `{"dark": "#000", "light": "#fff"}` -- **No color**: `"none"` - Uses the terminal's default color or transparent - ---- - -### Color definitions - -The `defs` section is optional and it allows you to define reusable colors that can be referenced in the theme. - ---- - -### Terminal defaults - -The special value `"none"` can be used for any color to inherit the terminal's default color. This is particularly useful for creating themes that blend seamlessly with your terminal's color scheme: - -- `"text": "none"` - Uses terminal's default foreground color -- `"background": "none"` - Uses terminal's default background color - ---- - -### Example - -Here's an example of a custom theme: - -```json title="my-theme.json" -{ - "$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" - } - } -} -``` diff --git a/packages/web/src/content/docs/docs/troubleshooting.mdx b/packages/web/src/content/docs/docs/troubleshooting.mdx deleted file mode 100644 index b846bed2d..000000000 --- a/packages/web/src/content/docs/docs/troubleshooting.mdx +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Troubleshooting -description: Common issues and how to resolve them. ---- - -To debug any issues with opencode, you can check the logs or the session data -that it stores locally. - ---- - -### Logs - -Log files are written to: - -- **macOS/Linux**: `~/.local/share/opencode/log/` -- **Windows**: `%APPDATA%\opencode\log\` - -Log files are named with timestamps (e.g., `2025-01-09T123456.log`) and the most recent 10 log files are kept. - -You can set the log level with the `--log-level` command-line option to get more detailed debug information. For example, `opencode --log-level DEBUG`. - ---- - -### Storage - -opencode stores session data and other application data on disk at: - -- **macOS/Linux**: `~/.local/share/opencode/` -- **Windows**: `%USERPROFILE%\.local\share\opencode` - -This directory contains: - -- `auth.json` - Authentication data like API keys, OAuth tokens -- `log/` - Application logs -- `project/` - Project-specific data like session and message data - - If the project is within a Git repo, it is stored in `.//storage/` - - If it is not a Git repo, it is stored in `./global/storage/` - ---- - -## Getting help - -If you're experiencing issues with opencode: - -1. **Report issues on GitHub** - - The best way to report bugs or request features is through our GitHub repository: - - [**github.com/sst/opencode/issues**](https://github.com/sst/opencode/issues) - - Before creating a new issue, search existing issues to see if your problem has already been reported. - -2. **Join our Discord** - - For real-time help and community discussion, join our Discord server: - - [**opencode.ai/discord**](https://opencode.ai/discord) - ---- - -## Common issues - -Here are some common issues and how to resolve them. - ---- - -### opencode won't start - -1. Check the logs for error messages -2. Try running with `--print-logs` to see output in the terminal -3. Ensure you have the latest version with `opencode upgrade` - ---- - -### Authentication issues - -1. Try re-authenticating with `opencode auth login ` -2. Check that your API keys are valid -3. Ensure your network allows connections to the provider's API - ---- - -### Model not available - -1. Check that you've authenticated with the provider -2. Verify the model name in your config is correct -3. Some models may require specific access or subscriptions - ---- - -### ProviderInitError - -If you encounter a ProviderInitError, you likely have an invalid or corrupted configuration. - -To resolve this: - -1. First, verify your provider is set up correctly by following the [providers guide](/docs/providers) -2. If the issue persists, try clearing your stored configuration: - - ```bash - rm -rf ~/.local/share/opencode - ``` - -3. Re-authenticate with your provider: - ```bash - opencode auth login - ``` - ---- - -### AI_APICallError and provider package issues - -If you encounter API call errors, this may be due to outdated provider packages. opencode dynamically installs provider packages (OpenAI, Anthropic, Google, etc.) as needed and caches them locally. - -To resolve provider package issues: - -1. Clear the provider package cache: - - ```bash - rm -rf ~/.cache/opencode - ``` - -2. Restart opencode to reinstall the latest provider packages - -This will force opencode to download the most recent versions of provider packages, which often resolves compatibility issues with model parameters and API changes. - ---- - -### Copy/paste not working on Linux - -Linux users need to have one of the following clipboard utilities installed for copy/paste functionality to work: - -**For X11 systems:** - -```bash -apt install -y xclip -# or -apt install -y xsel -``` - -**For Wayland systems:** - -```bash -apt install -y wl-clipboard -``` - -**For headless environments:** - -```bash -apt install -y xvfb -# and run: -Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & -export DISPLAY=:99.0 -``` - -opencode will detect if you're using Wayland and prefer `wl-clipboard`, otherwise it will try to find clipboard tools in order of: `xclip` and `xsel`. diff --git a/packages/web/src/content/docs/docs/tui.mdx b/packages/web/src/content/docs/docs/tui.mdx deleted file mode 100644 index 113bad697..000000000 --- a/packages/web/src/content/docs/docs/tui.mdx +++ /dev/null @@ -1,315 +0,0 @@ ---- -title: TUI -description: Using the opencode terminal user interface. ---- - -import { Tabs, TabItem } from "@astrojs/starlight/components" - -opencode provides an interactive terminal interface or TUI for working on your projects with an LLM. - -Running opencode starts the TUI for the current directory. - -```bash -opencode -``` - -Or you can start it for a specific working directory. - -```bash -opencode /path/to/project -``` - -Once you're in the TUI, you can prompt it with a message. - -```text -Give me a quick summary of the codebase. -``` - ---- - -## File references - -You can reference files in your messages using `@`. This does a fuzzy file search in the current working directory. - -:::tip -You can also use `@` to reference files in your messages. -::: - -```text "@packages/functions/src/api/index.ts" -How is auth handled in @packages/functions/src/api/index.ts? -``` - -The content of the file is added to the conversation automatically. - ---- - -## Bash commands - -Start a message with `!` to run a shell command. - -```bash frame="none" -!ls -la -``` - -The output of the command is added to the conversation as a tool result. - ---- - -## Commands - -When using the opencode TUI, you can type `/` followed by a command name to quickly execute actions. For example: - -```bash frame="none" -/help -``` - -Most commands also have keybind using `ctrl+x` as the leader key, where `ctrl+x` is the default leader key. [Learn more](/docs/keybinds). - -Here are all available slash commands: - ---- - -### compact - -Compact the current session. _Alias_: `/summarize` - -```bash frame="none" -/compact -``` - -**Keybind:** `ctrl+x c` - ---- - -### details - -Toggle tool execution details. - -```bash frame="none" -/details -``` - -**Keybind:** `ctrl+x d` - ---- - -### editor - -Open external editor for composing messages. Uses the editor set in your `EDITOR` environment variable. [Learn more](#editor-setup). - -```bash frame="none" -/editor -``` - -**Keybind:** `ctrl+x e` - ---- - -### exit - -Exit opencode. _Aliases_: `/quit`, `/q` - -```bash frame="none" -/exit -``` - -**Keybind:** `ctrl+x q` - ---- - -### export - -Export current conversation to Markdown and open in your default editor. Uses the editor set in your `EDITOR` environment variable. [Learn more](#editor-setup). - -```bash frame="none" -/export -``` - -**Keybind:** `ctrl+x x` - ---- - -### help - -Show the help dialog. - -```bash frame="none" -/help -``` - -**Keybind:** `ctrl+x h` - ---- - -### init - -Create or update `AGENTS.md` file. [Learn more](/docs/rules). - -```bash frame="none" -/init -``` - -**Keybind:** `ctrl+x i` - ---- - -### models - -List available models. - -```bash frame="none" -/models -``` - -**Keybind:** `ctrl+x m` - ---- - -### new - -Start a new session. _Alias_: `/clear` - -```bash frame="none" -/new -``` - -**Keybind:** `ctrl+x n` - ---- - -### redo - -Redo a previously undone message. Only available after using `/undo`. - -:::tip -Any file changes will also be restored. -::: - -```bash frame="none" -/redo -``` - -**Keybind:** `ctrl+x r` - ---- - -### sessions - -List and switch between sessions. _Aliases_: `/resume`, `/continue` - -```bash frame="none" -/sessions -``` - -**Keybind:** `ctrl+x l` - ---- - -### share - -Share current session. [Learn more](/docs/share). - -```bash frame="none" -/share -``` - -**Keybind:** `ctrl+x s` - ---- - -### themes - -List available themes. - -```bash frame="none" -/themes -``` - -**Keybind:** `ctrl+x t` - ---- - -### undo - -Undo last message in the conversation. Removes the most recent user message, all subsequent responses, and any file changes. - -:::tip -Any file changes made will also be reverted. -::: - -```bash frame="none" -/undo -``` - -**Keybind:** `ctrl+x u` - ---- - -### unshare - -Unshare current session. [Learn more](/docs/share#un-sharing). - -```bash frame="none" -/unshare -``` - ---- - -## Editor setup - -Both the `/editor` and `/export` commands use the editor specified in your `EDITOR` environment variable. - - - - ```bash - # Example for nano or vim - export EDITOR=nano - export EDITOR=vim - - # For GUI editors (VS Code, Cursor, VSCodium, Windsurf, Zed, etc.) include --wait - export EDITOR="code --wait" - ``` - - To make it permanent, add this to your shell profile; - `~/.bashrc`, `~/.zshrc`, etc. - - - - ```bash - set EDITOR=notepad - - # For GUI editors (VS Code, Cursor, VSCodium, Windsurf, Zed, etc.) include --wait - set EDITOR=code --wait - ``` - - To make it permanent, use **System Properties** > **Environment - Variables**. - - - - ```powershell - $env:EDITOR = "notepad" - - # For GUI editors (VS Code, Cursor, VSCodium, Windsurf, Zed, etc.) include --wait - $env:EDITOR = "code --wait" - ``` - - To make it permanent, add this to your PowerShell profile. - - - -Popular editor options include: - -- `code` - Visual Studio Code -- `cursor` - Cursor -- `windsurf` - Windsurf -- `vim` - Vim editor -- `nano` - Nano editor -- `notepad` - Windows Notepad -- `subl` - Sublime Text - -:::note -Some editors like VS Code need to be started with the `--wait` flag. -::: - -Some editors need command-line arguments to run in blocking mode. The `--wait` flag makes the editor process block until closed. diff --git a/packages/web/src/content/docs/docs/zen.mdx b/packages/web/src/content/docs/docs/zen.mdx deleted file mode 100644 index 46d457932..000000000 --- a/packages/web/src/content/docs/docs/zen.mdx +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Zen -description: Curated list of models provided by opencode. ---- - -import config from "../../../../config.mjs" -export const console = config.console -export const email = `mailto:${config.email}` - -opencode zen is a list of tested and verified models provided by the opencode team. - -:::note -opencode zen is currently in beta. -::: - -Zen works like any other provider in opencode. You login to opencode zen and get -your API key. It's **completely optional** and you don't need to use it to use -opencode. - ---- - -## Background - -There are a large number of models out there but only a few of -these models work well as coding agents. Additionally, most providers are -configured very differently; so you get very different performance and quality. - -:::tip -We tested a select group of models and providers that work well with opencode. -::: - -So if you are using a model through something like OpenRouter, you can never be -sure if you are getting the best version of the model you want. - -To fix this, we did a couple of things: - -1. We tested a select group of models and talked to their teams about how to - best run them. -2. We then worked with a few providers to make sure these were being served - correctly. -3. Finally, we benchmarked the combination of the model/provider and came up - with a list that we feel good recommending. - -opencode zen is an AI gateway that gives you access to these models. - ---- - -## Motivation - -We created opencode zen to: - -1. **Benchmark** the best models/providers for coding agents. -2. Access to **highest quality**; we don't downgrade performance or route to cheaper providers. -3. **Sell at cost**; the only markup is to cover our processing fees and any price - drops will be passed along. -4. **No lock-in**; you can use opencode zen with any other coding agent and you - can use any other provider with opencode. - ---- - -## How it works - -opencode zen works like any other provider in opencode. - -1. You sign in to **opencode zen** and get your API key. -2. You run `opencode auth login` and select opencode zen and add your API key. -3. Run `/models` in the TUI to see the list of models we recommend. - -You are charged per request and you can add credits to your account. - ---- - -## Pricing - -Below are the models that we currently support and their prices **per 1M -tokens**. - -| Model | Input | Output | -| ----- | ----- | ------ | -| Qwen3 Coder 480B | $0.38 | $0.50 | -| Grok Code Fast 1 | Free | Free | -| Sonnet 4 | Soon | Soon | - -:::note -We add a small markup to cover our costs. -::: - -A couple of notes: - -- These are the raw prices based on the provider we are using internally. We -charge a small markup on top of this to cover our processing fees. -- Grok Code Fast 1 is currently free on opencode till Sep 10th. The xAI team is - using this time to collect feedback and improve Grok Code. - -Contact us if you have any questions. diff --git a/packages/web/src/content/docs/enterprise.mdx b/packages/web/src/content/docs/enterprise.mdx new file mode 100644 index 000000000..4faff39cd --- /dev/null +++ b/packages/web/src/content/docs/enterprise.mdx @@ -0,0 +1,105 @@ +--- +title: Enterprise +description: Using opencode in your organization. +--- + +import config from "../../../config.mjs" +export const email = `mailto:${config.email}` + +opencode does not store any of your code or context data. This makes it easy for +you to use opencode at your organization. + +To get started, we recommend: + +1. Do a trial internally with your team. +2. **Contact us** to discuss pricing and implementation options. + +--- + +## Trial + +Since opencode is open source and does not store any of your code or context data, your developers can simply [get started](/docs/) and carry out a trial. + +--- + +### Data handling + +**opencode does not store your code or context data.** All processing happens locally or through direct API calls to your AI provider. + +The only caveat here is the optional `/share` feature. + +--- + +#### Sharing conversations + +If a user enables the `/share` feature, the conversation and the data associated with it are sent to the service we use to host these shares pages at opencode.ai. + +The data is currently served through our CDN's edge network, and is cached on the edge near your users. + +We recommend you disable this for your trial. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +[Learn more about sharing](/docs/share). + +--- + +### Code ownership + +**You own all code produced by opencode.** There are no licensing restrictions or ownership claims. + +--- + +## Deployment + +Once you have completed your trial and you are ready to self-host opencode at +your organization, you can **contact us** to discuss +pricing and implementation options. + +--- + +### SSO + +SSO integration can be implemented for enterprise deployments after your trial. +This will allow your team's session data and shared conversations to be protected +by your enterprise's authentication system. + +--- + +### Private NPM + +opencode supports private npm registries through Bun's native `.npmrc` file support. If your organization uses a private registry, such as JFrog Artifactory, Nexus, or similar, ensure developers are authenticated before running opencode. + +To set up authentication with your private registry: + +```bash +npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +``` + +This creates `~/.npmrc` with authentication details. opencode will automatically +pick this up. + +:::caution +You must be logged into the private registry before running opencode. +::: + +Alternatively, you can manually configure a `.npmrc` file: + +```bash title="~/.npmrc" +registry=https://your-company.jfrog.io/api/npm/npm-virtual/ +//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN} +``` + +Developers must be logged into the private registry before running opencode to ensure packages can be installed from your enterprise registry. + +--- + +### Self-hosting + +The share feature can be self-hosted and the share pages can be made accessible +only after the user has been authenticated. diff --git a/packages/web/src/content/docs/formatters.mdx b/packages/web/src/content/docs/formatters.mdx new file mode 100644 index 000000000..9c9411aeb --- /dev/null +++ b/packages/web/src/content/docs/formatters.mdx @@ -0,0 +1,108 @@ +--- +title: Formatters +description: opencode uses language specific formatters. +--- + +opencode automatically formats files after they are written or edited using language-specific formatters. This ensures that the code that is generated follows the code styles of your project. + +--- + +## Built-in + +opencode comes with several built-in formatters for popular languages and frameworks. Below is a list of the formatters, supported file extensions, and commands or config options it needs. + +| Formatter | Extensions | Requirements | +| -------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------- | +| gofmt | .go | `gofmt` command available | +| mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` command available | +| prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://prettier.io/docs/en/index.html) | `prettier` dependency in `package.json` | +| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://biomejs.dev/) | `biome.json(c)` config file | +| zig | .zig, .zon | `zig` command available | +| clang-format | .c, .cpp, .h, .hpp, .ino, and [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` config file | +| ktlint | .kt, .kts | `ktlint` command available | +| ruff | .py, .pyi | `ruff` command available with config | +| rubocop | .rb, .rake, .gemspec, .ru | `rubocop` command available | +| standardrb | .rb, .rake, .gemspec, .ru | `standardrb` command available | +| htmlbeautifier | .erb, .html.erb | `htmlbeautifier` command available | + +So if your project has `prettier` in your `package.json`, opencode will automatically use it. + +--- + +## How it works + +When opencode writes or edits a file, it: + +1. Checks the file extension against all enabled formatters. +2. Runs the appropriate formatter command on the file. +3. Applies the formatting changes automatically. + +This process happens in the background, ensuring your code styles are maintained without any manual steps. + +--- + +## Configure + +You can customize formatters through the `formatter` section in your opencode config. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { } +} +``` + +Each formatter configuration supports the following: + +| Property | Type | Description | +| ------------- | -------- | ------------------------------------------------------- | +| `disabled` | boolean | Set this to `true` to disable the formatter | +| `command` | string[] | The command to run for formatting | +| `environment` | object | Environment variables to set when running the formatter | +| `extensions` | string[] | File extensions this formatter should handle | + +Let's look at some examples. + +--- + +### Disabling formatters + +To disable a specific formatter, set `disabled` to `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "disabled": true + } + } +} +``` + +--- + +### Custom formatters + +You can override the built-in formatters or add new ones by specifying the command, environment variables, and file extensions: + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "formatter": { + "prettier": { + "command": ["npx", "prettier", "--write", "$FILE"], + "environment": { + "NODE_ENV": "development" + }, + "extensions": [".js", ".ts", ".jsx", ".tsx"] + }, + "custom-markdown-formatter": { + "command": ["deno", "fmt", "$FILE"], + "extensions": [".md"] + } + } +} +``` + +The **`$FILE` placeholder** in the command will be replaced with the path to the file being formatted. diff --git a/packages/web/src/content/docs/github.mdx b/packages/web/src/content/docs/github.mdx new file mode 100644 index 000000000..d592fc84f --- /dev/null +++ b/packages/web/src/content/docs/github.mdx @@ -0,0 +1,131 @@ +--- +title: GitHub +description: Use opencode in GitHub issues and pull-requests. +--- + +opencode integrates with your GitHub workflow. Mention `/opencode` or `/oc` in your comment, and opencode will execute tasks within your GitHub Actions runner. + +--- + +## Features + +- **Triage issues**: Ask opencode to look into an issue and explain it to you. +- **Fix and implement**: Ask opencode to fix an issue or implement a feature. And it will work in a new branch and submits a PR with all the changes. +- **Secure**: opencode runs inside your GitHub's runners. + +--- + +## Installation + +Run the following command in a project that is in a GitHub repo: + +```bash +opencode github install +``` + +This will walk you through installing the GitHub app, creating the workflow, and setting up secrets. + +--- + +### Manual Setup + +Or you can set it up manually. + +1. **Install the GitHub app** + + Head over to [**github.com/apps/opencode-agent**](https://github.com/apps/opencode-agent). Make sure it's installed on the target repository. + +2. **Add the workflow** + + Add the following workflow file to `.github/workflows/opencode.yml` in your repo. Make sure to set the appropriate `model` and required API keys in `env`. + + ```yml title=".github/workflows/opencode.yml" {24,26} + name: opencode + + on: + issue_comment: + types: [created] + + 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@v4 + with: + fetch-depth: 1 + + - name: Run opencode + uses: sst/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** + + In your organization or project **settings**, expand **Secrets and variables** on the left and select **Actions**. And add the required API keys. + +--- + +## Configuration + +- `model`: The model to use with opencode. Takes the format of `provider/model`. This is **required**. +- `share`: Whether to share the opencode session. Defaults to **true** for public repositories. +- `token`: Optional GitHub access token for performing operations such as creating comments, commiting changes, and opening pull requests. By default, opencode uses the installation access token from the opencode GitHub App, so commits, comments, and pull requests appear as coming from the app. + + Alternatively, you can use the GitHub Action runner's [built-in `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) without installing the opencode GitHub App. Just make sure to grant the required permissions in your workflow: + + ```yaml + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + ``` + + You can also use a [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) if preferred. + +--- + +## Examples + +Here are some examples of how you can use opencode in GitHub. + +- **Explain an issue** + + Add this comment in a GitHub issue. + + ``` + /opencode explain this issue + ``` + + opencode will read the entire thread, including all comments, and reply with a clear explanation. + +- **Fix an issue** + + In a GitHub issue, say: + + ``` + /opencode fix this + ``` + + And opencode will create a new branch, implement the changes, and open a PR with the changes. + +- **Review PRs and make changes** + + Leave the following comment on a GitHub PR. + + ``` + Delete the attachment from S3 when the note is removed /oc + ``` + + opencode will implement the requested change and commit it to the same PR. diff --git a/packages/web/src/content/docs/gitlab.mdx b/packages/web/src/content/docs/gitlab.mdx new file mode 100644 index 000000000..023ac678e --- /dev/null +++ b/packages/web/src/content/docs/gitlab.mdx @@ -0,0 +1,151 @@ +--- +title: GitLab +description: Use opencode in GitLab issues and merge requests. +--- + +opencode integrates with your GitLab workflow. +Mention `@opencode` in a comment, and opencode will execute tasks within your GitLab CI pipeline. + +--- + +## Features + +- **Triage issues**: Ask opencode to look into an issue and explain it to you. +- **Fix and implement**: Ask opencode to fix an issue or implement a feature. + It will work create a new branch and raised a merge request with the changes. +- **Secure**: opencode runs on your GitLab runners. + +--- + +## Setup + +opencode runs in your GitLab CI/CD pipeline, here's what you'll need to set it up: + +:::tip +Check out the [**GitLab docs**](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for up to date instructions. +::: + +1. Configure your GitLab environment +2. Set up CI/CD +3. Get an AI model provider API key +4. Create a service account +5. Configure CI/CD variables +6. Create a flow config file, here's an example: + +
+ Flow configuration + + ```yaml + image: node:22-slim + commands: + - echo "Installing opencode" + - npm install --global opencode-ai + - echo "Installing glab" + - export GITLAB_TOKEN=$GITLAB_TOKEN_OPENCODE + - apt-get update --quiet && apt-get install --yes curl wget gpg git && rm --recursive --force /var/lib/apt/lists/* + - curl --silent --show-error --location "https://raw.githubusercontent.com/upciti/wakemeops/main/assets/install_repository" | bash + - apt-get install --yes glab + - echo "Configuring glab" + - echo $GITLAB_HOST + - echo "Creating opencode auth configuration" + - mkdir --parents ~/.local/share/opencode + - | + cat > ~/.local/share/opencode/auth.json << EOF + { + "anthropic": { + "type": "api", + "key": "$ANTHROPIC_API_KEY" + } + } + EOF + - echo "Configuring git" + - git config --global user.email "opencode@gitlab.com" + - git config --global user.name "Opencode" + - echo "Testing glab" + - glab issue list + - echo "Running Opencode" + - | + opencode run " + You are an AI assistant helping with GitLab operations. + + Context: $AI_FLOW_CONTEXT + Task: $AI_FLOW_INPUT + Event: $AI_FLOW_EVENT + + Please execute the requested task using the available GitLab tools. + Be thorough in your analysis and provide clear explanations. + + + Please use the glab CLI to access data from GitLab. The glab CLI has already been authenticated. You can run the corresponding commands. + + If you are asked to summarise an MR or issue or asked to provide more information then please post back a note to the MR/Issue so that the user can see it. + You don't need to commit or push up changes, those will be done automatically based on the file changes you make. + + " + - git checkout --branch $CI_WORKLOAD_REF origin/$CI_WORKLOAD_REF + - echo "Checking for git changes and pushing if any exist" + - | + if ! git diff --quiet || ! git diff --cached --quiet || [ --not --zero "$(git ls-files --others --exclude-standard)" ]; then + echo "Git changes detected, adding and pushing..." + git add . + if git diff --cached --quiet; then + echo "No staged changes to commit" + else + echo "Committing changes to branch: $CI_WORKLOAD_REF" + git commit --message "Codex changes" + echo "Pushing changes up to $CI_WORKLOAD_REF" + git push https://gitlab-ci-token:$GITLAB_TOKEN@$GITLAB_HOST/gl-demo-ultimate-dev-ai-epic-17570/test-java-project.git $CI_WORKLOAD_REF + echo "Changes successfully pushed" + fi + else + echo "No git changes detected, skipping push" + fi + variables: + - ANTHROPIC_API_KEY + - GITLAB_TOKEN_OPENCODE + - GITLAB_HOST + ``` + +
+ +You can refer to the [GitLab CLI agents docs](https://docs.gitlab.com/user/duo_agent_platform/agent_assistant/) for detailed instructions. + +--- + +## Examples + +Here are some examples of how you can use opencode in GitLab. + +:::tip +You can configure to use a different trigger phrase than `@opencode`. +::: + +- **Explain an issue** + + Add this comment in a GitLab issue. + + ``` + @opencode explain this issue + ``` + + opencode will read the issue and reply with a clear explanation. + +- **Fix an issue** + + In a GitLab issue, say: + + ``` + @opencode fix this + ``` + + opencode will create a new branch, implement the changes, and open a merge request with the changes. + +- **Review merge requests** + + Leave the following comment on a GitLab merge request. + + ``` + @opencode review this merge request + ``` + + opencode will review the merge request and provide feedback. diff --git a/packages/web/src/content/docs/ide.mdx b/packages/web/src/content/docs/ide.mdx new file mode 100644 index 000000000..b2f7d1e10 --- /dev/null +++ b/packages/web/src/content/docs/ide.mdx @@ -0,0 +1,46 @@ +--- +title: IDE +description: The opencode extension for VS Code, Cursor, and other IDEs +--- + +opencode integrates with VS Code, Cursor, or any IDE that supports a terminal. Just run `opencode` in the terminal to get started. + +--- + +## Usage + +- **Quick Launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open opencode in a split terminal view, or focus an existing terminal session if one is already running. +- **New Session**: Use `Cmd+Shift+Esc` (Mac) or `Ctrl+Shift+Esc` (Windows/Linux) to start a new opencode terminal session, even if one is already open. You can also click the opencode button in the UI. +- **Context Awareness**: Automatically share your current selection or tab with opencode. +- **File Reference Shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references. For example, `@File#L37-42`. + +--- + +## Installation + +To install opencode on VS Code and popular forks like Cursor, Windsurf, VSCodium: + +1. Open VS Code +2. Open the integrated terminal +3. Run `opencode` - the extension installs automatically + +--- + +### Manual Install + +Search for **opencode** in the Extension Marketplace and click **Install**. + +--- + +### Troubleshooting + +If the extension fails to install automatically: + +- Ensure you’re running `opencode` in the integrated terminal. +- Confirm the CLI for your IDE is installed: + - For VS Code: `code` command + - For Cursor: `cursor` command + - For Windsurf: `windsurf` command + - For VSCodium: `codium` command + - If not, run `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux) and search for "Shell Command: Install 'code' command in PATH" (or the equivalent for your IDE) +- Ensure VS Code has permission to install extensions diff --git a/packages/web/src/content/docs/index.mdx b/packages/web/src/content/docs/index.mdx index ea39be9ee..7ca2fee79 100644 --- a/packages/web/src/content/docs/index.mdx +++ b/packages/web/src/content/docs/index.mdx @@ -1,12 +1,311 @@ --- -title: opencode -description: The AI coding agent built for the terminal. -template: splash -hero: - title: The AI coding agent built for the terminal. - tagline: The AI coding agent built for the terminal. - image: - dark: ../../assets/logo-ornate-dark.svg - light: ../../assets/logo-ornate-light.svg - alt: opencode logo +title: Intro +description: Get started with opencode. --- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +[**opencode**](/) is an AI coding agent built for the terminal. + +![opencode TUI with the opencode theme](../../assets/lander/screenshot.png) + +Let's get started. + +--- + +#### Prerequisites + +To use opencode, 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 + +The easiest way to install opencode is through the install script. + +```bash +curl -fsSL https://opencode.ai/install | bash +``` + +You can also install it with the following: + +- **Using Node.js** + + + + ```bash + npm install -g opencode-ai + ``` + + + ```bash + bun install -g opencode-ai + ``` + + + ```bash + pnpm install -g opencode-ai + ``` + + + ```bash + yarn global add opencode-ai + ``` + + + +- **Using Homebrew on macOS and Linux** + + ```bash + brew install sst/tap/opencode + ``` + +- **Using Paru on Arch Linux** + + ```bash + paru -S opencode-bin + ``` + +#### Windows + +Right now the automatic installation methods do not work properly on Windows. However you can grab the binary from the [Releases](https://github.com/sst/opencode/releases). + +--- + +## Configure + +With opencode you can use any LLM provider by configuring their API keys. + +We recommend signing up for [Claude Pro](https://www.anthropic.com/news/claude-pro) or [Max](https://www.anthropic.com/max), it's the most cost-effective way to use opencode. + +Once you've signed up, run `opencode auth login` and select Anthropic. + +```bash +$ opencode auth login + +┌ Add credential +│ +◆ Select provider +│ ● Anthropic (recommended) +│ ○ OpenAI +│ ○ Google +│ ○ Amazon Bedrock +│ ○ Azure +│ ○ DeepSeek +│ ○ Groq +│ ... +└ +``` + +Alternatively, you can select one of the other providers. [Learn more](/docs/providers#directory). + +--- + +## Initialize + +Now that you've configured a provider, you can navigate to a project that +you want to work on. + +```bash +cd /path/to/project +``` + +And run opencode. + +```bash +opencode +``` + +Next, initialize opencode for the project by running the following command. + +```bash frame="none" +/init +``` + +This will get opencode to analyze your project and create an `AGENTS.md` file in +the project root. + +:::tip +You should commit your project's `AGENTS.md` file to Git. +::: + +This helps opencode understand the project structure and the coding patterns +used. + +--- + +## Usage + +You are now ready to use opencode to work on your project. Feel free to ask it +anything! + +If you are new to using an AI coding agent, here are some examples that might +help. + +--- + +### Ask questions + +You can ask opencode to explain the codebase to you. + +:::tip +Use the `@` key to fuzzy search for files in the project. +::: + +```txt frame="none" "@packages/functions/src/api/index.ts" +How is authentication handled in @packages/functions/src/api/index.ts +``` + +This is helpful if there's a part of the codebase that you didn't work on. + +--- + +### Add features + +You can ask opencode to add new features to your project. Though we first recommend asking it to create a plan. + +1. **Create a plan** + + opencode has a _Plan mode_ that disables its ability to make changes and + instead suggest _how_ it'll implement the feature. + + Switch to it using the **Tab** key. You'll see an indicator for this in the lower right corner. + + ```bash frame="none" title="Switch to Plan mode" + + ``` + + Now let's describe what we want it to do. + + ```txt frame="none" + When a user deletes a note, we'd like to flag it as deleted in the database. + Then create a screen that shows all the recently deleted notes. + From this screen, the user can undelete a note or permanently delete it. + ``` + + You want to give opencode enough details to understand what you want. It helps + to talk to it like you are talking to a junior developer on your team. + + :::tip + Give opencode plenty of context and examples to help it understand what you + want. + ::: + +2. **Iterate on the plan** + + Once it gives you a plan, you can give it feedback or add more details. + + ```txt frame="none" + We'd like to design this new screen using a design I've used before. + [Image #1] Take a look at this image and use it as a reference. + ``` + + :::tip + Drag and drop images into the terminal to add them to the prompt. + ::: + + opencode can scan any images you give it and add them to the prompt. You can + do this by dragging and dropping an image into the terminal. + +3. **Build the feature** + + Once you feel comfortable with the plan, switch back to _Build mode_ by + hitting the **Tab** key again. + + ```bash frame="none" + + ``` + + And asking it to make the changes. + + ```bash frame="none" + Sounds good! Go ahead and make the changes. + ``` + +--- + +### Make changes + +For more straightforward changes, you can ask opencode to directly build it +without having to review the plan first. + +```txt frame="none" "@packages/functions/src/settings.ts" "@packages/functions/src/notes.ts" +We need to add authentication to the /settings route. Take a look at how this is +handled in the /notes route in @packages/functions/src/notes.ts and implement +the same logic in @packages/functions/src/settings.ts +``` + +You want to make sure you provide a good amount of detail so opencode makes the right +changes. + +--- + +### Undo changes + +Let's say you ask opencode to make some changes. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +But you realize that it is not what you wanted. You **can undo** the changes +using the `/undo` command. + +```bash frame="none" +/undo +``` + +opencode will now revert the changes you made and show your original message +again. + +```txt frame="none" "@packages/functions/src/api/index.ts" +Can you refactor the function in @packages/functions/src/api/index.ts? +``` + +From here you can tweak the prompt and ask opencode to try again. + +:::tip +You can run `/undo` multiple times to undo multiple changes. +::: + +Or you **can redo** the changes using the `/redo` command. + +```bash frame="none" +/redo +``` + +--- + +## Share + +The conversations that you have with opencode can be [shared with your +team](/docs/share). + +```bash frame="none" +/share +``` + +This will create a link to the current conversation and copy it to your clipboard. + +:::note +Conversations are not shared by default. +::: + +Here's an [example conversation](https://opencode.ai/s/4XP1fce5) with opencode. + +--- + +## Customize + +And that's it! You are now a pro at using opencode. + +To make it your own, we recommend [picking a theme](/docs/themes), [customizing the keybinds](/docs/keybinds), [configuring code formatters](/docs/formatters), [creating custom commands](/docs/commands), or playing around with the [opencode config](/docs/config). diff --git a/packages/web/src/content/docs/keybinds.mdx b/packages/web/src/content/docs/keybinds.mdx new file mode 100644 index 000000000..6fd6148e1 --- /dev/null +++ b/packages/web/src/content/docs/keybinds.mdx @@ -0,0 +1,75 @@ +--- +title: Keybinds +description: Customize your keybinds. +--- + +opencode has a list of keybinds that you can customize through the opencode config. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "leader": "ctrl+x", + "app_help": "h", + "app_exit": "ctrl+c,q", + "editor_open": "e", + "theme_list": "t", + "project_init": "i", + "tool_details": "d", + "thinking_blocks": "b", + "session_export": "x", + "session_new": "n", + "session_list": "l", + "session_share": "s", + "session_unshare": "none", + "session_interrupt": "esc", + "session_compact": "c", + "session_child_cycle": "ctrl+right", + "session_child_cycle_reverse": "ctrl+left", + "messages_page_up": "pgup", + "messages_page_down": "pgdown", + "messages_half_page_up": "ctrl+alt+u", + "messages_half_page_down": "ctrl+alt+d", + "messages_first": "ctrl+g", + "messages_last": "ctrl+alt+g", + "messages_copy": "y", + "messages_undo": "u", + "messages_redo": "r", + "model_list": "m", + "model_cycle_recent": "f2", + "model_cycle_recent_reverse": "shift+f2", + "agent_list": "a", + "agent_cycle": "tab", + "agent_cycle_reverse": "shift+tab", + "input_clear": "ctrl+c", + "input_paste": "ctrl+v", + "input_submit": "enter", + "input_newline": "shift+enter,ctrl+j" + } +} +``` + +--- + +## Leader key + +opencode uses a `leader` key for most keybinds. This avoids conflicts in your terminal. + +By default, `ctrl+x` is the leader key and most actions require you to first press the leader key and then the shortcut. For example, to start a new session you first press `ctrl+x` and then press `n`. + +You don't need to use a leader key for your keybinds but we recommend doing so. + +--- + +## Disable keybind + +You can disable a keybind by adding the key to your config with a value of "none". + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "keybinds": { + "session_compact": "none" + } +} +``` diff --git a/packages/web/src/content/docs/lsp.mdx b/packages/web/src/content/docs/lsp.mdx new file mode 100644 index 000000000..6a661521c --- /dev/null +++ b/packages/web/src/content/docs/lsp.mdx @@ -0,0 +1,101 @@ +--- +title: LSP Servers +description: opencode integrates with your LSP servers. +--- + +opencode integrates with your Language Server Protocol (LSP) to help the LLM interacts with your codebase. It uses diagnostics to provide feedback to the LLM. And _go-to-definition_ and _find-references_ to help navigate your codebase. + +--- + +## Built-in + +opencode comes with several built-in LSP servers for popular languages: + +| LSP Server | Extensions | Requirements | +| ---------- | ---------------------------------------------------- | ----------------------------------- | +| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project | +| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts, .vue | `eslint` dependency in project | +| gopls | .go | `go` command available | +| ruby-lsp | .rb, .rake, .gemspec, .ru | `ruby` and `gem` commands available | +| pyright | .py, .pyi | `pyright` dependency installed | +| elixir-ls | .ex, .exs | `elixir` command available | +| zls | .zig, .zon | `zig` command available | +| csharp | .cs | `.NET SDK` installed | +| vue | .vue | Auto-installs for Vue projects | +| rust | .rs | `rust-analyzer` command available | +| clangd | .c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++ | Auto-installs for C/C++ projects | + +LSP servers are automatically enabled when one of the above file extensions are detected and the requirements are met. + +:::note +You can disable automatic LSP server downloads by setting the `OPENCODE_DISABLE_LSP_DOWNLOAD` environment variable to `true`. +::: + +--- + +## How It Works + +When opencode opens a file, it: + +1. Checks the file extension against all enabled LSP servers. +2. Starts the appropriate LSP server if not already running. + +--- + +## Configure + +You can customize LSP servers through the `lsp` section in your opencode config. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "lsp": {} +} +``` + +Each LSP server supports the following: + +| Property | Type | Description | +| ---------------- | -------- | ------------------------------------------------- | +| `disabled` | boolean | Set this to `true` to disable the LSP server | +| `command` | string[] | The command to start the LSP server | +| `extensions` | string[] | File extensions this LSP server should handle | +| `env` | object | Environment variables to set when starting server | +| `initialization` | object | Initialization options to send to the LSP server | + +Let's look at some examples. + +--- + +### Disabling LSP servers + +To disable a specific LSP server, set `disabled` to `true`: + +```json title="opencode.json" {5} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "typescript": { + "disabled": true + } + } +} +``` + +--- + +### Custom LSP servers + +You can add custom LSP servers by specifying the command and file extensions: + +```json title="opencode.json" {4-7} +{ + "$schema": "https://opencode.ai/config.json", + "lsp": { + "custom-lsp": { + "command": ["custom-lsp-server", "--stdio"], + "extensions": [".custom"] + } + } +} +``` diff --git a/packages/web/src/content/docs/mcp-servers.mdx b/packages/web/src/content/docs/mcp-servers.mdx new file mode 100644 index 000000000..0ceeb47a3 --- /dev/null +++ b/packages/web/src/content/docs/mcp-servers.mdx @@ -0,0 +1,128 @@ +--- +title: MCP servers +description: Add local and remote MCP tools. +--- + +You can add external tools to opencode using the _Model Context Protocol_, or MCP. opencode supports both: + +- Local servers +- And remote servers + +Once added, MCP tools are automatically available to the LLM alongside built-in tools. + +--- + +## Configure + +You can define MCP servers in your opencode config under `mcp`. + +--- + +### Local + +Add local MCP servers using `"type": "local"` within the MCP object. Multiple MCP servers can be added. The key string for each server can be any arbitrary name. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value" + } + }, + "my-different-local-mcp-server": { + "type": "local", + "command": ["bun", "x", "my-other-mcp-command"], + "enabled": true + } + } +} +``` + +You can also disable a server by setting `enabled` to `false`. This is useful if you want to temporarily disable a server without removing it from your config. + +--- + +### Remote + +Add remote MCP servers under `mcp` with `"type": "remote"`. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +Local and remote servers can be used together within the same `mcp` config object. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "my-local-mcp-server": { + "type": "local", + "command": ["bun", "x", "my-mcp-command"], + "enabled": true, + "environment": { + "MY_ENV_VAR": "my_env_var_value" + } + }, + "my-remote-mcp": { + "type": "remote", + "url": "https://my-mcp-server.com", + "enabled": true, + "headers": { + "Authorization": "Bearer MY_API_KEY" + } + } + } +} +``` + +--- + +## Per agent + +If you have a large number of MCP servers you may want to only enable them per +agent and disable them globally. To do this: + +1. Configure the MCP server. +2. Disable it as a tool globally. +3. In your [agent config](/docs/agents#tools) enable the MCP server as a tool. + +```json title="opencode.json" {11, 14-17} +{ + "$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 + } + } + } +} +``` diff --git a/packages/web/src/content/docs/models.mdx b/packages/web/src/content/docs/models.mdx new file mode 100644 index 000000000..efebc5cb4 --- /dev/null +++ b/packages/web/src/content/docs/models.mdx @@ -0,0 +1,128 @@ +--- +title: Models +description: Configuring an LLM provider and model. +--- + +opencode uses the [AI SDK](https://ai-sdk.dev/) and [Models.dev](https://models.dev) to support for **75+ LLM providers** and it supports running local models. + +--- + +## Providers + +Most popular providers are preloaded by default. If you've added the credentials for a provider through `opencode auth login`, they'll be available when you start opencode. + +Learn more about [providers](/docs/providers). + +--- + +## Select a model + +Once you've configured your provider you can select the model you want by typing in: + +```bash frame="none" +/models +``` + +--- + +## Recommended models + +There are a lot of models out there, with new models coming out every week. + +:::tip +Consider using one of the models we recommend. +::: + +However, there are a only a few of them that are good at both generating code and tool calling. + +Here are the ones we recommend with opencode: + +- Claude Sonnet 4 +- Claude Opus 4 +- Kimi K2 +- Qwen3 Coder +- GPT 4.1 +- Gemini 2.5 Pro + +--- + +## Set a default + +To set one of these as the default model, you can set the `model` key in your +opencode config. + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "model": "lmstudio/google/gemma-3n-e4b" +} +``` + +Here the full ID is `provider_id/model_id`. + +If you've configured a [custom provider](/docs/providers#custom), the `provider_id` is key from the `provider` part of your config, and the `model_id` is the key from `provider.models`. + +--- + +## Configure models + +You can globally configure a model's options through the config. + +```jsonc title="opencode.jsonc" {7-12,19-24} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "openai": { + "models": { + "gpt-5": { + "options": { + "reasoningEffort": "high", + "textVerbosity": "low", + "reasoningSummary": "auto", + "include": ["reasoning.encrypted_content"], + }, + }, + }, + }, + "anthropic": { + "models": { + "claude-sonnet-4-20250514": { + "options": { + "thinking": { + "type": "enabled", + "budgetTokens": 16000, + }, + }, + }, + }, + }, + }, +} +``` + +Here we're configuring global settings for two models: `gpt-5` when accessed via the `openai` provider, and `claude-sonnet-4-20250514` when accessed via the `anthropic` provider. + +You can also configure these options for any agents that you are using. The agent config overrides any global options here. [Learn more](/docs/agents/#additional). + +--- + +## Loading models + +When opencode starts up, it checks for models in the following priority order: + +1. The `--model` or `-m` command line flag. The format is the same as in the config file: `provider_id/model_id`. + +2. The model list in the opencode config. + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "model": "anthropic/claude-sonnet-4-20250514" + } + ``` + + The format here is `provider/model`. + +3. The last used model. + +4. The first model using an internal priority. diff --git a/packages/web/src/content/docs/modes.mdx b/packages/web/src/content/docs/modes.mdx new file mode 100644 index 000000000..ae14c2f32 --- /dev/null +++ b/packages/web/src/content/docs/modes.mdx @@ -0,0 +1,331 @@ +--- +title: Modes +description: Different modes for different use cases. +--- + +:::caution +Modes are now configured through the `agent` option in the opencode config. The +`mode` option is now deprecated. [Learn more](/docs/agents). +::: + +Modes in opencode allow you to customize the behavior, tools, and prompts for different use cases. + +It comes with two built-in modes: **build** and **plan**. You can customize +these or configure your own through the opencode config. + +You can switch between modes during a session or configure them in your config file. + +--- + +## Built-in + +opencode comes with two built-in modes. + +--- + +### Build + +Build is the **default** mode with all tools enabled. This is the standard mode for development work where you need full access to file operations and system commands. + +--- + +### Plan + +A restricted mode designed for planning and analysis. In plan mode, the following tools are disabled by default: + +- `write` - Cannot create new files +- `edit` - Cannot modify existing files +- `patch` - Cannot apply patches +- `bash` - Cannot execute shell commands + +This mode is useful when you want the AI to analyze code, suggest changes, or create plans without making any actual modifications to your codebase. + +--- + +## Switching + +You can switch between modes during a session using the _Tab_ key. Or your configured `switch_mode` keybind. + +See also: [Formatters](/docs/formatters) for information about code formatting configuration. + +--- + +## Configure + +You can customize the built-in modes or create your own through configuration. Modes can be configured in two ways: + +### JSON Configuration + +Configure modes in your `opencode.json` config file: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "build": { + "model": "anthropic/claude-sonnet-4-20250514", + "prompt": "{file:./prompts/build.txt}", + "tools": { + "write": true, + "edit": true, + "bash": true + } + }, + "plan": { + "model": "anthropic/claude-haiku-4-20250514", + "tools": { + "write": false, + "edit": false, + "bash": false + } + } + } +} +``` + +### Markdown Configuration + +You can also define modes using markdown files. Place them in: + +- Global: `~/.config/opencode/mode/` +- Project: `.opencode/mode/` + +```markdown title="~/.config/opencode/mode/review.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.1 +tools: + write: false + edit: false + bash: false +--- + +You are in code review mode. Focus on: + +- Code quality and best practices +- Potential bugs and edge cases +- Performance implications +- Security considerations + +Provide constructive feedback without making direct changes. +``` + +The markdown file name becomes the mode name (e.g., `review.md` creates a `review` mode). + +Let's look at these configuration options in detail. + +--- + +### Model + +Use the `model` config to override the default model for this mode. Useful for using different models optimized for different tasks. For example, a faster model for planning, a more capable model for implementation. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "model": "anthropic/claude-haiku-4-20250514" + } + } +} +``` + +--- + +### Temperature + +Control the randomness and creativity of the AI's responses with the `temperature` config. Lower values make responses more focused and deterministic, while higher values increase creativity and variability. + +```json title="opencode.json" +{ + "mode": { + "plan": { + "temperature": 0.1 + }, + "creative": { + "temperature": 0.8 + } + } +} +``` + +Temperature values typically range from 0.0 to 1.0: + +- **0.0-0.2**: Very focused and deterministic responses, ideal for code analysis and planning +- **0.3-0.5**: Balanced responses with some creativity, good for general development tasks +- **0.6-1.0**: More creative and varied responses, useful for brainstorming and exploration + +```json title="opencode.json" +{ + "mode": { + "analyze": { + "temperature": 0.1, + "prompt": "{file:./prompts/analysis.txt}" + }, + "build": { + "temperature": 0.3 + }, + "brainstorm": { + "temperature": 0.7, + "prompt": "{file:./prompts/creative.txt}" + } + } +} +``` + +If no temperature is specified, opencode uses model-specific defaults (typically 0 for most models, 0.55 for Qwen models). + +--- + +### Prompt + +Specify a custom system prompt file for this mode with the `prompt` config. The prompt file should contain instructions specific to the mode's purpose. + +```json title="opencode.json" +{ + "mode": { + "review": { + "prompt": "{file:./prompts/code-review.txt}" + } + } +} +``` + +This path is relative to where the config file is located. So this works for +both the global opencode config and the project specific config. + +--- + +### Tools + +Control which tools are available in this mode with the `tools` config. You can enable or disable specific tools by setting them to `true` or `false`. + +```json +{ + "mode": { + "readonly": { + "tools": { + "write": false, + "edit": false, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +If no tools are specified, all tools are enabled by default. + +--- + +#### Available tools + +Here are all the tools can be controlled through the mode config. + +| Tool | Description | +| ----------- | ----------------------- | +| `bash` | Execute shell commands | +| `edit` | Modify existing files | +| `write` | Create new files | +| `read` | Read file contents | +| `grep` | Search file contents | +| `glob` | Find files by pattern | +| `list` | List directory contents | +| `patch` | Apply patches to files | +| `todowrite` | Manage todo lists | +| `todoread` | Read todo lists | +| `webfetch` | Fetch web content | + +--- + +## Custom modes + +You can create your own custom modes by adding them to the configuration. Here are examples using both approaches: + +### Using JSON configuration + +```json title="opencode.json" {4-14} +{ + "$schema": "https://opencode.ai/config.json", + "mode": { + "docs": { + "prompt": "{file:./prompts/documentation.txt}", + "tools": { + "write": true, + "edit": true, + "bash": false, + "read": true, + "grep": true, + "glob": true + } + } + } +} +``` + +### Using markdown files + +Create mode files in `.opencode/mode/` for project-specific modes or `~/.config/opencode/mode/` for global modes: + +```markdown title=".opencode/mode/debug.md" +--- +temperature: 0.1 +tools: + bash: true + read: true + grep: true + write: false + edit: false +--- + +You are in debug mode. Your primary goal is to help investigate and diagnose issues. + +Focus on: + +- Understanding the problem through careful analysis +- Using bash commands to inspect system state +- Reading relevant files and logs +- Searching for patterns and anomalies +- Providing clear explanations of findings + +Do not make any changes to files. Only investigate and report. +``` + +```markdown title="~/.config/opencode/mode/refactor.md" +--- +model: anthropic/claude-sonnet-4-20250514 +temperature: 0.2 +tools: + edit: true + read: true + grep: true + glob: true +--- + +You are in refactoring mode. Focus on improving code quality without changing functionality. + +Priorities: + +- Improve code readability and maintainability +- Apply consistent naming conventions +- Reduce code duplication +- Optimize performance where appropriate +- Ensure all tests continue to pass +``` + +--- + +### Use cases + +Here are some common use cases for different modes. + +- **Build mode**: Full development work with all tools enabled +- **Plan mode**: Analysis and planning without making changes +- **Review mode**: Code review with read-only access plus documentation tools +- **Debug mode**: Focused on investigation with bash and read tools enabled +- **Docs mode**: Documentation writing with file operations but no system commands + +You might also find different models are good for different use cases. diff --git a/packages/web/src/content/docs/permissions.mdx b/packages/web/src/content/docs/permissions.mdx new file mode 100644 index 000000000..44dbc92ef --- /dev/null +++ b/packages/web/src/content/docs/permissions.mdx @@ -0,0 +1,115 @@ +--- +title: Permissions +description: Control what agents can do in your codebase. +--- + +By default, opencode **allows all operations** without requiring explicit approval. + +The permissions system provides granular control to restrict what actions AI agents can perform in your codebase, allowing you to configure explicit approval requirements for sensitive operations like file editing, bash commands, and more. + +--- + +## Configure + +Permissions are configured in your `opencode.json` file under the `permission` key. Here are the available options. + +### Tool Permission Support + +| Tool | Description | +| ---------- | ------------------------------- | +| `edit` | Control file editing operations | +| `bash` | Control bash command execution | +| `webfetch` | Control web content fetching | + +They can also be configured per agent, see [Agent Configuration](/docs/agents#agent-configuration) for more details. + +--- + +### edit + +Use the `permission.edit` key to control whether file editing operations require user approval. + +- `"ask"` - Prompt for approval before editing files +- `"allow"` - Allow all file editing operations without approval +- `"deny"` - Make all file editing tools disabled and unavailable + +```json title="opencode.json" {4} +{ + "$schema": "https://opencode.ai/config.json", + "permission": { + "edit": "ask" + } +} +``` + +--- + +### bash + +Controls whether bash commands require user approval. + +:::tip +You can specify which commands you want to have run without approval. +::: + +This can be configured globally or with specific patterns. Setting this to `"ask"`, requiring approval for all bash commands. +Setting this to `"deny"` is the strictest option, blocking LLM from running that command or command pattern. + +For example. + +- **Ask for approval for all commands** + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": "ask" + } + } + ``` + +- **Disable all Terraform commands** + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "terraform *": "deny" + } + } + } + ``` + +- **Approve specific commands** + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "git status": "allow", + "git diff": "allow", + "npm run build": "allow", + "ls": "allow", + "pwd": "allow" + } + } + } + ``` + +- **Use wildcard patterns to restrict specific commands** + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "permission": { + "bash": { + "git push": "ask", + "*": "allow" + } + } + } + ``` + + This configuration allows all commands by default (`"*": "allow"`) but requires approval for `git push` commands. diff --git a/packages/web/src/content/docs/plugins.mdx b/packages/web/src/content/docs/plugins.mdx new file mode 100644 index 000000000..071f1d427 --- /dev/null +++ b/packages/web/src/content/docs/plugins.mdx @@ -0,0 +1,105 @@ +--- +title: Plugins +description: Write your own plugins to extend opencode. +--- + +Plugins allow you to extend opencode by hooking into various events and customizing behavior. You can create plugins to add new features, integrate with external services, or modify opencode's default behavior. + +--- + +## Create a plugin + +A plugin is a **JavaScript/TypeScript module** that exports one or more plugin +functions. Each function receives a context object and returns a hooks object. + +--- + +### Location + +Plugins are loaded from: + +1. `.opencode/plugin` directory either in your project +2. Or, globally in `~/.config/opencode/plugin` + +--- + +### Basic structure + +```js title=".opencode/plugin/example.js" +export const MyPlugin = async ({ project, client, $, directory, worktree }) => { + console.log("Plugin initialized!") + + return { + // Hook implementations go here + } +} +``` + +The plugin function receives: + +- `project`: The current project information. +- `directory`: The current working directory. +- `worktree`: The git worktree path. +- `client`: An opencode SDK client for interacting with the AI. +- `$`: Bun's [shell API](https://bun.com/docs/runtime/shell) for executing commands. + +--- + +### TypeScript support + +For TypeScript plugins, you can import types from the plugin package: + +```ts title="my-plugin.ts" {1} +import type { Plugin } from "@opencode-ai/plugin" + +export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { + return { + // Type-safe hook implementations + } +} +``` + +--- + +## Examples + +Here are some examples of plugins you can use to extend opencode. + +--- + +### Send notifications + +Send notifications when certain events occur: + +```js title=".opencode/plugin/notification.js" +export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + // Send notification on session completion + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session completed!" with title "opencode"'` + } + }, + } +} +``` + +We are using `osascript` to run AppleScript on macOS. Here we are using it to send notifications. + +--- + +### .env protection + +Prevent opencode from reading `.env` files: + +```javascript title=".opencode/plugin/env-protection.js" +export const EnvProtection = async ({ project, client, $, directory, worktree }) => { + return { + "tool.execute.before": async (input, output) => { + if (input.tool === "read" && output.args.filePath.includes(".env")) { + throw new Error("Do not read .env files") + } + }, + } +} +``` diff --git a/packages/web/src/content/docs/providers.mdx b/packages/web/src/content/docs/providers.mdx new file mode 100644 index 000000000..c25a1c7d7 --- /dev/null +++ b/packages/web/src/content/docs/providers.mdx @@ -0,0 +1,887 @@ +--- +title: Providers +description: Using any LLM provider in opencode. +--- + +import config from "../../../config.mjs" +export const console = config.console + +opencode uses the [AI SDK](https://ai-sdk.dev/) and [Models.dev](https://models.dev) to support for **75+ LLM providers** and it supports running local models. + +To add a provider you need to: + +1. Add the API keys for the provider using `opencode auth login`. +2. Configure the provider in your opencode config. + +--- + +### Credentials + +When you add a provider's API keys with `opencode auth login`, they are stored +in `~/.local/share/opencode/auth.json`. + +--- + +### Config + +You can customize the providers through the `provider` section in your opencode +config. + +--- + +#### Base URL + +You can customize the base URL for any provider by setting the `baseURL` option. This is useful when using proxy services or custom endpoints. + +```json title="opencode.json" {6} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "anthropic": { + "options": { + "baseURL": "https://api.anthropic.com/v1" + } + } + } +} +``` + +--- + +## opencode zen + +opencode zen is a list of models provided by the opencode team that have been +tested and verified to work well with opencode. [Learn more](/docs/zen). + +:::tip +If you are new, we recommend starting with opencode zen. +::: + +1. You sign in to **opencode zen** and get your API key. +2. You run `opencode auth login` and select opencode zen and add your API key. +3. Run `/models` in the TUI to see the list of models we recommend. + +It works like any other provider in opencode. And is completely optional to use +it. + +--- + +## Directory + +Let's look at some of the providers in detail. If you'd like to add a provider to the +list, feel free to open a PR. + +:::note +Don't see a provider here? Submit a PR. +::: + +--- + +### Amazon Bedrock + +To use Amazon Bedrock with opencode: + +1. Head over to the **Model catalog** in the Amazon Bedrock console and request + access to the models you want. + + :::tip + You need to have access to the model you want in Amazon Bedrock. + ::: + +1. You'll need either to set one of the following environment variables: + + - `AWS_ACCESS_KEY_ID`: You can get this by creating an IAM user and generating + an access key for it. + - `AWS_PROFILE`: First login through AWS IAM Identity Center (or AWS SSO) using + `aws sso login`. Then get the name of the profile you want to use. + - `AWS_BEARER_TOKEN_BEDROCK`: You can generate a long-term API key from the + Amazon Bedrock console. + + Once you have one of the above, set it while running opencode. + + ```bash + AWS_ACCESS_KEY_ID=XXX opencode + ``` + + Or add it to a `.env` file in the project root. + + ```bash title=".env" + AWS_ACCESS_KEY_ID=XXX + ``` + + Or add it to your bash profile. + + ```bash title="~/.bash_profile" + export AWS_ACCESS_KEY_ID=XXX + ``` + +1. Run the `/models` command to select the model you want. + +--- + +### Anthropic + +We recommend signing up for [Claude Pro](https://www.anthropic.com/news/claude-pro) or [Max](https://www.anthropic.com/max), it's the most cost-effective way to use opencode. + +Once you've singed up, run `opencode auth login` and select Anthropic. + +```bash +$ opencode auth login + +┌ Add credential +│ +◆ Select provider +│ ● Anthropic (recommended) +│ ○ OpenAI +│ ○ Google +│ ... +└ +``` + +Here you can select the **Claude Pro/Max** option and it'll open your browser +and ask you to authenticate. + +```bash +$ opencode auth login +┌ Add credential +│ +◇ Select provider +│ Anthropic +│ +◆ Login method +│ ● Claude Pro/Max +│ ○ Create API Key +│ ○ Manually enter API Key +└ +``` + +Now all the the Anthropic models should be available when you use the `/models` command. + +##### Using API keys + +You can also select **Create API Key** if you don't have a Pro/Max subscription. It'll also open your browser and ask you to login to Anthropic and give you a code you can paste in your terminal. + +Or if you already have an API key, you can select **Manually enter API Key** and paste it in your terminal. + +--- + +### Azure OpenAI + +1. Head over to the [Azure portal](https://portal.azure.com/) and create an **Azure OpenAI** resource. You'll need: + + - **Resource name**: This becomes part of your API endpoint (`https://RESOURCE_NAME.openai.azure.com/`) + - **API key**: Either `KEY 1` or `KEY 2` from your resource + +2. Go to [Azure AI Foundry](https://ai.azure.com/) and deploy a model. + + :::note + The deployment name must match the model name for opencode to work properly. + ::: + +3. Run `opencode auth login` and select **Azure**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● Azure + │ ... + └ + ``` + +4. Enter your API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ Azure + │ + ◇ Enter your API key + │ _ + └ + ``` + +5. Set your resource name as an environment variable: + + ```bash + AZURE_RESOURCE_NAME=XXX opencode + ``` + + Or add it to a `.env` file in the project root: + + ```bash title=".env" + AZURE_RESOURCE_NAME=XXX + ``` + + Or add it to your bash profile: + + ```bash title="~/.bash_profile" + export AZURE_RESOURCE_NAME=XXX + ``` + +6. Run the `/models` command to select your deployed model. + +--- + +### Cerebras + +1. Head over to the [Cerebras console](https://inference.cerebras.ai/), create an account, and generate an API key. + +2. Run `opencode auth login` and select **Cerebras**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● Cerebras + │ ... + └ + ``` + +3. Enter your Cerebras API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ Cerebras + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select a model like _Qwen 3 Coder 480B_. + +--- + +### DeepSeek + +1. Head over to the [DeepSeek console](https://platform.deepseek.com/), create an account, and click **Create new API key**. + +2. Run `opencode auth login` and select **DeepSeek**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● DeepSeek + │ ... + └ + ``` + +3. Enter your DeepSeek API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ DeepSeek + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select a DeepSeek model like _DeepSeek Reasoner_. + +--- + +### Fireworks AI + +1. Head over to the [Fireworks AI console](https://app.fireworks.ai/), create an account, and click **Create API Key**. + +2. Run `opencode auth login` and select **Fireworks AI**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● Fireworks AI + │ ... + └ + ``` + +3. Enter your Fireworks AI API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ Fireworks AI + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select a model like _Kimi K2 Instruct_. + +--- + +### GitHub Copilot + +To use your GitHub Copilot subscription with opencode: + +:::note +Some models might need a [Pro+ +subscription](https://github.com/features/copilot/plans) to use. +::: + +1. Run `opencode auth login` and select GitHub Copilot. + + ```bash + $ opencode auth login + ┌ Add credential + + │ + ◇ Select provider + │ GitHub Copilot + │ + ◇ ──────────────────────────────────────────────╮ + │ │ + │ Please visit: https://github.com/login/device │ + │ Enter code: 8F43-6FCF │ + │ │ + ├─────────────────────────────────────────────────╯ + │ + ◓ Waiting for authorization... + ``` + +2. Navigate to [github.com/login/device](https://github.com/login/device) and enter the code. + +3. Now run the `/models` command to select the model you want. + +--- + +### Groq + +1. Head over to the [Groq console](https://console.groq.com/), click **Create API Key**, and copy the key. + +2. Run `opencode auth login` and select Groq. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● Groq + │ ... + └ + ``` + +3. Enter the API key for the provider. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ Groq + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select the one you want. + +--- + +### LM Studio + +You can configure opencode to use local models through LM Studio. + +```json title="opencode.json" "lmstudio" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "lmstudio": { + "npm": "@ai-sdk/openai-compatible", + "name": "LM Studio (local)", + "options": { + "baseURL": "http://127.0.0.1:1234/v1" + }, + "models": { + "google/gemma-3n-e4b": { + "name": "Gemma 3n-e4b (local)" + } + } + } + } +} +``` + +In this example: + +- `lmstudio` is the custom provider ID. This can be any string you want. +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` is the display name for the provider in the UI. +- `options.baseURL` is the endpoint for the local server. +- `models` is a map of model IDs to their configurations. The model name will be displayed in the model selection list. + +--- + +### Moonshot AI + +To use Kimi K2 from Moonshot AI: + +1. Head over to the [Moonshot AI console](https://platform.moonshot.ai/console), create an account, and click **Create API key**. + +2. Run `opencode auth login` and select **Moonshot AI**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Moonshot AI + └ + ``` + +3. Enter your Moonshot API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ Moonshot AI + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select _Kimi K2_. + +--- + +### Ollama + +You can configure opencode to use local models through Ollama. + +```json title="opencode.json" "ollama" {5, 6, 8, 10-14} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (local)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "llama2": { + "name": "Llama 2" + } + } + } + } +} +``` + +In this example: + +- `ollama` is the custom provider ID. This can be any string you want. +- `npm` specifies the package to use for this provider. Here, `@ai-sdk/openai-compatible` is used for any OpenAI-compatible API. +- `name` is the display name for the provider in the UI. +- `options.baseURL` is the endpoint for the local server. +- `models` is a map of model IDs to their configurations. The model name will be displayed in the model selection list. + +--- + +### OpenAI + +1. Head over to the [OpenAI Platform console](https://platform.openai.com/api-keys), click **Create new secret key**, and copy the key. + +2. Run `opencode auth login` and select OpenAI. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● OpenAI + │ ... + └ + ``` + +3. Enter the API key for the provider. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ OpenAI + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select the one you want. + +--- + +### opencode zen + +opencode zen is a list of tested and verified models provided by the opencode team. [Learn more](/docs/zen). + +1. Sign in to **opencode zen** and click **Create API Key**. + +2. Run `opencode auth login` and select **opencode zen**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● opencode zen + │ ... + └ + ``` + +3. Enter your opencode API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ opencode zen + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select a model like _Qwen 3 Coder 480B_. + +--- + +### OpenRouter + +1. Head over to the [OpenRouter dashboard](https://openrouter.ai/settings/keys), click **Create API Key**, and copy the key. + +2. Run `opencode auth login` and select OpenRouter. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● OpenRouter + │ ○ Anthropic + │ ○ Google + │ ... + └ + ``` + +3. Enter the API key for the provider. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ OpenRouter + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Many OpenRouter models are preloaded by default, run the `/models` command to select the one you want. + + You can also add additional models through your opencode config. + + ```json title="opencode.json" {6} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "somecoolnewmodel": {} + } + } + } + } + ``` + +5. You can also customize them through your opencode config. Here's an example of specifying a provider + + ```json title="opencode.json" + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "openrouter": { + "models": { + "moonshotai/kimi-k2": { + "options": { + "provider": { + "order": ["baseten"], + "allow_fallbacks": false + } + } + } + } + } + } + } + ``` + +--- + +### Together AI + +1. Head over to the [Together AI console](https://api.together.ai), create an account, and click **Add Key**. + +2. Run `opencode auth login` and select **Together AI**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● Together AI + │ ... + └ + ``` + +3. Enter your Together AI API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ Together AI + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select a model like _Kimi K2 Instruct_. + +--- + +### xAI + +For a limited time, you can use xAI's Grok Code for free with opencode. + +:::tip +Grok Code is available for free for a limited time on opencode. +::: + +1. Make sure you are on the latest version of opencode. + +2. Run the `/models` command and select **Grok Code Free**. + +As a part of the trial period, the xAI team will be using the request logs to +monitor and improve Grok Code. + +--- + +### Z.AI + +1. Head over to the [Z.AI API console](https://z.ai/manage-apikey/apikey-list), create an account, and click **Create a new API key**. + +2. Run `opencode auth login` and select **Z.AI**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ● Z.AI + │ ... + └ + ``` + +3. Enter your Z.AI API key. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Select provider + │ Z.AI + │ + ◇ Enter your API key + │ _ + └ + ``` + +4. Run the `/models` command to select a model like _GLM-4.5_. + +--- + +## Custom provider + +To add any **OpenAI-compatible** provider that's not listed in `opencode auth login`: + +:::tip +You can use any OpenAI-compatible provider with opencode. Most modern AI providers offer OpenAI-compatible APIs. +::: + +1. Run `opencode auth login` and scroll down to **Other**. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◆ Select provider + │ ... + │ ● Other + └ + ``` + +2. Enter a unique ID for the provider. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ◇ Enter provider id + │ myprovider + └ + ``` + + :::note + Choose a memorable ID, you'll use this in your config file. + ::: + +3. Enter your API key for the provider. + + ```bash + $ opencode auth login + + ┌ Add credential + │ + ▲ This only stores a credential for myprovider - you will need configure it in opencode.json, check the docs for examples. + │ + ◇ Enter your API key + │ sk-... + └ + ``` + +4. Create or update your `opencode.json` file in your project directory: + + ```json title="opencode.json" ""myprovider"" {5-15} + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1" + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } + } + ``` + + Here are the configuration options: + + - **npm**: AI SDK package to use, `@ai-sdk/openai-compatible` for OpenAI-compatible providers + - **name**: Display name in UI. + - **models**: Available models. + - **options.baseURL**: API endpoint URL. + - **options.apiKey**: Optionally set the API key, if not using auth. + - **options.headers**: Optionally set custom headers. + + More on the advanced options in the example below. + +5. Run the `/models` command and your custom provider and models will appear in the selection list. + +--- + +##### Example + +Here's an example setting the `apiKey` and `headers` options. + +```json title="opencode.json" {9,11} +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "name": "My AI ProviderDisplay Name", + "options": { + "baseURL": "https://api.myprovider.com/v1", + "apiKey": "{env:ANTHROPIC_API_KEY}", + "headers": { + "Authorization": "Bearer custom-token" + } + }, + "models": { + "my-model-name": { + "name": "My Model Display Name" + } + } + } + } +} +``` + +We are setting the `apiKey` using the `env` variable syntax, [learn more](/docs/config#env-vars). + +--- + +## Troubleshooting + +If you are having trouble with configuring a provider, check the following: + +1. **Check the auth setup**: Run `opencode auth list` to see if the credentials + for the provider are added to your config. + + This doesn't apply to providers like Amazon Bedrock, that rely on environment variables for their auth. + +2. For custom providers, check the opencode config and: + + - Make sure the provider ID used in `opencode auth login` matches the ID in your opencode config. + - The right npm package is used for the provider. For example, use `@ai-sdk/cerebras` for Cerebras. And for all other OpenAI-compatible providers, use `@ai-sdk/openai-compatible`. + - Check correct API endpoint is used in the `options.baseURL` field. diff --git a/packages/web/src/content/docs/rules.mdx b/packages/web/src/content/docs/rules.mdx new file mode 100644 index 000000000..aa5590bb5 --- /dev/null +++ b/packages/web/src/content/docs/rules.mdx @@ -0,0 +1,152 @@ +--- +title: Rules +description: Set custom instructions for opencode. +--- + +You can provide custom instructions to opencode by creating an `AGENTS.md` file. This is similar to `CLAUDE.md` or Cursor's rules. It contains instructions that will be included in the LLM's context to customize its behavior for your specific project. + +--- + +## Initialize + +To create a new `AGENTS.md` file, you can run the `/init` command in opencode. + +:::tip +You should commit your project's `AGENTS.md` file to Git. +::: + +This will scan your project and all its contents to understand what the project is about and generate an `AGENTS.md` file with it. This helps opencode to navigate the project better. + +If you have an existing `AGENTS.md` file, this will try to add to it. + +--- + +## Example + +You can also just create this file manually. Here's an example of some things you can put into an `AGENTS.md` file. + +```markdown title="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` +``` + +We are adding project-specific instructions here and this will be shared across your team. + +--- + +## Types + +opencode also supports reading the `AGENTS.md` file from multiple locations. And this serves different purposes. + +### Project + +The ones we have seen above, where the `AGENTS.md` is placed in the project root, are project-specific rules. These only apply when you are working in this directory or its sub-directories. + +### Global + +You can also have global rules in a `~/.config/opencode/AGENTS.md` file. This gets applied across all opencode sessions. + +Since this isn't committed to Git or shared with your team, we recommend using this to specify any personal rules that the LLM should follow. + +--- + +## Precedence + +So when opencode starts, it looks for: + +1. **Local files** by traversing up from the current directory +2. **Global file** by checking `~/.config/opencode/AGENTS.md` + +If you have both global and project-specific rules, opencode will combine them together. + +--- + +## Custom Instructions + +You can specify custom instruction files in your `opencode.json` or the global `~/.config/opencode/opencode.json`. This allows you and your team to reuse existing rules rather than having to duplicate them to AGENTS.md. + +Example: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] +} +``` + +All instruction files are combined with your `AGENTS.md` files. + +--- + +## Referencing External Files + +While opencode doesn't automatically parse file references in `AGENTS.md`, you can achieve similar functionality in two ways: + +### Using opencode.json + +The recommended approach is to use the `instructions` field in `opencode.json`: + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "instructions": ["docs/development-standards.md", "test/testing-guidelines.md", "packages/*/AGENTS.md"] +} +``` + +### Manual Instructions in AGENTS.md + +You can teach opencode to read external files by providing explicit instructions in your `AGENTS.md`. Here's a practical example: + +```markdown title="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.md +For React component architecture and hooks patterns: @docs/react-patterns.md +For REST API design and error handling: @docs/api-standards.md +For 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. +``` + +This approach allows you to: + +- Create modular, reusable rule files +- Share rules across projects via symlinks or git submodules +- Keep AGENTS.md concise while referencing detailed guidelines +- Ensure opencode loads files only when needed for the specific task + +:::tip +For monorepos or projects with shared standards, using `opencode.json` with glob patterns (like `packages/*/AGENTS.md`) is more maintainable than manual instructions. +::: diff --git a/packages/web/src/content/docs/sdk.mdx b/packages/web/src/content/docs/sdk.mdx new file mode 100644 index 000000000..1e65064f4 --- /dev/null +++ b/packages/web/src/content/docs/sdk.mdx @@ -0,0 +1,359 @@ +--- +title: SDK +description: Type-safe JS client for opencode server. +--- + +import config from "../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +The opencode JS/TS SDK provides a type-safe client for interacting with the server. +Use it to build integrations and control opencode programmatically. + +[Learn more](/docs/server) about how the server works. + +--- + +## Install + +Install the SDK from npm: + +```bash +npm install @opencode-ai/sdk +``` + +--- + +## Create client + +Create a client instance to connect to your server: + +```javascript +import { createOpencodeClient } from "@opencode-ai/sdk" + +const client = createOpencodeClient({ + baseUrl: "http://localhost:4096", + responseStyle: "data", +}) +``` + +#### Options + +| Option | Type | Description | Default | +| --------------- | ---------- | -------------------------------- | ----------------------- | +| `baseUrl` | `string` | URL of the server | `http://localhost:4096` | +| `fetch` | `function` | Custom fetch implementation | `globalThis.fetch` | +| `parseAs` | `string` | Response parsing method | `auto` | +| `responseStyle` | `string` | Return style: `data` or `fields` | `fields` | +| `throwOnError` | `boolean` | Throw errors instead of return | `false` | + +--- + +## Start server + +You can also programmatically start an opencode server: + +```javascript +import { createOpencodeServer } from "@opencode-ai/sdk" + +const server = await createOpencodeServer({ + hostname: "127.0.0.1", + port: 4096, +}) + +console.log(`Server running at ${server.url}`) + +server.close() +``` + +You can pass a configuration object to customize server behavior. The server still picks up your `opencode.json`, but you can override or add configuration inline: + +```javascript +import { createOpencodeServer } from "@opencode-ai/sdk" + +const server = await createOpencodeServer({ + hostname: "127.0.0.1", + port: 4096, + config: { + model: "anthropic/claude-3-5-sonnet-20241022", + }, +}) + +console.log(`Server running at ${server.url}`) + +server.close() +``` + +#### Options + +| Option | Type | Description | Default | +| ---------- | ------------- | ------------------------------ | ----------- | +| `hostname` | `string` | Server hostname | `127.0.0.1` | +| `port` | `number` | Server port | `4096` | +| `signal` | `AbortSignal` | Abort signal for cancellation | `undefined` | +| `timeout` | `number` | Timeout in ms for server start | `5000` | +| `config` | `Config` | Configuration object | `{}` | + +--- + +## Types + +The SDK includes TypeScript definitions for all API types. Import them directly: + +```typescript +import type { Session, Message, Part } from "@opencode-ai/sdk" +``` + +All types are generated from the server's OpenAPI specification and available in the types file. + +--- + +## Errors + +The SDK can throw errors that you can catch and handle: + +```typescript +try { + await client.session.get({ path: { id: "invalid-id" } }) +} catch (error) { + console.error("Failed to get session:", (error as Error).message) +} +``` + +--- + +## APIs + +The SDK exposes all server APIs through a type-safe client. + +--- + +### App + +| Method | Description | Response | +| -------------- | ------------------------- | ------------------------------------------- | +| `app.log()` | Write a log entry | `boolean` | +| `app.agents()` | List all available agents | Agent[] | + +--- + +#### Examples + +```javascript +// Write a log entry +await client.app.log({ + body: { + service: "my-app", + level: "info", + message: "Operation completed", + }, +}) + +// List available agents +const agents = await client.app.agents() +``` + +--- + +### Project + +| Method | Description | Response | +| ------------------- | ------------------- | --------------------------------------------- | +| `project.list()` | List all projects | Project[] | +| `project.current()` | Get current project | Project | + +--- + +#### Examples + +```javascript +// List all projects +const projects = await client.project.list() + +// Get current project +const currentProject = await client.project.current() +``` + +--- + +### Path + +| Method | Description | Response | +| ------------ | ---------------- | ---------------------------------------- | +| `path.get()` | Get current path | Path | + +--- + +#### Examples + +```javascript +// Get current path information +const pathInfo = await client.path.get() +``` + +--- + +### Config + +| Method | Description | Response | +| -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `config.get()` | Get config info | Config | +| `config.providers()` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +#### Examples + +```javascript +const config = await client.config.get() + +const { providers, default: defaults } = await client.config.providers() +``` + +--- + +### Sessions + +| Method | Description | Notes | +| ---------------------------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `session.list()` | List sessions | Returns Session[] | +| `session.get({ path })` | Get session | Returns Session | +| `session.children({ path })` | List child sessions | Returns Session[] | +| `session.create({ body })` | Create session | Returns Session | +| `session.delete({ path })` | Delete session | Returns `boolean` | +| `session.update({ path, body })` | Update session properties | Returns Session | +| `session.init({ path, body })` | Analyze app and create `AGENTS.md` | Returns `boolean` | +| `session.abort({ path })` | Abort a running session | Returns `boolean` | +| `session.share({ path })` | Share session | Returns Session | +| `session.unshare({ path })` | Unshare session | Returns Session | +| `session.summarize({ path, body })` | Summarize session | Returns `boolean` | +| `session.messages({ path })` | List messages in a session | Returns `{ info: `Message`, parts: `Part[]`}[]` | +| `session.message({ path })` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | +| `session.prompt({ path, body })` | Send prompt message | Returns `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.command({ path, body })` | Send command to session | Returns `{ info: `AssistantMessage`, parts: `Part[]`}` | +| `session.shell({ path, body })` | Run a shell command | Returns AssistantMessage | +| `session.revert({ path, body })` | Revert a message | Returns Session | +| `session.unrevert({ path })` | Restore reverted messages | Returns Session | +| `postSessionByIdPermissionsByPermissionId({ path, body })` | Respond to a permission request | Returns `boolean` | + +--- + +#### Examples + +```javascript +// Create and manage sessions +const session = await client.session.create({ + body: { title: "My session" }, +}) + +const sessions = await client.session.list() + +// Send a prompt message +const result = await client.session.prompt({ + path: { id: session.id }, + body: { + model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, + parts: [{ type: "text", text: "Hello!" }], + }, +}) +``` + +--- + +### Files + +| Method | Description | Response | +| ------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------- | +| `find.text({ query })` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `find.files({ query })` | Find files by name | `string[]` (file paths) | +| `find.symbols({ query })` | Find workspace symbols | Symbol[] | +| `file.read({ query })` | Read a file | `{ type: "raw" \| "patch", content: string }` | +| `file.status({ query? })` | Get status for tracked files | File[] | + +--- + +#### Examples + +```javascript +// Search and read files +const textResults = await client.find.text({ + query: { pattern: "function.*opencode" }, +}) + +const files = await client.find.files({ + query: { query: "*.ts" }, +}) + +const content = await client.file.read({ + query: { path: "src/index.ts" }, +}) +``` + +--- + +### TUI + +| Method | Description | Response | +| ------------------------------ | ------------------------- | --------- | +| `tui.appendPrompt({ body })` | Append text to the prompt | `boolean` | +| `tui.openHelp()` | Open the help dialog | `boolean` | +| `tui.openSessions()` | Open the session selector | `boolean` | +| `tui.openThemes()` | Open the theme selector | `boolean` | +| `tui.openModels()` | Open the model selector | `boolean` | +| `tui.submitPrompt()` | Submit the current prompt | `boolean` | +| `tui.clearPrompt()` | Clear the prompt | `boolean` | +| `tui.executeCommand({ body })` | Execute a command | `boolean` | +| `tui.showToast({ body })` | Show toast notification | `boolean` | + +--- + +#### Examples + +```javascript +// Control TUI interface +await client.tui.appendPrompt({ + body: { text: "Add this to prompt" }, +}) + +await client.tui.showToast({ + body: { message: "Task completed", variant: "success" }, +}) +``` + +--- + +### Auth + +| Method | Description | Response | +| ------------------- | ------------------------------ | --------- | +| `auth.set({ ... })` | Set authentication credentials | `boolean` | + +--- + +#### Examples + +```javascript +await client.auth.set({ + path: { id: "anthropic" }, + body: { type: "api", key: "your-api-key" }, +}) +``` + +--- + +### Events + +| Method | Description | Response | +| ------------------- | ------------------------- | ------------------------- | +| `event.subscribe()` | Server-sent events stream | Server-sent events stream | + +--- + +#### Examples + +```javascript +// Listen to real-time events +const events = await client.event.subscribe() +for await (const event of events.stream) { + console.log("Event:", event.type, event.properties) +} +``` diff --git a/packages/web/src/content/docs/server.mdx b/packages/web/src/content/docs/server.mdx new file mode 100644 index 000000000..0713cce65 --- /dev/null +++ b/packages/web/src/content/docs/server.mdx @@ -0,0 +1,180 @@ +--- +title: Server +description: Interact with opencode server over HTTP. +--- + +import config from "../../../config.mjs" +export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` + +The `opencode serve` command runs a headless HTTP server that exposes an OpenAPI endpoint that an opencode client can use. + +--- + +### Usage + +```bash +opencode serve [--port ] [--hostname ] +``` + +#### Options + +| Flag | Short | Description | Default | +| ------------ | ----- | --------------------- | ----------- | +| `--port` | `-p` | Port to listen on | `4096` | +| `--hostname` | `-h` | Hostname to listen on | `127.0.0.1` | + +--- + +### How it works + +When you run `opencode` it starts a TUI and a server. Where the TUI is the +client that talks to the server. The server exposes an OpenAPI 3.1 spec +endpoint. This endpoint is also used to generate an [SDK](/docs/sdk). + +:::tip +Use the opencode server to interact with opencode programmatically. +::: + +This architecture lets opencode support multiple clients and allows you to interact with opencode programmatically. + +You can run `opencode serve` to start a standalone server. If you have the +opencode TUI running, `opencode serve` will start a new server. + +--- + +#### Connect to an existing server + +When you start the TUI it randomly assigns a port and hostname. You can instead pass in the `--hostname` and `--port` [flags](/docs/cli). Then use this to connect to its server. + +The [`/tui`](#tui) endpoint can be used to drive the TUI through the server. For example, you can prefill or run a prompt. This setup is used by the opencode [IDE](/docs/ide) plugins. + +--- + +## Spec + +The server publishes an OpenAPI 3.1 spec that can be viewed at: + +``` +http://:/doc +``` + +For example, `http://localhost:4096/doc`. Use the spec to generate clients or inspect request and response types. Or view it in a Swagger explorer. + +--- + +## APIs + +The opencode server exposes the following APIs. + +--- + +### App + +| Method | Path | Description | Response | +| ------ | ----------- | ------------------ | --------------------------------------- | +| `GET` | `/app` | Get app info | App | +| `POST` | `/app/init` | Initialize the app | `boolean` | + +--- + +### Config + +| Method | Path | Description | Response | +| ------ | ------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `GET` | `/config` | Get config info | Config | +| `GET` | `/config/providers` | List providers and default models | `{ providers: `Provider[]`, default: { [key: string]: string } }` | + +--- + +### Sessions + +| Method | Path | Description | Notes | +| -------- | ---------------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET` | `/session` | List sessions | Returns Session[] | +| `GET` | `/session/:id` | Get session | Returns Session | +| `GET` | `/session/:id/children` | List child sessions | Returns Session[] | +| `POST` | `/session` | Create session | body: `{ parentID?, title? }`, returns Session | +| `DELETE` | `/session/:id` | Delete session | | +| `PATCH` | `/session/:id` | Update session properties | body: `{ title? }`, returns Session | +| `POST` | `/session/:id/init` | Analyze app and create `AGENTS.md` | body: `{ messageID, providerID, modelID }` | +| `POST` | `/session/:id/abort` | Abort a running session | | +| `POST` | `/session/:id/share` | Share session | Returns Session | +| `DELETE` | `/session/:id/share` | Unshare session | Returns Session | +| `POST` | `/session/:id/summarize` | Summarize session | | +| `GET` | `/session/:id/message` | List messages in a session | Returns `{ info: `Message`, parts: `Part[]`}[]` | +| `GET` | `/session/:id/message/:messageID` | Get message details | Returns `{ info: `Message`, parts: `Part[]`}` | +| `POST` | `/session/:id/message` | Send chat message | body matches [`ChatInput`](https://github.com/sst/opencode/blob/main/packages/opencode/src/session/index.ts#L358), returns Message | +| `POST` | `/session/:id/shell` | Run a shell command | body matches [`CommandInput`](https://github.com/sst/opencode/blob/main/packages/opencode/src/session/index.ts#L1007), returns Message | +| `POST` | `/session/:id/revert` | Revert a message | body: `{ messageID }` | +| `POST` | `/session/:id/unrevert` | Restore reverted messages | | +| `POST` | `/session/:id/permissions/:permissionID` | Respond to a permission request | body: `{ response }` | + +--- + +### Files + +| Method | Path | Description | Response | +| ------ | ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------- | +| `GET` | `/find?pattern=` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` | +| `GET` | `/find/file?query=` | Find files by name | `string[]` (file paths) | +| `GET` | `/find/symbol?query=` | Find workspace symbols | Symbol[] | +| `GET` | `/file?path=` | Read a file | `{ type: "raw" \| "patch", content: string }` | +| `GET` | `/file/status` | Get status for tracked files | File[] | + +--- + +### Logging + +| Method | Path | Description | Response | +| ------ | ------ | ------------------------------------------------------------ | --------- | +| `POST` | `/log` | Write log entry. Body: `{ service, level, message, extra? }` | `boolean` | + +--- + +### Agents + +| Method | Path | Description | Response | +| ------ | -------- | ------------------------- | ------------------------------------------- | +| `GET` | `/agent` | List all available agents | Agent[] | + +--- + +### TUI + +| Method | Path | Description | Response | +| ------ | ----------------------- | ------------------------------------------- | ---------------------- | +| `POST` | `/tui/append-prompt` | Append text to the prompt | `boolean` | +| `POST` | `/tui/open-help` | Open the help dialog | `boolean` | +| `POST` | `/tui/open-sessions` | Open the session selector | `boolean` | +| `POST` | `/tui/open-themes` | Open the theme selector | `boolean` | +| `POST` | `/tui/open-models` | Open the model selector | `boolean` | +| `POST` | `/tui/submit-prompt` | Submit the current prompt | `boolean` | +| `POST` | `/tui/clear-prompt` | Clear the prompt | `boolean` | +| `POST` | `/tui/execute-command` | Execute a command (`{ command }`) | `boolean` | +| `POST` | `/tui/show-toast` | Show toast (`{ title?, message, variant }`) | `boolean` | +| `GET` | `/tui/control/next` | Wait for the next control request | Control request object | +| `POST` | `/tui/control/response` | Respond to a control request (`{ body }`) | `boolean` | + +--- + +### Auth + +| Method | Path | Description | Response | +| ------ | ----------- | --------------------------------------------------------------- | --------- | +| `PUT` | `/auth/:id` | Set authentication credentials. Body must match provider schema | `boolean` | + +--- + +### Events + +| Method | Path | Description | Response | +| ------ | -------- | ----------------------------------------------------------------------------- | ------------------------- | +| `GET` | `/event` | Server-sent events stream. First event is `server.connected`, then bus events | Server-sent events stream | + +--- + +### Docs + +| Method | Path | Description | Response | +| ------ | ------ | -------------------------------------- | ------------------------------------------ | +| `GET` | `/doc` | OpenAPI 3.1 specification | HTML page with OpenAPI spec | diff --git a/packages/web/src/content/docs/share.mdx b/packages/web/src/content/docs/share.mdx new file mode 100644 index 000000000..efb54c2d5 --- /dev/null +++ b/packages/web/src/content/docs/share.mdx @@ -0,0 +1,128 @@ +--- +title: Share +description: Share your opencode conversations. +--- + +opencode's share feature allows you to create public links to your opencode conversations, so you can collaborate with teammates or get help from others. + +:::note +Shared conversations are publicly accessible to anyone with the link. +::: + +--- + +## How it works + +When you share a conversation, opencode: + +1. Creates a unique public URL for your session +2. Syncs your conversation history to our servers +3. Makes the conversation accessible via the shareable link — `opencode.ai/s/` + +--- + +## Sharing + +opencode supports three sharing modes that control how conversations are shared: + +--- + +### Manual (default) + +By default, opencode uses manual sharing mode. Sessions are not shared automatically, but you can manually share them using the `/share` command: + +``` +/share +``` + +This will generate a unique URL that'll be copied to your clipboard. + +To explicitly set manual mode in your [config file](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "manual" +} +``` + +--- + +### Auto-share + +You can enable automatic sharing for all new conversations by setting the `share` option to `"auto"` in your [config file](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "auto" +} +``` + +With auto-share enabled, every new conversation will automatically be shared and a link will be generated. + +--- + +### Disabled + +You can disable sharing entirely by setting the `share` option to `"disabled"` in your [config file](/docs/config): + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "share": "disabled" +} +``` + +To enforce this across your team for a given project, add it to the `opencode.json` in your project and check into Git. + +--- + +## Un-sharing + +To stop sharing a conversation and remove it from public access: + +``` +/unshare +``` + +This will remove the share link and delete the data related to the conversation. + +--- + +## Privacy + +There are a few things to keep in mind when sharing a conversation. + +--- + +### Data retention + +Shared conversations remain accessible until you explicitly unshare them. This +includes: + +- Full conversation history +- All messages and responses +- Session metadata + +--- + +### Recommendations + +- Only share conversations that don't contain sensitive information. +- Review conversation content before sharing. +- Unshare conversations when collaboration is complete. +- Avoid sharing conversations with proprietary code or confidential data. +- For sensitive projects, disable sharing entirely. + +--- + +## For enterprises + +For enterprise deployments, the share feature can be: + +- **Disabled** entirely for security compliance +- **Restricted** to users authenticated through SSO only +- **Self-hosted** on your own infrastructure + +[Learn more](/docs/enterprise) about using opencode in your organization. diff --git a/packages/web/src/content/docs/themes.mdx b/packages/web/src/content/docs/themes.mdx new file mode 100644 index 000000000..3defceaea --- /dev/null +++ b/packages/web/src/content/docs/themes.mdx @@ -0,0 +1,368 @@ +--- +title: Themes +description: Select a built-in theme or define your own. +--- + +With opencode you can select from one of several built-in themes, use a theme that adapts to your terminal theme, or define your own custom theme. + +By default, opencode uses our own `opencode` theme. + +--- + +## Terminal requirements + +For themes to display correctly with their full color palette, your terminal must support **truecolor** (24-bit color). Most modern terminals support this by default, but you may need to enable it: + +- **Check support**: Run `echo $COLORTERM` - it should output `truecolor` or `24bit` +- **Enable truecolor**: Set the environment variable `COLORTERM=truecolor` in your shell profile +- **Terminal compatibility**: Ensure your terminal emulator supports 24-bit color (most modern terminals like iTerm2, Alacritty, Kitty, Windows Terminal, and recent versions of GNOME Terminal do) + +Without truecolor support, themes may appear with reduced color accuracy or fall back to the nearest 256-color approximation. + +--- + +## Built-in themes + +opencode comes with several built-in themes. + +| Name | Description | +| ------------ | ------------------------------------------ | +| `system` | Adapts to your terminal's background color | +| `tokyonight` | Based on the Tokyonight theme | +| `everforest` | Based on the Everforest theme | +| `ayu` | Based on the Ayu dark theme | +| `catppuccin` | Based on the Catppuccin theme | +| `gruvbox` | Based on the Gruvbox theme | +| `kanagawa` | Based on the Kanagawa theme | +| `nord` | Based on the Nord theme | +| `matrix` | Hacker-style green on black theme | +| `one-dark` | Based on the Atom One Dark theme | + +And more, we are constantly adding new themes. + +--- + +## System theme + +The `system` theme is designed to automatically adapt to your terminal's color scheme. Unlike traditional themes that use fixed colors, the _system_ theme: + +- **Generates gray scale**: Creates a custom gray scale based on your terminal's background color, ensuring optimal contrast. +- **Uses ANSI colors**: Leverages standard ANSI colors (0-15) for syntax highlighting and UI elements, which respect your terminal's color palette. +- **Preserves terminal defaults**: Uses `none` for text and background colors to maintain your terminal's native appearance. + +The system theme is for users who: + +- Want opencode to match their terminal's appearance +- Use custom terminal color schemes +- Prefer a consistent look across all terminal applications + +--- + +## Using a theme + +You can select a theme by bringing up the theme select with the `/theme` command. Or you can specify it in your [config](/docs/config). + +```json title="opencode.json" {3} +{ + "$schema": "https://opencode.ai/config.json", + "theme": "tokyonight" +} +``` + +--- + +## Custom themes + +opencode supports a flexible JSON-based theme system that allows users to create and customize themes easily. + +--- + +### Hierarchy + +Themes are loaded from multiple directories in the following order where later directories override earlier ones: + +1. **Built-in themes** - These are embedded in the binary +2. **User config directory** - Defined in `~/.config/opencode/themes/*.json` or `$XDG_CONFIG_HOME/opencode/themes/*.json` +3. **Project root directory** - Defined in the `/.opencode/themes/*.json` +4. **Current working directory** - Defined in `./.opencode/themes/*.json` + +If multiple directories contain a theme with the same name, the theme from the directory with higher priority will be used. + +--- + +### Creating a theme + +To create a custom theme, create a JSON file in one of the theme directories. + +For user-wide themes: + +```bash no-frame +mkdir -p ~/.config/opencode/themes +vim ~/.config/opencode/themes/my-theme.json +``` + +And for project-specific themes. + +```bash no-frame +mkdir -p .opencode/themes +vim .opencode/themes/my-theme.json +``` + +--- + +### JSON format + +Themes use a flexible JSON format with support for: + +- **Hex colors**: `"#ffffff"` +- **ANSI colors**: `3` (0-255) +- **Color references**: `"primary"` or custom definitions +- **Dark/light variants**: `{"dark": "#000", "light": "#fff"}` +- **No color**: `"none"` - Uses the terminal's default color or transparent + +--- + +### Color definitions + +The `defs` section is optional and it allows you to define reusable colors that can be referenced in the theme. + +--- + +### Terminal defaults + +The special value `"none"` can be used for any color to inherit the terminal's default color. This is particularly useful for creating themes that blend seamlessly with your terminal's color scheme: + +- `"text": "none"` - Uses terminal's default foreground color +- `"background": "none"` - Uses terminal's default background color + +--- + +### Example + +Here's an example of a custom theme: + +```json title="my-theme.json" +{ + "$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" + } + } +} +``` diff --git a/packages/web/src/content/docs/troubleshooting.mdx b/packages/web/src/content/docs/troubleshooting.mdx new file mode 100644 index 000000000..b846bed2d --- /dev/null +++ b/packages/web/src/content/docs/troubleshooting.mdx @@ -0,0 +1,156 @@ +--- +title: Troubleshooting +description: Common issues and how to resolve them. +--- + +To debug any issues with opencode, you can check the logs or the session data +that it stores locally. + +--- + +### Logs + +Log files are written to: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: `%APPDATA%\opencode\log\` + +Log files are named with timestamps (e.g., `2025-01-09T123456.log`) and the most recent 10 log files are kept. + +You can set the log level with the `--log-level` command-line option to get more detailed debug information. For example, `opencode --log-level DEBUG`. + +--- + +### Storage + +opencode stores session data and other application data on disk at: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: `%USERPROFILE%\.local\share\opencode` + +This directory contains: + +- `auth.json` - Authentication data like API keys, OAuth tokens +- `log/` - Application logs +- `project/` - Project-specific data like session and message data + - If the project is within a Git repo, it is stored in `.//storage/` + - If it is not a Git repo, it is stored in `./global/storage/` + +--- + +## Getting help + +If you're experiencing issues with opencode: + +1. **Report issues on GitHub** + + The best way to report bugs or request features is through our GitHub repository: + + [**github.com/sst/opencode/issues**](https://github.com/sst/opencode/issues) + + Before creating a new issue, search existing issues to see if your problem has already been reported. + +2. **Join our Discord** + + For real-time help and community discussion, join our Discord server: + + [**opencode.ai/discord**](https://opencode.ai/discord) + +--- + +## Common issues + +Here are some common issues and how to resolve them. + +--- + +### opencode won't start + +1. Check the logs for error messages +2. Try running with `--print-logs` to see output in the terminal +3. Ensure you have the latest version with `opencode upgrade` + +--- + +### Authentication issues + +1. Try re-authenticating with `opencode auth login ` +2. Check that your API keys are valid +3. Ensure your network allows connections to the provider's API + +--- + +### Model not available + +1. Check that you've authenticated with the provider +2. Verify the model name in your config is correct +3. Some models may require specific access or subscriptions + +--- + +### ProviderInitError + +If you encounter a ProviderInitError, you likely have an invalid or corrupted configuration. + +To resolve this: + +1. First, verify your provider is set up correctly by following the [providers guide](/docs/providers) +2. If the issue persists, try clearing your stored configuration: + + ```bash + rm -rf ~/.local/share/opencode + ``` + +3. Re-authenticate with your provider: + ```bash + opencode auth login + ``` + +--- + +### AI_APICallError and provider package issues + +If you encounter API call errors, this may be due to outdated provider packages. opencode dynamically installs provider packages (OpenAI, Anthropic, Google, etc.) as needed and caches them locally. + +To resolve provider package issues: + +1. Clear the provider package cache: + + ```bash + rm -rf ~/.cache/opencode + ``` + +2. Restart opencode to reinstall the latest provider packages + +This will force opencode to download the most recent versions of provider packages, which often resolves compatibility issues with model parameters and API changes. + +--- + +### Copy/paste not working on Linux + +Linux users need to have one of the following clipboard utilities installed for copy/paste functionality to work: + +**For X11 systems:** + +```bash +apt install -y xclip +# or +apt install -y xsel +``` + +**For Wayland systems:** + +```bash +apt install -y wl-clipboard +``` + +**For headless environments:** + +```bash +apt install -y xvfb +# and run: +Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +export DISPLAY=:99.0 +``` + +opencode will detect if you're using Wayland and prefer `wl-clipboard`, otherwise it will try to find clipboard tools in order of: `xclip` and `xsel`. diff --git a/packages/web/src/content/docs/tui.mdx b/packages/web/src/content/docs/tui.mdx new file mode 100644 index 000000000..113bad697 --- /dev/null +++ b/packages/web/src/content/docs/tui.mdx @@ -0,0 +1,315 @@ +--- +title: TUI +description: Using the opencode terminal user interface. +--- + +import { Tabs, TabItem } from "@astrojs/starlight/components" + +opencode provides an interactive terminal interface or TUI for working on your projects with an LLM. + +Running opencode starts the TUI for the current directory. + +```bash +opencode +``` + +Or you can start it for a specific working directory. + +```bash +opencode /path/to/project +``` + +Once you're in the TUI, you can prompt it with a message. + +```text +Give me a quick summary of the codebase. +``` + +--- + +## File references + +You can reference files in your messages using `@`. This does a fuzzy file search in the current working directory. + +:::tip +You can also use `@` to reference files in your messages. +::: + +```text "@packages/functions/src/api/index.ts" +How is auth handled in @packages/functions/src/api/index.ts? +``` + +The content of the file is added to the conversation automatically. + +--- + +## Bash commands + +Start a message with `!` to run a shell command. + +```bash frame="none" +!ls -la +``` + +The output of the command is added to the conversation as a tool result. + +--- + +## Commands + +When using the opencode TUI, you can type `/` followed by a command name to quickly execute actions. For example: + +```bash frame="none" +/help +``` + +Most commands also have keybind using `ctrl+x` as the leader key, where `ctrl+x` is the default leader key. [Learn more](/docs/keybinds). + +Here are all available slash commands: + +--- + +### compact + +Compact the current session. _Alias_: `/summarize` + +```bash frame="none" +/compact +``` + +**Keybind:** `ctrl+x c` + +--- + +### details + +Toggle tool execution details. + +```bash frame="none" +/details +``` + +**Keybind:** `ctrl+x d` + +--- + +### editor + +Open external editor for composing messages. Uses the editor set in your `EDITOR` environment variable. [Learn more](#editor-setup). + +```bash frame="none" +/editor +``` + +**Keybind:** `ctrl+x e` + +--- + +### exit + +Exit opencode. _Aliases_: `/quit`, `/q` + +```bash frame="none" +/exit +``` + +**Keybind:** `ctrl+x q` + +--- + +### export + +Export current conversation to Markdown and open in your default editor. Uses the editor set in your `EDITOR` environment variable. [Learn more](#editor-setup). + +```bash frame="none" +/export +``` + +**Keybind:** `ctrl+x x` + +--- + +### help + +Show the help dialog. + +```bash frame="none" +/help +``` + +**Keybind:** `ctrl+x h` + +--- + +### init + +Create or update `AGENTS.md` file. [Learn more](/docs/rules). + +```bash frame="none" +/init +``` + +**Keybind:** `ctrl+x i` + +--- + +### models + +List available models. + +```bash frame="none" +/models +``` + +**Keybind:** `ctrl+x m` + +--- + +### new + +Start a new session. _Alias_: `/clear` + +```bash frame="none" +/new +``` + +**Keybind:** `ctrl+x n` + +--- + +### redo + +Redo a previously undone message. Only available after using `/undo`. + +:::tip +Any file changes will also be restored. +::: + +```bash frame="none" +/redo +``` + +**Keybind:** `ctrl+x r` + +--- + +### sessions + +List and switch between sessions. _Aliases_: `/resume`, `/continue` + +```bash frame="none" +/sessions +``` + +**Keybind:** `ctrl+x l` + +--- + +### share + +Share current session. [Learn more](/docs/share). + +```bash frame="none" +/share +``` + +**Keybind:** `ctrl+x s` + +--- + +### themes + +List available themes. + +```bash frame="none" +/themes +``` + +**Keybind:** `ctrl+x t` + +--- + +### undo + +Undo last message in the conversation. Removes the most recent user message, all subsequent responses, and any file changes. + +:::tip +Any file changes made will also be reverted. +::: + +```bash frame="none" +/undo +``` + +**Keybind:** `ctrl+x u` + +--- + +### unshare + +Unshare current session. [Learn more](/docs/share#un-sharing). + +```bash frame="none" +/unshare +``` + +--- + +## Editor setup + +Both the `/editor` and `/export` commands use the editor specified in your `EDITOR` environment variable. + + + + ```bash + # Example for nano or vim + export EDITOR=nano + export EDITOR=vim + + # For GUI editors (VS Code, Cursor, VSCodium, Windsurf, Zed, etc.) include --wait + export EDITOR="code --wait" + ``` + + To make it permanent, add this to your shell profile; + `~/.bashrc`, `~/.zshrc`, etc. + + + + ```bash + set EDITOR=notepad + + # For GUI editors (VS Code, Cursor, VSCodium, Windsurf, Zed, etc.) include --wait + set EDITOR=code --wait + ``` + + To make it permanent, use **System Properties** > **Environment + Variables**. + + + + ```powershell + $env:EDITOR = "notepad" + + # For GUI editors (VS Code, Cursor, VSCodium, Windsurf, Zed, etc.) include --wait + $env:EDITOR = "code --wait" + ``` + + To make it permanent, add this to your PowerShell profile. + + + +Popular editor options include: + +- `code` - Visual Studio Code +- `cursor` - Cursor +- `windsurf` - Windsurf +- `vim` - Vim editor +- `nano` - Nano editor +- `notepad` - Windows Notepad +- `subl` - Sublime Text + +:::note +Some editors like VS Code need to be started with the `--wait` flag. +::: + +Some editors need command-line arguments to run in blocking mode. The `--wait` flag makes the editor process block until closed. diff --git a/packages/web/src/content/docs/zen.mdx b/packages/web/src/content/docs/zen.mdx new file mode 100644 index 000000000..b3de59021 --- /dev/null +++ b/packages/web/src/content/docs/zen.mdx @@ -0,0 +1,95 @@ +--- +title: Zen +description: Curated list of models provided by opencode. +--- + +import config from "../../../config.mjs" +export const console = config.console +export const email = `mailto:${config.email}` + +opencode zen is a list of tested and verified models provided by the opencode team. + +:::note +opencode zen is currently in beta. +::: + +Zen works like any other provider in opencode. You login to opencode zen and get +your API key. It's **completely optional** and you don't need to use it to use +opencode. + +--- + +## Background + +There are a large number of models out there but only a few of +these models work well as coding agents. Additionally, most providers are +configured very differently; so you get very different performance and quality. + +:::tip +We tested a select group of models and providers that work well with opencode. +::: + +So if you are using a model through something like OpenRouter, you can never be +sure if you are getting the best version of the model you want. + +To fix this, we did a couple of things: + +1. We tested a select group of models and talked to their teams about how to + best run them. +2. We then worked with a few providers to make sure these were being served + correctly. +3. Finally, we benchmarked the combination of the model/provider and came up + with a list that we feel good recommending. + +opencode zen is an AI gateway that gives you access to these models. + +--- + +## Motivation + +We created opencode zen to: + +1. **Benchmark** the best models/providers for coding agents. +2. Access to **highest quality**; we don't downgrade performance or route to cheaper providers. +3. **Sell at cost**; the only markup is to cover our processing fees and any price + drops will be passed along. +4. **No lock-in**; you can use opencode zen with any other coding agent and you + can use any other provider with opencode. + +--- + +## How it works + +opencode zen works like any other provider in opencode. + +1. You sign in to **opencode zen** and get your API key. +2. You run `opencode auth login` and select opencode zen and add your API key. +3. Run `/models` in the TUI to see the list of models we recommend. + +You are charged per request and you can add credits to your account. + +--- + +## Pricing + +Below are the models that we currently support and their prices **per 1M +tokens**. + +| Model | Input | Output | +| ----- | ----- | ------ | +| Qwen3 Coder 480B | $0.38 | $0.50 | +| Grok Code Fast 1 | Free | Free | +| Sonnet 4 | Soon | Soon | + +:::note +We add a small markup to cover our costs. +::: + +A couple of notes: + +- These are the raw prices based on the provider we are using internally. We +charge a small markup on top of this to cover our processing fees. +- Grok Code Fast 1 is currently free on opencode till Sep 10th. The xAI team is + using this time to collect feedback and improve Grok Code. + +Contact us if you have any questions. -- cgit v1.2.3