OpenCode Agents: How Build and Plan Roles Differ
OpenCode hit 160,000 GitHub stars. By early 2026, it stands as the leading open-source AI coding agent. This isn't accidental. The architecture separates high-level orchestration from specialized execution. Primary agents like Build handle unrestricted development, while Plan manages safe analysis. Specific subtasks get offloaded to subagents like Explore and Scout.
This guide breaks down how primary agents enforce session hierarchy and tool permissions to stop rogue code modifications. We'll dig into the mechanics of subagent invocation, how these workers handle read-only research or parallel units without clogging the main context window. You'll also learn to craft custom agents via JSON and Markdown to force the AI into specific behavioral lanes.
The project moves fast: over 900 contributors and 13,000 commits validate this modular approach. Knowing the difference between the Build agent's full system access and the Scout agent's external focus lets you build reliable pipelines. Let's dissect the OpenCode roles to optimize your automated development.
The Role of Primary Agents and Subagents in OpenCode Workflows
Primary Agents vs Subagents in OpenCode Workflows
OpenCode enforces a strict hierarchy: orchestration stays separate from execution. Primary agents are your direct interface. They manage the conversation flow and hold the permission keys. You cycle between them using Tab or a custom `switch_agent` binding. Build wields full tool access for active coding. Plan locks file edits and bash commands behind an `ask` state by default. This friction forces explicit validation before anything high-risk happens.
Subagents are the specialized labor force. You invoke them manually with `@` mentions or let the system trigger them for specific capabilities. The General subagent handles complex, multi-step research with full tool access. Explore performs rapid, read-only codebase traversal. Unlike primary agents, subagents run in child sessions. This isolation enables parallel work without polluting the main context window. It also supports privacy: code stays local to your chosen provider instead of routing through vendor clouds.
Context isolation solves one problem but creates another. Preventing state leakage between sessions is vital, yet too much fragmentation blinds the primary agent to global project awareness if it fails to synthesize child outputs. You must configure permission schemas carefully to balance autonomy with safety.
When to Use Build Agent vs Plan Agent Modes
Active development needs the Build agent. Analysis tasks, where file edits must stay blocked by default, require Plan.
Build enables all tools immediately. It's the standard orchestrator for writing code and executing system commands. Use this when you need direct workspace modification without intermediate approval steps. Plan restricts permissions so file edits and bash commands trigger an ask state. This constraint stops unintended modifications while the LLM analyzes structure or suggests architectural changes. Deploy Plan when auditing legacy repositories or generating roadmaps before actual coding begins.
Speed often conflicts with safety. Automatic execution accelerates tasks but risks running destructive commands unchecked. Plan mitigates this by forcing human validation on every write operation or shell invocation. Exploratory queries won't alter the working directory state. Privacy remains preserved as code stays between you and your provider rather than processing on vendor servers by default (privacy). Weigh rapid iteration against strict change control when picking your primary agent. Start sessions in Plan mode for unfamiliar codebases to map dependencies safely before switching to Build.
Built-in Agent Capabilities: General, Explore, and Scout
OpenCode ships with three built-in subagents, General, Explore, and Scout, each engineered with distinct permission sets.
The General subagent is a full-capacity worker for complex, multi-step tasks. It can modify files but excludes the `todo` tool. Explore acts as a read-only scanner optimized for rapid codebase navigation and pattern matching without write access. Scout extends this read-only constraint to external dependencies, cloning repositories into a managed cache to inspect upstream source code safely.
Delegating to General introduces write-risk absent in Explore or Scout configurations. While General accelerates throughput by running multiple work units in parallel, it lacks the inherent safety guardrails of the read-only variants. You must choose between execution speed and workspace immutability for every delegated task.
Cost visibility is integrated. The system calculates exact run costs by cross-referencing token usage with real-time pricing data from models.dev. Invoke these assistants manually via `@` mentions or let primary agents orchestrate them automatically based on task descriptions.
Internal Mechanics of Agent Configuration and Session Hierarchy
Temperature Ranges and Agent Configuration Files
LLM randomness sits on a scale from 0.0 to 1.0. This parameter, temperature, dictates output determinism. Low values produce focused, repeatable logic suitable for code analysis. Higher settings inject variance for creative exploration. This setting interacts directly with the file-based definition system where operators define agent behavior via JSON or Markdown. Configuration files reside globally in `~/.config/opencode/agents/` or locally within `.opencode/agents/`. The filename itself defines the agent identity.
| Format | Location | Naming Convention |
|---|---|---|
| JSON | `opencode.json` | Key-based definition |
| Markdown | `~/.config/opencode/agents/` | Filename becomes ID |
Cost predictability often conflicts with creative freedom. High temperature aids brainstorming yet increases token variance, complicating the real-time cost calculations performed by the internal `getUsage` function. Balance exploratory needs against budget constraints. Markdown configurations allow inline system prompts that override default behaviors, offering granular control over the permission model. Unlike JSON, which requires rigid syntax validation, Markdown files separate instructions from metadata, reducing parsing errors during rapid iteration. Inconsistent temperature settings across global and local files lead to unpredictable responses if precedence rules are misunderstood. The file closest to the execution context typically wins, but verify the active configuration by inspecting both scopes. Standardize temperature ranges per task type to maintain consistent orchestration quality.
Session Navigation Commands and Subagent Invocation
Enter child sessions using the `session_child_first` command, bound by default to `+Down`, to inspect subagent work directly. This step is necessary because primary agents delegate specialized tasks to subagents like Explore or Scout, creating isolated execution contexts that require explicit traversal. You can bypass automatic orchestration by manually invoking a specific worker via @ mentions in the chat input. Subagents can be invoked manually by @ mentioning a subagent in a message. A common failure mode occurs when an @ mention yields no response; this often indicates the target agent is hidden via configuration or the description field lacks the semantic keywords required for the router to resolve the request. Distinguishing between read-only explorers and external researchers prevents permission errors during these manual calls.
| Command | Default Key | Function |
|---|---|---|
| `session_child_first` | `+Down` | Enter first child |
| `session_child_cycle` | Right | Next sibling session |
| `session_parent` | Up | Return to parent |
Context does not flow upstream automatically. You must return to the parent session to synthesize findings into the main thread. The system provides full project awareness, yet the session boundary isolates the subagent's intermediate reasoning steps from the primary context window until completion. Developers analyzing complex dependency chains with Scout must manually traverse the session tree to verify that external cloning operations completed before integrating results. Validating agent descriptions ensures manual invocation reliability.
Validating Agent Descriptions and Keybind Setup
Verify the Description field exists in every agent definition to prevent routing failures. This required configuration option explicitly defines the agent's function and appropriate usage context, acting as the primary signal for automated task delegation. Primary agents cannot correctly identify when to invoke a specialized subagent without this semantic anchor. Stalled workflows occur when the system fails to recognize available tools. Ensure this metadata is present whether defining agents via opencode.json or Markdown files.
Confirm that the switch_agent keybind or Tab key correctly cycles through available primary agents to maintain session fluidity. Users rely on this input mechanism to toggle between the unrestricted Build agent and the restricted Plan agent without interrupting their workflow context. A misconfigured keybind forces manual re-entry of agent names, slowing down iterative development cycles where rapid context switching is frequent.
Troubleshoot unresponsive @ mentions by checking if the target subagent is marked as hidden in the configuration. Hidden agents remain callable by other automated processes but disappear from user autocomplete menus, a design choice that prevents accidental manual invocation of system-level workers.
| Failure Symptom | Likely Configuration Cause |
|---|---|
| Agent not suggested in autocomplete | Missing Description or Hidden set to true |
| Wrong agent executes task | Vague Description lacking specific keywords |
| Cannot switch agents | switch_agent keybind conflict or misconfiguration |
The hierarchical orchestration model functions as intended only when these validation steps are complete, balancing autonomous tool use with explicit user control.
Implementing Custom Agents via JSON and Markdown Files
JSON vs Markdown Agent Configuration Syntax
OpenCode accepts custom agent definitions through opencode.json or dedicated Markdown files. Editing opencode.json centralizes logic, while separate Markdown files keep prompts distinct from schema.
- Select a configuration format based on workflow requirements.
- Map the file name to the agent identifier, where specific naming conventions create distinct agents.
- Place global definitions in `~/.config/opencode/` or project-specific files in `.opencode/`.
| Feature | JSON Config | Markdown File |
|---|---|---|
| Location | Root `opencode.json` | `agents/` directory |
| Naming | Object key definition | Filename becomes ID |
| Content | Structured metadata only | Metadata plus system prompt |
| Use Case | Global permission policies | Task-specific logic |
The Description field remains mandatory across both formats to guarantee correct task routing. JSON structures permissions for easy auditing. Markdown files embed system prompts directly, removing dependencies on external text. A structural tension exists here: JSON enforces strict schema validation but separates prompt logic from definition, whereas Markdown unifies prompt and config but lacks native schema enforcement for complex permission trees. Operators defining agents via privacy-focused configurations must ensure sensitive prompts in configuration files respect file system permissions, as these files store explicit behavioral instructions alongside configuration data.
Interactive Agent Creation via CLI Command
Running `opencode agent create` launches a wizard that builds configuration files without manual drafting. The operator selects a storage scope, choosing between global directories or project-local paths like `.opencode/agents/`. Next, the tool requests a natural language description to populate the mandatory Description field required for agent routing logic. Subsequent steps guide the selection of specific capabilities, allowing granular control over tool access where unselected items are implicitly denied by default.
- Run the creation command in the terminal root.
- Choose the configuration scope for the new entity.
- Input the functional description for task identification.
- Toggle permissions for actions like `bash` or `edit`.
- Generate the final configuration file with embedded system prompts.
This interactive approach reduces configuration errors common in manual JSON editing, particularly when defining complex permission matrices. The CLI wizard offers less flexibility than direct file manipulation for advanced settings like custom model overrides. Operators requiring precise control over model selection or specific prompt tuning must still edit the resulting file manually. The generated file serves as a safe baseline, but production environments often demand the fine-tuned parameters found in deep-dive technical analyses.
| Step | Input Type | Outcome |
|---|---|---|
| Scope | Path Selection | Global or Local File |
| Description | Text String | Routing Metadata |
| Permissions | Toggle List | Security Policy |
The resulting agent integrates immediately into the orchestration layer, ready for invocation via @ mention or automatic delegation.
Defining Specialized Agent Roles and Denials
Configure explicit permission denials in opencode.json to enforce strict safety boundaries for specialized roles.
- Define the Documentation agent (docs-writer.md) as a subagent that writes and maintains project documentation and denies bash permissions.
- Set the bash permission to `deny` within the configuration to prevent the agent from executing system commands.
- Establish the Security auditor (security-auditor.md) as a subagent that performs security audits and identifies vulnerabilities and denies edit permissions.
- Apply an `edit` denial to ensure this auditor can read files but cannot modify the codebase directly.
This explicit denial strategy prevents accidental workspace pollution during sensitive analysis phases. Denying bash access limits the agent's ability to run local commands, forcing reliance on provided context or external verification tools. Unlike cloud-native solutions that may process data on vendor servers, this local configuration keeps code between the user and their chosen provider. Treat permission keys as hard firewall rules rather than suggestions. Regular auditing of these deny lists is recommended to match evolving threat models.
Operational Control Through Agent Invocation and Lifecycle Management
OpenCode Agent Lifecycle and Invocation Mechanics
Subagents start work when a primary agent delegates tasks or users trigger execution manually via @general mentions. This manual override bypasses automated routing logic so engineers force specific tool use regardless of the primary agent internal state. Direct mentions provide immediate context switching without intermediate planning steps unlike automatic delegation which relies on semantic matching.
Session hierarchy management requires precise navigation commands to maintain workflow continuity across parent and child contexts. Operators enter the first child session using session_child_first, typically mapped to the +Down sequence, before cycling through parallel executions with session_child_cycle. Returning to the main conversation thread demands explicit use of the session_parent command to avoid orphaned context windows.
Flexible spawning models increase cognitive load during deep traversal operations. Engineers must track their position within the session tree manually because the interface does not visually flatten nested contexts into a single view. Strict discipline prevents context loss when managing complex multi-agent debugging sessions. Resources at AI Agents News offer deeper analysis of secure agent deployment patterns.
Application: Executing Session Navigation Commands for Child Agents
Trigger the session_child_first command to enter the first child session from a parent context, an action defaulting to the +Down key sequence. This shift moves active focus from the primary agent to the initial subagent execution thread without altering parent conversation history. Operators managing complex multi-step tasks often require this explicit entry point to monitor intermediate reasoning steps occurring within the child scope.
Navigate between parallel subagent threads inside a child session using the session_child_cycle command, mapped by default to the Right arrow key. Reversing direction requires the session_child_cycle_reverse binding, typically assigned to the Left arrow, allowing bidirectional movement across active child contexts. Control returns to the main conversation flow via the session_parent command, usually bound to the Up arrow, which collapses the child view and restores the primary agent interface. Configuration rather than runtime keybinds handles disabling or preventing specific agent actions since the system lacks a global "disable" toggle during execution.
| Action | Default Key | Scope |
|---|---|---|
| Enter First Child | +Down | Parent to Child |
| Cycle Next | Right | Child to Child |
| Cycle Previous | Left | Child to Child |
| Return to Parent | Up | Child to Parent |
State isolation creates a structural limitation here. Navigating away from a child session does not halt background processes if the underlying model continues generating tokens. Engineers must distinguish between UI focus and computational activity because the snapshotting mechanism preserves state but does not pause execution upon navigation. Verify task completion status within the child view before cycling away to avoid orphaned runs consuming token budgets.
Optimizing Context by Cycling Primary Agents via Keybinds
Press the Tab key or your configured switch_agent binding to switch the active primary agent instantly. This action toggles the interface between the unrestricted Build mode and the restricted Plan mode, shifting the underlying permission set from full execution to ask-before-write safeguards. Engineers managing complex refactors should cycle to Plan during the analysis phase to prevent accidental file modifications while the model maps dependencies.
Manual overrides allow direct invocation of specialized subagents like @general for parallel task execution without leaving the current thread.
| Agent Type | Default Behavior | Key Constraint |
|---|---|---|
| Build | Full tool access | Can execute bash |
| Plan | Read-only analysis | Edits set to ask |
Cycling away from a primary agent suspends its immediate context window, effectively pausing tool access until re-selected, so disabling an agent requires no complex teardown. This local-first approach keeps code context between the user and their chosen provider, enhancing privacy by design unlike cloud-native systems that may retain state on vendor servers. Context switching does not merge conversation histories; operators must manually track distinct logical threads when toggling between planning and execution modes frequently.
About
Priya Nair serves as AI Industry Editor at AI Agents News, where she tracks product launches and platform shifts across the autonomous agent environment. Her daily work analyzing vendors like Devin, Claude Code, and Cursor provides the precise context needed to evaluate OpenCode's new agent capabilities. Because she constantly assesses how different frameworks handle tool access and multi-agent coordination, Nair is uniquely positioned to explain the practical utility of configuring primary agents versus subagents. Her reporting focuses on concrete functionality rather than hype, ensuring this breakdown of custom prompts and workflow specialization remains grounded in real-world engineering needs. At AI Agents News, the mission is to provide software engineers with trustworthy analysis of the tools they build with. By connecting OpenCode's specific features to broader industry patterns in agentic orchestration, this article offers the clear, technical clarity that builders require to make informed decisions about their development environments.
Conclusion
Scaling agent workflows exposes a critical friction point where UI navigation diverges from computational reality. Because the snapshotting mechanism preserves state without halting execution, operators risk paying for idle token generation simply by shifting focus. This structural gap demands a disciplined operational rhythm where verifying task completion in the child view becomes a mandatory gate before any context switch. Relying on visual cues alone fails when background processes continue consuming resources unseen. Teams must treat the distinction between Build and Plan modes not merely as a permission toggle but as a hard boundary for resource allocation.
Adopt a strict protocol where you validate all background runs before cycling the primary agent via keybinds. This practice prevents orphaned executions from inflating costs while maintaining the privacy benefits of local-first context management. Do not assume that leaving a view pauses the underlying model. Start this week by auditing your current session logs to identify any completed tasks that continued generating tokens after you navigated away. Adjust your workflow to explicitly confirm termination status within the child view before invoking the switch_agent binding for your next refactor.
Frequently Asked Questions
Plan mode blocks all file edits and bash commands by default. This restriction forces an ask state for every action, preventing the 13,000 commits in the codebase from being corrupted by unintended automated changes.
Subagents execute tasks within isolated child sessions separate from the primary conversation. This architecture allows over a large number developers to run parallel research units without bloating the main context window with excessive data.
Yes, you can configure custom agents using JSON and Markdown files to tailor behavior. This flexibility supports the 900 contributors who have expanded the system beyond the standard General, Explore, and Scout options.
Use the session_parent command, typically mapped to the Up key, to return to the parent session. This navigation is essential for managing the workflow of over 5 million monthly active developers efficiently.
The macOS ARM64 desktop binary requires 39.5 MB of disk space for installation. This small footprint allows the 160,000 GitHub stars project to be deployed quickly on local machines without heavy resource usage.