A structured knowledge base for understanding OpenCode as a local-first AI coding assistant: architecture, agents, sessions, tools, permissions, database, server design, testing, and extensibility.
How to Use This Knowledge Base
Use this document as a reference when you need to understand:
How OpenCode is architected internally.
How agents, sub-agents, sessions, tools, and permissions work together.
What infrastructure OpenCode uses and deliberately avoids.
Where the system can be generalised beyond coding workflows.
OpenCode is a local-first AI coding assistant for developers. It provides a terminal, web, and desktop interface over a custom agent orchestration system that can inspect code, edit files, run shell commands, call tools, spawn sub-agents, and persist conversation state locally.
The system is notable because its core orchestration is custom-built rather than being based on frameworks such as LangChain, CrewAI, AutoGen, or Vercel AI SDK as the central orchestration layer. External libraries are used for infrastructure and provider transport, but the core model of sessions, agents, tools, permissions, and sub-agent spawning is implemented inside OpenCode.
OpenCode is designed for single-user local development, not multi-tenant production orchestration.
The most important abstraction is the session, which isolates conversations, sub-agents, permissions, messages, and state.
The most important safety mechanism is permission inheritance, especially for sub-agents.
Concurrency uses Effect fibers, not OS-level worker threads.
Tool execution and agent orchestration are extensible and domain-agnostic.
The coding-specific parts are mostly tools, prompts, agent configurations, and permission names.
Glossary
Term
Meaning
Agent
A configured AI role with a prompt, model settings, mode, and permission rules.
Primary agent
A user-facing agent, such as build, plan, or general.
Sub-agent
A helper agent spawned by a parent agent through the task tool.
Session
A conversation unit with its own state, message history, permissions, runner, and optional parent session.
Tool
A callable capability exposed to an agent, such as file read, edit, grep, shell, web fetch, or task spawning.
MCP
Model Context Protocol, used to connect external tools/providers.
Effect
The functional programming runtime used for services, dependency injection, structured concurrency, and typed effects.
Fiber
Lightweight Effect concurrency primitive running on Node.js's single event loop.
Permission ruleset
A rule structure controlling which tools are allowed, denied, or require user approval.
Human-in-the-loop
Mechanisms that pause execution for user approvals or structured answers.
1. Product Summary
What OpenCode Is
OpenCode is an AI-powered coding assistant for local development. It runs on the developer's machine and gives the LLM access to local codebase context through controlled tools.
Primary Use Cases
Codebase exploration and understanding.
Writing, editing, and refactoring code.
Automating development tasks via shell commands.
Planning and architectural reasoning.
Delegating exploration or research tasks to sub-agents.
Pair programming through terminal, web, or desktop UI.
Target Users
OpenCode is primarily built for:
Full-stack developers.
Backend engineers.
Frontend engineers.
DevOps and infrastructure engineers.
Open-source contributors.
Developers who want AI assistance with local control and permission-based safety.
2. Repository & Package Structure
OpenCode is organised as a monorepo with packages for the core application, shared libraries, SDKs, UI, desktop app, documentation, plugins, and admin console.
Shared utilities such as logging, filesystem helpers, and schemas.
packages/llm
LLM provider abstraction, route system, and tool runtime.
packages/sdk
API client for consumers of the HTTP server.
packages/plugin
Plugin support and extensibility.
packages/app, packages/ui
Shared UI components.
packages/desktop
Electron desktop application.
packages/web
Documentation website.
migration
SQLite schema migrations.
3. Core Architecture
Architectural Pattern
OpenCode uses a service-oriented architecture built on Effect.
Each feature is modelled as a service with:
Part
Purpose
Interface
Defines what the service can do.
Implementation
Defines how the service behaves.
Layer
Defines how dependencies are injected.
This makes the system modular, testable, and dependency-injectable.
Core Services
Service
Responsibility
Session
Manages AI conversations, message history, and state.
Agent
Defines AI personalities, modes, prompts, and permissions.
Config
Loads settings from files, environment variables, and remote configuration.
Auth
Manages API keys, OAuth, and provider credentials.
Provider
Connects to LLM providers.
Tool
Exposes file, shell, web, orchestration, and utility capabilities.
Server
Provides HTTP API and WebSocket transport.
Permission
Evaluates and enforces tool access rules.
Question
Handles structured human-in-the-loop prompts.
Background
Manages background jobs and task execution.
Main Data Flow
Text
User input
-> CLI / TUI / Web / Desktop UI
-> Config loading
-> Session creation or lookup
-> Agent selection
-> LLM call through provider layer
-> Tool execution when requested
-> Permission and question checks as needed
-> Results persisted in SQLite
-> Events emitted to UI and API consumers
Key Technologies
Layer
Technology
Language
TypeScript
Functional runtime
Effect
Validation
Effect Schema
UI
SolidJS
ORM
Drizzle ORM
Database
SQLite
Runtime and build
Bun
4. LLM Integration & Orchestration
Core Insight
OpenCode uses a custom orchestration layer.
The following are implemented internally:
Agent management and hierarchy.
Session creation and parent-child session relationships.
Permission derivation and composition.
Sub-agent spawning through the task tool.
Tool registry and execution orchestration.
LLM route system.
Session processor for LLM events, tool calls, and results.
What External Libraries Do
External libraries are used for infrastructure rather than core orchestration.
LLM request
-> Route.compile
-> Provider API
-> Tool call event detected
-> ToolRuntime.execute
-> Tool.execute through Effect
-> Tool result returned to session loop
-> Result fed back to LLM
Runtime Selection
Location:
Text
packages/opencode/src/session/llm.ts
The session layer decides per request between:
Runtime
Role
Native route runtime
Custom Effect-based runtime.
AI SDK runtime
Vercel AI SDK-based provider adapter.
5. Agent System
Agent Shape
Agents are configured with a name, mode, permissions, prompt, model, and generation settings.
TypeScript
{
name: "explore",
mode: "subagent",
permission: {
"*": "deny",
grep: "allow",
glob: "allow",
read: "allow"
},
prompt: "You are a fast exploration agent...",
model: { ... },
temperature: 0.0
}
Agent Modes
Mode
Meaning
primary
User-facing agent.
subagent
Helper agent that can only be invoked by another agent.
Built-In Agents
Agent
Mode
Purpose
Typical tools
build
Primary
Default execution agent.
Broad permitted tool set.
plan
Primary
Planning mode.
No edit tools.
general
Primary
Multi-step, parallel work.
Broad tool set.
explore
Sub-agent
Fast codebase exploration.
grep, glob, read.
scout
Sub-agent
External docs and dependency research.
webfetch, websearch.
compaction
Sub-agent
Context compaction.
read.
title
Sub-agent
Generate session titles.
None.
summary
Sub-agent
Summarise sessions.
read.
Agent Selection Flow
Text
User input
-> Session processor
-> Agent selected from request/config
-> Agent prompt + available tools prepared
-> LLM called
6. Sub-Agent Orchestration
How Sub-Agents Are Spawned
Sub-agents are not automatically picked from a worker queue. A parent agent explicitly creates one by calling the task tool.
Example:
TypeScript
task({
description: "Explore codebase",
prompt: "Find all API endpoints",
subagent_type: "explore"
})
Parent agent calls task tool
-> New child session is created
-> Permissions are derived from parent and sub-agent config
-> Sub-agent processes its prompt independently
-> Result is returned to parent as text
-> Parent may continue, spawn more sub-agents, or resume by task_id
Permission Derivation
Permission inheritance is the critical safety layer.
Linux / macOS / Windows
x
arm64 / x64
x
glibc / musl where applicable
Build Features
Cross-platform binary generation.
Embedded web UI bundling.
Embedded SQLite migrations.
Optional source maps.
Smoke testing for the current platform.
Release automation with GitHub uploads.
15. Testing Strategy
Test Framework
OpenCode uses Bun test.
Test Types
Unit tests.
Integration tests.
CLI tests.
HTTP API tests.
Effect-specific tests through a testEffect helper.
Snapshot tests.
Fixtures and Test Utilities
Temporary directories.
Test providers.
Mock services.
Stable snapshot outputs.
Testing Guidance
Documented testing practices include:
Avoid arbitrary sleep calls for readiness.
Prefer Effect synchronisation primitives.
Use dedicated test guides such as:
test/AGENTS.md
test/EFFECT_TEST_MIGRATION.md
16. Security Model
Strengths
Multiple authentication methods.
Credentials stored with restricted file permissions.
Default-deny permission posture.
Per-agent permission isolation.
Session-level rejection cascades.
Schema-based input validation.
Sub-agent permission inheritance.
Risks and Weaknesses
Risk
Explanation
API keys in local JSON
File permissions help, but secrets still exist on disk.
No resource quotas
Sub-agents can consume excessive API/network/local resources.
No permission revocation UI
Users may need to edit config manually.
No approval timeout
Execution can hang forever if the user walks away.
Complex inheritance
Sub-agent permission logic may be hard to audit.
No approval spam guard
Many tool calls can create many permission prompts.
Security Interpretation
OpenCode is designed for a trusted local developer environment.
It provides meaningful guardrails, especially around tools and permissions, but it is not a hardened multi-user sandbox or production agent execution platform.
17. Explicit Non-Goals / Missing Capabilities
Capability
Status
Headless browser
Not included.
Redis / external cache
Not used.
Distributed locks
Not used.
Durable task queue
Not used; background jobs are in-memory.
Resource quotas for sub-agents
Not implemented.
Maximum sub-agent limit
No hard limit.
Permission revocation UI
Not included.
Approval timeout
Not included.
CPU / OS-thread parallelism
Not used for Effect fibers.
Core orchestration framework
Not based on LangChain, CrewAI, AutoGen, etc.
18. Design Philosophy
1. Local-First and Single-User
OpenCode prioritises local control and developer ownership over multi-tenant cloud orchestration.
2. Trust the Developer
The system assumes the developer is the operator and provides permission controls rather than strict resource policing.
3. Service-Oriented with Effect
Each major capability is a service with interface, implementation, and dependency layer.
Effect provides:
Typed error handling.
Structured concurrency.
Dependency injection.
Interruption.
Resource safety.
4. Protocol-Agnostic LLM Routing
The LLM layer separates protocol, endpoint, authentication, and stream framing so providers can vary without rewriting orchestration.
5. Tools Are the Extension Point
The orchestration layer is general. Domain-specific behaviour is mainly in:
Tool implementations.
Agent prompts.
Agent configs.
Permission rule names.
6. MCP for External Extensibility
MCP is used to connect external services and tools without embedding every capability into core.
7. Sessions Are the Unit of Isolation
Sessions isolate:
Message history.
Agent state.
Parent-child relationships.
Permission state.
Running jobs.
8. Permission Inheritance Is the Safety Guarantee
Sub-agents inherit constraints from their parent so delegation does not become privilege escalation.
Check whether approval prompts can hang indefinitely.
Check whether permission revocation is documented.
Check whether prompt spam or tool spam can overwhelm users.
Decide whether resource quotas are required for your use case.
Generalisation Checklist
List domain-specific tools.
List domain-specific agents.
Define permission names and default policy.
Decide which tools require human approval.
Decide whether sessions remain the right isolation unit.
Decide whether SQLite is sufficient.
Decide whether background jobs need durable queues.
Decide whether MCP integrations are enough.
Define test fixtures for domain-specific workflows.
21. Frequently Asked Questions
Is OpenCode based on LangChain, CrewAI, AutoGen, or a similar orchestration framework?
No. The analysed design indicates that the orchestration layer is custom-built. External libraries are used for infrastructure, provider transport, validation, persistence, and runtime support.
Does OpenCode use a headless browser?
No. Core web fetching uses HTTP requests and parsing. Browser automation would need to be added through MCP, a custom tool, or a skill/plugin.
Do Effect fibers use multiple CPU cores?
No. Effect fibers run on Node.js's single-threaded event loop. They improve structured concurrency and I/O orchestration, but they are not OS threads.
Can sub-agents escalate permissions?
The intended safety model prevents this. Effective sub-agent permissions are derived from parent permissions and additional default denies.
Is the database suitable for production multi-user workloads?
Not as described. The database design is best suited for local, single-user, project-scoped workflows.
What is the most reusable part of OpenCode?
The session + agent + tool + permission harness is the most reusable part. The coding domain can be swapped out by replacing tools, prompts, and agent definitions.
22. Quick Reference
Most Important Concepts
Concept
Why it matters
Session
Unit of state, isolation, persistence, and execution.
Agent
Defines role, tools, prompt, model, and permissions.