anomalyco-opencode
OpenCode is an open-source AI-powered development tool and coding agent that provides a terminal-first CLI, desktop application, and a JavaScript/TypeScript SDK for programmatic access. It enables dev
OpenCode
OpenCode is an open-source AI-powered development tool and coding agent that provides a terminal-first CLI, desktop application, and a JavaScript/TypeScript SDK for programmatic access. It enables developers to interact with AI agents through a TUI (Terminal User Interface), manage sessions, automate code changes, and build custom tools via a plugin system.
Quick References
| File | Purpose |
|---|---|
packages/opencode/src/index.ts | Main CLI entry point |
packages/sdk/js/src/index.ts | JavaScript/TypeScript SDK entry point |
packages/plugin/src/index.ts | Plugin system for extending functionality |
README.md | Official documentation and installation guide |
Packages
| Package | npm name | Description |
|---|---|---|
packages/opencode | opencode | Main CLI application (published as opencode-ai) |
packages/sdk/js | @opencode-ai/sdk | JavaScript/TypeScript SDK for programmatic access |
packages/script | @opencode-ai/script | Build scripts and utilities |
When to Use
- AI-Assisted Development: When you want an AI coding agent that can read, analyze, edit, and write code while you work in your terminal
- Automated Code Tasks: For repetitive coding operations like refactoring, testing, documentation generation, or code reviews
- Custom Workflows: When you need to build custom tools and integrate them into an AI-powered development environment
- Headless Server Mode: For running OpenCode as a background service that other applications can interact with via SDK
- Plugin Development: When extending OpenCode with custom tools, authentication providers, or workflow hooks
Installation
# Install the CLI globally
npm install -g opencode-ai
# or with bun
bun install -g opencode-ai
# Install SDK for programmatic access
npm install @opencode-ai/sdk
# Install plugin development utilities
npm install @opencode-ai/plugin
Best Practices
-
Use the SDK for programmatic workflows: When building scripts or automated tools, use the SDK with
createOpencode()andcreateOpencodeClient()rather than spawning CLI processes manually. -
Implement proper permission handling: When creating custom tools using
tool()from@opencode-ai/plugin, use thectx.ask()method to request user permission for sensitive operations like file writes or external API calls. -
Validate tool parameters with Zod schemas: Tool arguments should be validated using Zod schemas that are built into the plugin system. Return meaningful error messages for validation failures.
-
Use context-aware file paths: When writing tools, prefer
context.directoryandcontext.worktreeoverprocess.cwd()for resolving file paths, as this ensures tools work correctly within project workspaces. -
Handle abort signals properly: Always respect the
context.abortAbortSignalin custom tools to allow users to cancel long-running operations. -
Provide clear tool descriptions: Write helpful descriptions for custom tools so the AI agent understands when and how to use them appropriately.
Common Patterns
Starting a headless OpenCode server:
import { createOpencode } from "@opencode-ai/sdk"
const opencode = await createOpencode({
hostname: "127.0.0.1",
port: 4096,
timeout: 5000,
})
const client = opencode.client
const server = opencode.server
console.log(`Server running at ${server.url}`)
// Later, when done:
server.close()
Using the SDK client to create AI sessions:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({
baseUrl: "http://localhost:4096",
directory: process.cwd(),
})
const session = await client.session.create()
const result = await client.session.prompt({
path: { id: session.data!.id },
body: {
agent: "build",
parts: [{ type: "text", text: "Add unit tests for the user module" }],
},
})
Creating a custom tool for OpenCode:
import { tool } from "@opencode-ai/plugin/Tool"
export default tool({
description: "Search for GitHub pull requests in a repository",
args: {
query: tool.schema.string().describe("Search query for PR titles and descriptions"),
limit: tool.schema.number().describe("Maximum results to return").default(10),
},
async execute(args, context: ToolContext) {
context.metadata({
title: "Searching GitHub PRs",
metadata: { query: args.query },
})
const response = await fetch(
`https://api.github.com/search/issues?q=${encodeURIComponent(
`${args.query} repo:owner/repo type:pr`
)}&per_page=${args.limit}`
)
const data = await response.json()
const prs = data.items
return `Found ${data.total_count} PRs:\n${prs.map((pr) => ` - ${pr.title}: ${pr.html_url}`).join('\n')}`
}
})
Creating a plugin with hooks:
import type { Plugin, Hooks } from "@opencode-ai/plugin"
const myPlugin: Plugin = (input) => {
return {
event: async ({ event }) => {
console.log("Event received:", event)
},
"tool.execute.before": async ({ tool }, { args }) => {
console.log(`Tool ${tool} called with args:`, args)
},
tool: {
"my-custom-tool": tool({
description: "A custom tool",
args: {
input: tool.schema.string(),
},
async execute(args) {
return `Processed: ${args.input}`
},
}),
},
}
}
export default myPlugin
Using the CLI to start an interactive session:
# Start the TUI in your project directory
opencode
# Use a specific model
opencode --model claude-3.5-sonnet
# Use a specific agent
opencode --agent plan
# Resume a previous session
opencode --session <session-id>
Running OpenCode as a headless server:
# Start the server (note: set OPENCODE_SERVER_PASSWORD for security)
opencode serve --hostname 127.0.0.1 --port 4096
API Quick Reference
| Export | Type | Description |
|---|---|---|
createOpencode | Function | Creates a bundled client and server for programmatic OpenCode access |
createOpencodeClient | Function | Creates an OpenCode API client for making requests to a running server |
createOpencodeServer | Function | Spawns an OpenCode server process programmatically |
createOpencodeTui | Function | Spawns the interactive terminal UI programmatically |
tool | Function | Helper for defining custom tools with Zod schema validation |
Tool.Context | Type | Context passed to tool execute functions (session, directory, abort signal) |
OpencodeClient | Class | Generated client with methods for sessions, files, permissions, etc. |
Plugin | Type | Type definition for OpenCode plugins that extend functionality |
Hooks | Type | Available lifecycle hooks for plugins (event, tool.execute.before, etc.) |
SDK Client Methods (via OpencodeClient):
| Method | API Group | Description |
|---|---|---|
.session.create() | Sessions | Create a new coding session |
.session.prompt() | Sessions | Send messages and get AI responses |
.session.list() | Sessions | List all sessions |
.session.get() | Sessions | Get session details by ID |
.file.read() | Files | Read file contents |
.file.list() | Files | List project files |
.find.text() | Search | Search for text patterns in files |
.find.files() | Search | Find files matching glob patterns |
.permission.list() | Permissions | List active permission requests |
.provider.list() | Providers | List available AI model providers |