# OpenCode Setup Guide

This document has two parts:

1. **Part I — Cursor Agent Prompt** — copy into Cursor to implement the setup automatically
2. **Part II — Setup Tutorial** — manual reference with every file, config, and step

Attach this entire file to Cursor and paste the prompt from Part I.

---

# Part I — Cursor Agent Prompt

## How to use

1. Attach this file (`opencode_setup.md`) to your Cursor chat
2. Copy the **full prompt** or **short prompt** below and paste it
3. The agent will follow **Part II** as the source of truth for what to create

---

## Full prompt (copy from here)

```
You are setting up OpenCode globally on this machine. Follow the attached tutorial (Part II of `opencode_setup.md`) as the single source of truth. Do not improvise a different structure.

## Goal

Implement the full global OpenCode configuration:
- Rules layer: `AGENTS.md` + `instructions` pointing to this workspace's `.cursor/rules/`
- Agents layer: customized `build`, `plan`, `explore`, and five subagents with prompt files
- Environment layer: `.env` model vars + shell profile sourcing for `{env:VAR}` substitution

Model priority (strict order): Groq → Mistral → OpenCode (`small_model`) → Anthropic.

## Before you write any files

1. Check OpenCode is installed: `which opencode` and `opencode --version` (or equivalent)
2. Discover this workspace's absolute path and list `.cursor/rules/` — only include rule files that actually exist in `instructions`
3. Detect the user's shell profile (`~/.zshrc` or `~/.bashrc`)
4. Check whether `~/.config/opencode/` already exists and what is already configured — merge/update, do not blindly overwrite user customizations without noting what changed
5. Run `opencode models` (with any existing API keys in the environment) to list valid `provider/model-id` values

## Files to create or update

### Global OpenCode config (`~/.config/opencode/`)

| File | Action |
|------|--------|
| `opencode.jsonc` | Create or update per tutorial Step 5 |
| `AGENTS.md` | Create or update per tutorial Step 3 |
| `prompts/build.txt` | Create |
| `prompts/plan.txt` | Create |
| `prompts/explore.txt` | Create |
| `prompts/code-reviewer.txt` | Create |
| `prompts/security-auditor.txt` | Create |
| `prompts/supabase.txt` | Create |
| `prompts/ui-builder.txt` | Create |
| `prompts/wiki-docs.txt` | Create |

Use `{file:./prompts/...}` paths in `opencode.jsonc` (relative to config dir).

### Environment

| File | Action |
|------|--------|
| `.env` | Create or update in the workspace root (or user-preferred location outside git) |
| Shell profile | Add OpenCode to PATH and source `.env` with `set -a` / `set +a` |
| `~/.config/opencode/.env` | Optional symlink to the main `.env` |

### `.env` variables (required)

```
ANTHROPIC_API_KEY=
ANTHROPIC_DEFAULT_MODEL=

GROQ_API_KEY=
GROQ_DEFAULT_MODEL=

MISTRAL_API_KEY=
MISTRAL_DEFAULT_MODEL=

