anomalyco-opencode

IndexedCommit: 4abf8040 pullsUpdated Feb 7, 2026

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

Install this reference
Reference

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

FilePurpose
packages/opencode/src/index.tsMain CLI entry point
packages/sdk/js/src/index.tsJavaScript/TypeScript SDK entry point
packages/plugin/src/index.tsPlugin system for extending functionality
README.mdOfficial documentation and installation guide

Packages

Packagenpm nameDescription
packages/opencodeopencodeMain CLI application (published as opencode-ai)
packages/sdk/js@opencode-ai/sdkJavaScript/TypeScript SDK for programmatic access
packages/script@opencode-ai/scriptBuild 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

  1. Use the SDK for programmatic workflows: When building scripts or automated tools, use the SDK with createOpencode() and createOpencodeClient() rather than spawning CLI processes manually.

  2. Implement proper permission handling: When creating custom tools using tool() from @opencode-ai/plugin, use the ctx.ask() method to request user permission for sensitive operations like file writes or external API calls.

  3. 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.

  4. Use context-aware file paths: When writing tools, prefer context.directory and context.worktree over process.cwd() for resolving file paths, as this ensures tools work correctly within project workspaces.

  5. Handle abort signals properly: Always respect the context.abort AbortSignal in custom tools to allow users to cancel long-running operations.

  6. 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

ExportTypeDescription
createOpencodeFunctionCreates a bundled client and server for programmatic OpenCode access
createOpencodeClientFunctionCreates an OpenCode API client for making requests to a running server
createOpencodeServerFunctionSpawns an OpenCode server process programmatically
createOpencodeTuiFunctionSpawns the interactive terminal UI programmatically
toolFunctionHelper for defining custom tools with Zod schema validation
Tool.ContextTypeContext passed to tool execute functions (session, directory, abort signal)
OpencodeClientClassGenerated client with methods for sessions, files, permissions, etc.
PluginTypeType definition for OpenCode plugins that extend functionality
HooksTypeAvailable lifecycle hooks for plugins (event, tool.execute.before, etc.)

SDK Client Methods (via OpencodeClient):

MethodAPI GroupDescription
.session.create()SessionsCreate a new coding session
.session.prompt()SessionsSend messages and get AI responses
.session.list()SessionsList all sessions
.session.get()SessionsGet session details by ID
.file.read()FilesRead file contents
.file.list()FilesList project files
.find.text()SearchSearch for text patterns in files
.find.files()SearchFind files matching glob patterns
.permission.list()PermissionsList active permission requests
.provider.list()ProvidersList available AI model providers

“Explore distant worlds.”

© 2026 Oscar Gabriel