OPENCODE_DEFAULT_MODEL=
```

- If the user already has API keys in an existing `.env`, preserve them — only add missing vars
- If keys are missing, use empty values or `your-*-key` placeholders and tell the user to fill them in
- Model IDs must be exact matches from `opencode models` output, in `provider/model-id` format
- Never commit `.env` or print API keys in your response

### `opencode.jsonc` requirements

- `"model": "{env:GROQ_DEFAULT_MODEL}"`
- `"small_model": "{env:OPENCODE_DEFAULT_MODEL}"`
- `"enabled_providers": ["groq", "mistral", "opencode", "anthropic"]` (omit providers the user does not use)
- `"instructions"`: absolute paths to existing files in `<workspace>/.cursor/rules/`
- `"agent"` block: all agents from the tutorial with correct `mode`, `model`, `temperature`, `permission`, and `prompt`

### Agent model assignment (from tutorial)

| Agent | Model env var |
|-------|---------------|
| build (primary) | `GROQ_DEFAULT_MODEL` |
| plan (primary) | `MISTRAL_DEFAULT_MODEL` |
| explore | default (inherits) |
| code-reviewer | `ANTHROPIC_DEFAULT_MODEL` |
| security-auditor | `ANTHROPIC_DEFAULT_MODEL` |
| supabase | `GROQ_DEFAULT_MODEL` |
| ui-builder | `GROQ_DEFAULT_MODEL` |
| wiki-docs | `MISTRAL_DEFAULT_MODEL` |

### Permissions (do not skip)

- **build**: `git push*` and `git commit*` → `ask`; `security-auditor` task → `ask`
- **plan**: `edit: deny`, `bash: deny`
- **code-reviewer**: `edit: deny`, `bash: deny`
- **security-auditor**: `edit: deny`; bash allow only `git diff*`, `git log*`, `grep *`
- **supabase**: bash `ask` except `npx supabase gen types*`, `grep *`
- **ui-builder**: bash `ask` except `npx shadcn@latest add*`, `npm run typecheck*`
- **wiki-docs**: `bash: deny`

## Adapt to this workspace

- Replace tutorial placeholders (`PATH_TO_YOUR_PROJECT`) with the actual workspace path
- In `instructions`, include only `.cursor/rules/` files that exist — skip missing ones
- If `.cursor/rules/` is empty or missing, create a minimal `AGENTS.md` and omit `instructions` until rules exist
- If the project has no `.wiki/` workflow, keep wiki sections in prompts but note they are optional

## Verification (run before finishing)

1. Confirm all 8 prompt files exist under `~/.config/opencode/prompts/`
2. Confirm `opencode.jsonc` is valid JSONC (schema, no trailing issues)
3. With env sourced, verify each model var appears in `opencode models` output
4. Confirm shell profile sources the `.env` file
5. Do not start a long-running `opencode` session — just verify config and models

## Output format

When done, respond with:

1. **Created/updated** — list of files with one-line description each
2. **Model mapping** — table of env var → chosen model ID (no API keys)
3. **Manual steps** — what the user must do (fill keys, open new terminal, restart OpenCode)
4. **Usage** — how to switch Build/Plan (Tab), invoke subagents (@name)
5. **Skipped** — anything you could not do and why

## Constraints

- Do not commit changes unless the user explicitly asks
- Do not expose API keys, tokens, or absolute home directory paths in your summary (use `~` shorthand)
- Do not edit `.wiki/` files
- Follow the tutorial's rules-vs-agents separation: conventions in `instructions`, role behavior in `prompts/`
- Minimize scope — only files required for this OpenCode setup
```

---

## Short prompt (minimal)

```
Read the attached `opencode_setup.md` (Part II) and implement the complete global OpenCode setup on my machine.

Discover `.cursor/rules/` in this workspace, verify model IDs via `opencode models`, create `~/.config/opencode/` (config + AGENTS.md + 8 prompts), update `.env` and my shell profile. Model priority: Groq → Mistral → OpenCode → Anthropic. Preserve existing API keys. Do not commit secrets. Summarize what was created and what I must do manually.
```

---

## Tips for best results

1. **Attach this file** — the agent needs Part II in context
2. **Open the workspace** that contains `.cursor/rules/` so paths resolve correctly
3. **Have API keys ready** — or let the agent use placeholders and fill them in after
4. **New terminal** — env vars only load after sourcing the shell profile

---
---
---

# Part II — Setup Tutorial

A step-by-step guide to configure [OpenCode](https://opencode.ai) with global rules, custom agents, model routing via environment variables, and integration with existing Cursor rules.

**Official docs referenced:**
- [Rules](https://opencode.ai/docs/rules/)
- [Agents](https://opencode.ai/docs/agents/)
- [Config](https://opencode.ai/docs/config/)

---

## What this setup provides

| Layer | Purpose |
|-------|---------|
| **Rules** (`AGENTS.md` + `instructions`) | What the model knows — conventions, session rituals, project standards |
| **Agents** (`agent` block + prompt files) | How the model behaves — roles, permissions, per-task models |
| **Environment** (`.env` + shell profile) | API keys and model IDs referenced as `{env:VAR}` in config |

After setup you get:

- **Build** — primary dev agent (full tool access, guarded git commands)
- **Plan** — read-only planning agent
- **Explore** — read-only codebase search (wiki-first)
- **Subagents** — `@code-reviewer`, `@security-auditor`, `@supabase`, `@ui-builder`, `@wiki-docs`
- **Model priority** — Groq → Mistral → OpenCode (small tasks) → Anthropic (deep review)

---

## Prerequisites

1. [OpenCode](https://opencode.ai) installed (`opencode` on your `PATH`)
2. API keys for the providers you use (Groq, Mistral, Anthropic; OpenCode Zen if applicable)
3. A project with Cursor rules in `.cursor/rules/` (optional but recommended)
4. A shell profile (`~/.zshrc` or `~/.bashrc`)

Run `opencode models` with your API keys exported to see valid `provider/model-id` values for your account.

---

## Directory layout

Create this structure under the global OpenCode config directory:

```
~/.config/opencode/
├── opencode.jsonc          # Main config (models, agents, instructions)
├── AGENTS.md               # Global rules (session start, principles)
├── .env                    # Symlink or copy of your secrets file (optional)
└── prompts/
    ├── build.txt
    ├── plan.txt
    ├── explore.txt
    ├── code-reviewer.txt
    ├── security-auditor.txt
    ├── supabase.txt
    ├── ui-builder.txt
    └── wiki-docs.txt
```

OpenCode also uses (automatically, no setup needed):

```
~/.opencode/bin/            # OpenCode binary
~/.local/state/opencode/    # Runtime state
~/.local/share/opencode/    # Database, logs, sessions
```

Per-project overrides (optional):

```
<your-project>/
├── opencode.jsonc          # Project-specific config
├── AGENTS.md               # Project-specific rules
└── .opencode/agents/       # Project-specific agents
```

---

## Step 1 — Environment variables

Create a `.env` file **outside version control** (e.g. in your main dev folder or `~/.config/opencode/.env`).

```bash
# AI/LLM — replace values with your own keys and model IDs from `opencode models`

ANTHROPIC_API_KEY=your-anthropic-key
ANTHROPIC_DEFAULT_MODEL=anthropic/claude-sonnet-4-6

GROQ_API_KEY=your-groq-key
GROQ_DEFAULT_MODEL=groq/meta-llama/llama-4-scout-17b-16e-instruct

MISTRAL_API_KEY=your-mistral-key
MISTRAL_DEFAULT_MODEL=mistral/codestral-latest

OPENCODE_DEFAULT_MODEL=opencode/north-mini-code-free
```

**Model ID format:** always `provider/model-id` (e.g. `groq/...`, `mistral/...`, `anthropic/...`, `opencode/...`).

**Priority order** (cheapest/fastest first, Anthropic for hard tasks):

| Priority | Env var | Used for |
|----------|---------|----------|
| 1 | `GROQ_DEFAULT_MODEL` | Default model, Build, Supabase, UI subagents |
| 2 | `MISTRAL_DEFAULT_MODEL` | Plan, wiki-docs subagent |
| 3 | `OPENCODE_DEFAULT_MODEL` | `small_model` (titles, lightweight tasks) |
| 4 | `ANTHROPIC_DEFAULT_MODEL` | Code review, security audit |

> **Important:** OpenCode resolves `{env:VAR}` in config at startup from your **shell environment**, not from `.env` files automatically. You must source the file in your shell profile (Step 2).

---

## Step 2 — Load env in your shell profile

Add to `~/.zshrc` (or `~/.bashrc`):

```bash
# OpenCode
export PATH="$HOME/.opencode/bin:$PATH"

# Load OpenCode env vars (adjust path to your .env file)
if [ -f "$HOME/path/to/your/.env" ]; then
  set -a
  source "$HOME/path/to/your/.env"
  set +a
fi
```

Open a **new terminal** after editing. Verify:

```bash
echo "$GROQ_DEFAULT_MODEL"
opencode models | grep -E 'groq|mistral|anthropic|opencode'
```

---

## Step 3 — Global `AGENTS.md`

Create `~/.config/opencode/AGENTS.md`:

```markdown
# Global Agent Rules

These rules apply to every OpenCode session. Project-specific `AGENTS.md` in repos takes precedence.

## Session start

Before starting work in a project:

1. Read `.wiki/INDEX.md` fully (if it exists)
2. Read `.wiki/architecture.md` and `.wiki/structure.md`
3. Confirm with a 3-sentence summary: what the project does, the main tech stack, and the most important service or workflow
4. Then wait for the first task

If `.wiki/INDEX.md` does not exist, say so and ask the user to run `npm run wiki` first.

## Codebase wiki

If a `.wiki/` folder exists, it is the authoritative knowledge base.

- Always read `.wiki/INDEX.md` before architectural decisions
- Never edit `.wiki/*.md` directly — regenerate with `npm run wiki`
- Never overwrite `<!-- manual -->` sections
- After schema/API/service/env changes, remind the user to run `npm run wiki`

## Cursor rules

Detailed conventions are loaded via the `instructions` field in `opencode.jsonc` from your project's `.cursor/rules/` directory. Apply them by context — do not load everything for every task.

## Model priority

Models come from environment variables (`GROQ_DEFAULT_MODEL`, `MISTRAL_DEFAULT_MODEL`, `OPENCODE_DEFAULT_MODEL`, `ANTHROPIC_DEFAULT_MODEL`). See `opencode.jsonc` for per-agent assignment.

## Subagents

| Agent | Purpose |
|-------|---------|
| `@explore` | Read-only codebase search |
| `@code-reviewer` | Review without edits |
| `@security-auditor` | Security audit without edits |
| `@supabase` | Migrations, RLS, typed services |
| `@ui-builder` | React + shadcn/ui components |
| `@wiki-docs` | Documentation guidance |

Switch primary agents with **Tab**: **Build** ↔ **Plan**.

## Core principles

1. Minimize scope — simplest correct diff only
2. Match existing conventions in the codebase
3. No hardcoded secrets — use `src/config/`
4. Only commit when explicitly asked
```

Customize wiki/session sections if your projects do not use a `.wiki/` folder.

---

## Step 4 — Prompt files

Create `~/.config/opencode/prompts/` with these files.

### `build.txt`

```
You are the Build agent — the default development assistant with full tool access.

## Session start
Before substantive work in a project:
1. Read `.wiki/INDEX.md`, `.wiki/architecture.md`, and `.wiki/structure.md` if they exist
2. Give a 3-sentence summary (purpose, stack, key workflow), then proceed
3. If `.wiki/INDEX.md` is missing, ask the user to run `npm run wiki` first

## Working style
- Minimize scope — simplest correct diff only
- Match existing conventions in the codebase
- No hardcoded secrets, URLs, or model names — use `src/config/`
- Only commit when explicitly asked

Delegate when appropriate: @explore, @code-reviewer, @supabase, @ui-builder, @security-auditor.
```

### `plan.txt`

```
You are the Plan agent — read-only analysis and planning.
Do not edit files or run bash commands.

## Focus
- Break work into clear, ordered steps
- Call out risks, dependencies, and verification steps
- Reference existing patterns from the codebase and loaded rules
- Prefer minimal, incremental changes

Present the plan and wait for the user to switch to Build for implementation.
```

### `explore.txt`

```
You are the Explore agent — fast, read-only codebase exploration.
Never modify files.

If `.wiki/INDEX.md` exists, read it before searching.
Find files by pattern, search code for keywords, report paths with brief context.
```

### `code-reviewer.txt`

```
You are a code reviewer. Do not make changes — only analyze and report.

Focus on: quality, bugs, performance, security, type safety.
Provide actionable feedback by severity (critical / warning / suggestion).
```

### `security-auditor.txt`

```
You are a security auditor. Do not make changes — only analyze and report.

Look for: input validation, auth/authz flaws, data exposure, dependency risks, config issues.
Report findings by severity with remediation steps.
```

### `supabase.txt`

```
You are a Supabase specialist.

- Migrations in `supabase/migrations/` with timestamp prefix
- Always include `id uuid`, `created_at`, `updated_at`
- RLS on ALL tables
- Regenerate types after schema changes
- Never use admin client on frontend or public routes
```

### `ui-builder.txt`

```
You are a UI builder for React + shadcn/ui + Tailwind.

- Install shadcn via CLI — never edit `src/components/ui/` directly
- Wrap and extend; use typed props and `cn()` for className
- Match existing design patterns in the codebase
```

### `wiki-docs.txt`

```
You are a documentation agent.

- Clear structure, code examples, user-friendly language
- Remind user to run `npm run wiki` to regenerate wiki — do not edit `.wiki/` directly
- Never overwrite manual wiki sections
```

---

## Step 5 — `opencode.jsonc`

Create `~/.config/opencode/opencode.jsonc`. Replace `PATH_TO_YOUR_PROJECT` with the absolute path to the project whose `.cursor/rules/` you want to load.

```jsonc
{
  "$schema": "https://opencode.ai/config.json",
  "model": "{env:GROQ_DEFAULT_MODEL}",
  "small_model": "{env:OPENCODE_DEFAULT_MODEL}",
  "autoupdate": true,
  "enabled_providers": ["groq", "mistral", "opencode", "anthropic"],
  "instructions": [
    "PATH_TO_YOUR_PROJECT/.cursor/rules/main.mdc",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/wiki.mdc",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/frontend-ui.mdc",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/component-design-consistency.mdc",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/supabase.mdc",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/llm-workflows.mdc",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/new-project.md",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/new-supabase-table.md",
    "PATH_TO_YOUR_PROJECT/.cursor/rules/opencode-session-start.md"
  ],
  "agent": {
    "build": {
      "mode": "primary",
      "model": "{env:GROQ_DEFAULT_MODEL}",
      "temperature": 0.3,
      "prompt": "{file:./prompts/build.txt}",
      "permission": {
        "bash": {
          "*": "allow",
          "git push*": "ask",
          "git commit*": "ask"
        },
        "task": {
          "*": "allow",
          "security-auditor": "ask"
        }
      }
    },
    "plan": {
      "mode": "primary",
      "model": "{env:MISTRAL_DEFAULT_MODEL}",
      "temperature": 0.1,
      "prompt": "{file:./prompts/plan.txt}",
      "permission": {
        "edit": "deny",
        "bash": "deny"
      }
    },
    "explore": {
      "prompt": "{file:./prompts/explore.txt}"
    },
    "code-reviewer": {
      "description": "Reviews code for quality, security, and best practices without making changes",
      "mode": "subagent",
      "model": "{env:ANTHROPIC_DEFAULT_MODEL}",
      "temperature": 0.1,
      "color": "accent",
      "prompt": "{file:./prompts/code-reviewer.txt}",
      "permission": {
        "edit": "deny",
        "bash": "deny"
      }
    },
    "security-auditor": {
      "description": "Performs security audits and identifies vulnerabilities",
      "mode": "subagent",
      "model": "{env:ANTHROPIC_DEFAULT_MODEL}",
      "temperature": 0.1,
      "color": "warning",
      "prompt": "{file:./prompts/security-auditor.txt}",
      "permission": {
        "edit": "deny",
        "bash": {
          "*": "deny",
          "git diff*": "allow",
          "git log*": "allow",
          "grep *": "allow"
        }
      }
    },
    "supabase": {
      "description": "Creates Supabase migrations, RLS policies, and typed service functions",
      "mode": "subagent",
      "model": "{env:GROQ_DEFAULT_MODEL}",
      "temperature": 0.2,
      "color": "success",
      "prompt": "{file:./prompts/supabase.txt}",
      "permission": {
        "bash": {
          "*": "ask",
          "npx supabase gen types*": "allow",
          "grep *": "allow"
        }
      }
    },
    "ui-builder": {
      "description": "Builds React UI with shadcn/ui and Tailwind following project conventions",
      "mode": "subagent",
      "model": "{env:GROQ_DEFAULT_MODEL}",
      "temperature": 0.3,
      "color": "info",
      "prompt": "{file:./prompts/ui-builder.txt}",
      "permission": {
        "bash": {
          "*": "ask",
          "npx shadcn@latest add*": "allow",
          "npm run typecheck*": "allow"
        }
      }
    },
    "wiki-docs": {
      "description": "Writes and maintains project documentation and wiki guidance",
      "mode": "subagent",
      "model": "{env:MISTRAL_DEFAULT_MODEL}",
      "temperature": 0.2,
      "color": "secondary",
      "prompt": "{file:./prompts/wiki-docs.txt}",
      "permission": {
        "bash": "deny"
      }
    }
  }
}
```

**Customize `instructions`:** list only the `.cursor/rules/` files that exist in your project. Omit stacks you do not use (e.g. remove `supabase.mdc` if you have no Supabase).

**Alternative — glob patterns** (per [Rules docs](https://opencode.ai/docs/rules/)):

```jsonc
"instructions": ["PATH_TO_YOUR_PROJECT/.cursor/rules/*.mdc"]
```

---

## Step 6 — Optional symlink for `.env`

If your `.env` lives in a project folder, symlink it into the OpenCode config dir for reference:

```bash
ln -sf /path/to/your/.env ~/.config/opencode/.env
```

This does **not** replace shell sourcing — OpenCode still needs vars in the process environment.

---

## Step 7 — Verify

1. Open a new terminal (env vars loaded)
2. Run `opencode` and start a session
3. Press **Tab** — you should cycle **Build** ↔ **Plan**
4. Type `@` — subagents should appear in autocomplete
5. Confirm the default model matches `GROQ_DEFAULT_MODEL`

---

## Daily usage

| Action | How |
|--------|-----|
| Switch primary agent | **Tab** (Build ↔ Plan) |
| Invoke subagent | `@code-reviewer review this diff` |
| Read-only exploration | `@explore find the auth middleware` |
| Planning without edits | Switch to **Plan** agent |
| Project-specific rules | Add `AGENTS.md` or `opencode.jsonc` in project root |

---

## Rules vs agents — quick reference

| Concern | Where |
|---------|-------|
| Stack, naming, git conventions | `instructions` → `.cursor/rules/*.mdc` |
| Session start ritual | `AGENTS.md` + `prompts/build.txt` |
| Role behavior ("you are a reviewer…") | `prompts/*.txt` or `agents/*.md` |
| Model per role | `agent` block in `opencode.jsonc` |
| Tool restrictions | `permission` per agent |

Do not duplicate full rule content inside agent prompts — reference loaded instructions and add role-specific behavior only.

---

## Customization checklist

- [ ] Adjust `instructions` to match your `.cursor/rules/` files
- [ ] Remove subagents you do not need (e.g. `supabase`, `ui-builder`)
- [ ] Change model assignments per agent after running `opencode models`
- [ ] Add project-level `opencode.jsonc` for repo-specific overrides
- [ ] Tighten bash permissions if you want more `ask` prompts
- [ ] Run `/init` in a project to generate project `AGENTS.md` ([Rules docs](https://opencode.ai/docs/rules/))

---

## Troubleshooting

| Problem | Fix |
|---------|-----|
| `{env:VAR}` empty in config | Source `.env` in shell profile; open new terminal |
| Model not found | Run `opencode models`; use exact `provider/model-id` |
| Rules not loading | Check `instructions` paths exist; use absolute paths |
| Subagent missing from `@` menu | Confirm `description` and `mode: subagent` in config |
| Plan agent still edits files | Check `permission.edit: deny` and `permission.bash: deny` |

---

*Last updated: June 2026 — based on OpenCode docs for Rules, Agents, and Config.*
