Initial commit: Discord-Claude Gateway with event-driven agent runtime
This commit is contained in:
1
references/opencode/link.md
Normal file
1
references/opencode/link.md
Normal file
@@ -0,0 +1 @@
|
||||
https://opencode.ai/docs/
|
||||
437
references/opencode/opencode cli.md
Normal file
437
references/opencode/opencode cli.md
Normal file
@@ -0,0 +1,437 @@
|
||||
|
||||
CLI
|
||||
|
||||
OpenCode CLI options and commands.
|
||||
|
||||
The OpenCode CLI by default starts the TUI when run without any arguments.
|
||||
Terminal window
|
||||
|
||||
opencode
|
||||
|
||||
But it also accepts commands as documented on this page. This allows you to interact with OpenCode programmatically.
|
||||
Terminal window
|
||||
|
||||
opencode run "Explain how closures work in JavaScript"
|
||||
|
||||
tui
|
||||
|
||||
Start the OpenCode terminal user interface.
|
||||
Terminal window
|
||||
|
||||
opencode [project]
|
||||
|
||||
Flags
|
||||
Flag Short Description
|
||||
--continue -c Continue the last session
|
||||
--session -s Session ID to continue
|
||||
--fork Fork the session when continuing (use with --continue or --session)
|
||||
--prompt Prompt to use
|
||||
--model -m Model to use in the form of provider/model
|
||||
--agent Agent to use
|
||||
--port Port to listen on
|
||||
--hostname Hostname to listen on
|
||||
Commands
|
||||
|
||||
The OpenCode CLI also has the following commands.
|
||||
agent
|
||||
|
||||
Manage agents for OpenCode.
|
||||
Terminal window
|
||||
|
||||
opencode agent [command]
|
||||
|
||||
attach
|
||||
|
||||
Attach a terminal to an already running OpenCode backend server started via serve or web commands.
|
||||
Terminal window
|
||||
|
||||
opencode attach [url]
|
||||
|
||||
This allows using the TUI with a remote OpenCode backend. For example:
|
||||
Terminal window
|
||||
|
||||
# Start the backend server for web/mobile access
|
||||
opencode web --port 4096 --hostname 0.0.0.0
|
||||
|
||||
# In another terminal, attach the TUI to the running backend
|
||||
opencode attach http://10.20.30.40:4096
|
||||
|
||||
Flags
|
||||
Flag Short Description
|
||||
--dir Working directory to start TUI in
|
||||
--session -s Session ID to continue
|
||||
create
|
||||
|
||||
Create a new agent with custom configuration.
|
||||
Terminal window
|
||||
|
||||
opencode agent create
|
||||
|
||||
This command will guide you through creating a new agent with a custom system prompt and tool configuration.
|
||||
list
|
||||
|
||||
List all available agents.
|
||||
Terminal window
|
||||
|
||||
opencode agent list
|
||||
|
||||
auth
|
||||
|
||||
Command to manage credentials and login for providers.
|
||||
Terminal window
|
||||
|
||||
opencode auth [command]
|
||||
|
||||
login
|
||||
|
||||
OpenCode is powered by the provider list at Models.dev, so you can use opencode auth login to configure API keys for any provider you’d like to use. This is stored in ~/.local/share/opencode/auth.json.
|
||||
Terminal window
|
||||
|
||||
opencode auth login
|
||||
|
||||
When OpenCode starts up it loads the providers from the credentials file. And if there are any keys defined in your environments or a .env file in your project.
|
||||
list
|
||||
|
||||
Lists all the authenticated providers as stored in the credentials file.
|
||||
Terminal window
|
||||
|
||||
opencode auth list
|
||||
|
||||
Or the short version.
|
||||
Terminal window
|
||||
|
||||
opencode auth ls
|
||||
|
||||
logout
|
||||
|
||||
Logs you out of a provider by clearing it from the credentials file.
|
||||
Terminal window
|
||||
|
||||
opencode auth logout
|
||||
|
||||
github
|
||||
|
||||
Manage the GitHub agent for repository automation.
|
||||
Terminal window
|
||||
|
||||
opencode github [command]
|
||||
|
||||
install
|
||||
|
||||
Install the GitHub agent in your repository.
|
||||
Terminal window
|
||||
|
||||
opencode github install
|
||||
|
||||
This sets up the necessary GitHub Actions workflow and guides you through the configuration process. Learn more.
|
||||
run
|
||||
|
||||
Run the GitHub agent. This is typically used in GitHub Actions.
|
||||
Terminal window
|
||||
|
||||
opencode github run
|
||||
|
||||
Flags
|
||||
Flag Description
|
||||
--event GitHub mock event to run the agent for
|
||||
--token GitHub personal access token
|
||||
mcp
|
||||
|
||||
Manage Model Context Protocol servers.
|
||||
Terminal window
|
||||
|
||||
opencode mcp [command]
|
||||
|
||||
add
|
||||
|
||||
Add an MCP server to your configuration.
|
||||
Terminal window
|
||||
|
||||
opencode mcp add
|
||||
|
||||
This command will guide you through adding either a local or remote MCP server.
|
||||
list
|
||||
|
||||
List all configured MCP servers and their connection status.
|
||||
Terminal window
|
||||
|
||||
opencode mcp list
|
||||
|
||||
Or use the short version.
|
||||
Terminal window
|
||||
|
||||
opencode mcp ls
|
||||
|
||||
auth
|
||||
|
||||
Authenticate with an OAuth-enabled MCP server.
|
||||
Terminal window
|
||||
|
||||
opencode mcp auth [name]
|
||||
|
||||
If you don’t provide a server name, you’ll be prompted to select from available OAuth-capable servers.
|
||||
|
||||
You can also list OAuth-capable servers and their authentication status.
|
||||
Terminal window
|
||||
|
||||
opencode mcp auth list
|
||||
|
||||
Or use the short version.
|
||||
Terminal window
|
||||
|
||||
opencode mcp auth ls
|
||||
|
||||
logout
|
||||
|
||||
Remove OAuth credentials for an MCP server.
|
||||
Terminal window
|
||||
|
||||
opencode mcp logout [name]
|
||||
|
||||
debug
|
||||
|
||||
Debug OAuth connection issues for an MCP server.
|
||||
Terminal window
|
||||
|
||||
opencode mcp debug <name>
|
||||
|
||||
models
|
||||
|
||||
List all available models from configured providers.
|
||||
Terminal window
|
||||
|
||||
opencode models [provider]
|
||||
|
||||
This command displays all models available across your configured providers in the format provider/model.
|
||||
|
||||
This is useful for figuring out the exact model name to use in your config.
|
||||
|
||||
You can optionally pass a provider ID to filter models by that provider.
|
||||
Terminal window
|
||||
|
||||
opencode models anthropic
|
||||
|
||||
Flags
|
||||
Flag Description
|
||||
--refresh Refresh the models cache from models.dev
|
||||
--verbose Use more verbose model output (includes metadata like costs)
|
||||
|
||||
Use the --refresh flag to update the cached model list. This is useful when new models have been added to a provider and you want to see them in OpenCode.
|
||||
Terminal window
|
||||
|
||||
opencode models --refresh
|
||||
|
||||
run
|
||||
|
||||
Run opencode in non-interactive mode by passing a prompt directly.
|
||||
Terminal window
|
||||
|
||||
opencode run [message..]
|
||||
|
||||
This is useful for scripting, automation, or when you want a quick answer without launching the full TUI. For example.
|
||||
Terminal window
|
||||
|
||||
opencode run Explain the use of context in Go
|
||||
|
||||
You can also attach to a running opencode serve instance to avoid MCP server cold boot times on every run:
|
||||
Terminal window
|
||||
|
||||
# Start a headless server in one terminal
|
||||
opencode serve
|
||||
|
||||
# In another terminal, run commands that attach to it
|
||||
opencode run --attach http://localhost:4096 "Explain async/await in JavaScript"
|
||||
|
||||
Flags
|
||||
Flag Short Description
|
||||
--command The command to run, use message for args
|
||||
--continue -c Continue the last session
|
||||
--session -s Session ID to continue
|
||||
--fork Fork the session when continuing (use with --continue or --session)
|
||||
--share Share the session
|
||||
--model -m Model to use in the form of provider/model
|
||||
--agent Agent to use
|
||||
--file -f File(s) to attach to message
|
||||
--format Format: default (formatted) or json (raw JSON events)
|
||||
--title Title for the session (uses truncated prompt if no value provided)
|
||||
--attach Attach to a running opencode server (e.g., http://localhost:4096)
|
||||
--port Port for the local server (defaults to random port)
|
||||
serve
|
||||
|
||||
Start a headless OpenCode server for API access. Check out the server docs for the full HTTP interface.
|
||||
Terminal window
|
||||
|
||||
opencode serve
|
||||
|
||||
This starts an HTTP server that provides API access to opencode functionality without the TUI interface. Set OPENCODE_SERVER_PASSWORD to enable HTTP basic auth (username defaults to opencode).
|
||||
Flags
|
||||
Flag Description
|
||||
--port Port to listen on
|
||||
--hostname Hostname to listen on
|
||||
--mdns Enable mDNS discovery
|
||||
--cors Additional browser origin(s) to allow CORS
|
||||
session
|
||||
|
||||
Manage OpenCode sessions.
|
||||
Terminal window
|
||||
|
||||
opencode session [command]
|
||||
|
||||
list
|
||||
|
||||
List all OpenCode sessions.
|
||||
Terminal window
|
||||
|
||||
opencode session list
|
||||
|
||||
Flags
|
||||
Flag Short Description
|
||||
--max-count -n Limit to N most recent sessions
|
||||
--format Output format: table or json (table)
|
||||
stats
|
||||
|
||||
Show token usage and cost statistics for your OpenCode sessions.
|
||||
Terminal window
|
||||
|
||||
opencode stats
|
||||
|
||||
Flags
|
||||
Flag Description
|
||||
--days Show stats for the last N days (all time)
|
||||
--tools Number of tools to show (all)
|
||||
--models Show model usage breakdown (hidden by default). Pass a number to show top N
|
||||
--project Filter by project (all projects, empty string: current project)
|
||||
export
|
||||
|
||||
Export session data as JSON.
|
||||
Terminal window
|
||||
|
||||
opencode export [sessionID]
|
||||
|
||||
If you don’t provide a session ID, you’ll be prompted to select from available sessions.
|
||||
import
|
||||
|
||||
Import session data from a JSON file or OpenCode share URL.
|
||||
Terminal window
|
||||
|
||||
opencode import <file>
|
||||
|
||||
You can import from a local file or an OpenCode share URL.
|
||||
Terminal window
|
||||
|
||||
opencode import session.json
|
||||
opencode import https://opncd.ai/s/abc123
|
||||
|
||||
web
|
||||
|
||||
Start a headless OpenCode server with a web interface.
|
||||
Terminal window
|
||||
|
||||
opencode web
|
||||
|
||||
This starts an HTTP server and opens a web browser to access OpenCode through a web interface. Set OPENCODE_SERVER_PASSWORD to enable HTTP basic auth (username defaults to opencode).
|
||||
Flags
|
||||
Flag Description
|
||||
--port Port to listen on
|
||||
--hostname Hostname to listen on
|
||||
--mdns Enable mDNS discovery
|
||||
--cors Additional browser origin(s) to allow CORS
|
||||
acp
|
||||
|
||||
Start an ACP (Agent Client Protocol) server.
|
||||
Terminal window
|
||||
|
||||
opencode acp
|
||||
|
||||
This command starts an ACP server that communicates via stdin/stdout using nd-JSON.
|
||||
Flags
|
||||
Flag Description
|
||||
--cwd Working directory
|
||||
--port Port to listen on
|
||||
--hostname Hostname to listen on
|
||||
uninstall
|
||||
|
||||
Uninstall OpenCode and remove all related files.
|
||||
Terminal window
|
||||
|
||||
opencode uninstall
|
||||
|
||||
Flags
|
||||
Flag Short Description
|
||||
--keep-config -c Keep configuration files
|
||||
--keep-data -d Keep session data and snapshots
|
||||
--dry-run Show what would be removed without removing
|
||||
--force -f Skip confirmation prompts
|
||||
upgrade
|
||||
|
||||
Updates opencode to the latest version or a specific version.
|
||||
Terminal window
|
||||
|
||||
opencode upgrade [target]
|
||||
|
||||
To upgrade to the latest version.
|
||||
Terminal window
|
||||
|
||||
opencode upgrade
|
||||
|
||||
To upgrade to a specific version.
|
||||
Terminal window
|
||||
|
||||
opencode upgrade v0.1.48
|
||||
|
||||
Flags
|
||||
Flag Short Description
|
||||
--method -m The installation method that was used; curl, npm, pnpm, bun, brew
|
||||
Global Flags
|
||||
|
||||
The opencode CLI takes the following global flags.
|
||||
Flag Short Description
|
||||
--help -h Display help
|
||||
--version -v Print version number
|
||||
--print-logs Print logs to stderr
|
||||
--log-level Log level (DEBUG, INFO, WARN, ERROR)
|
||||
Environment variables
|
||||
|
||||
OpenCode can be configured using environment variables.
|
||||
Variable Type Description
|
||||
OPENCODE_AUTO_SHARE boolean Automatically share sessions
|
||||
OPENCODE_GIT_BASH_PATH string Path to Git Bash executable on Windows
|
||||
OPENCODE_CONFIG string Path to config file
|
||||
OPENCODE_CONFIG_DIR string Path to config directory
|
||||
OPENCODE_CONFIG_CONTENT string Inline json config content
|
||||
OPENCODE_DISABLE_AUTOUPDATE boolean Disable automatic update checks
|
||||
OPENCODE_DISABLE_PRUNE boolean Disable pruning of old data
|
||||
OPENCODE_DISABLE_TERMINAL_TITLE boolean Disable automatic terminal title updates
|
||||
OPENCODE_PERMISSION string Inlined json permissions config
|
||||
OPENCODE_DISABLE_DEFAULT_PLUGINS boolean Disable default plugins
|
||||
OPENCODE_DISABLE_LSP_DOWNLOAD boolean Disable automatic LSP server downloads
|
||||
OPENCODE_ENABLE_EXPERIMENTAL_MODELS boolean Enable experimental models
|
||||
OPENCODE_DISABLE_AUTOCOMPACT boolean Disable automatic context compaction
|
||||
OPENCODE_DISABLE_CLAUDE_CODE boolean Disable reading from .claude (prompt + skills)
|
||||
OPENCODE_DISABLE_CLAUDE_CODE_PROMPT boolean Disable reading ~/.claude/CLAUDE.md
|
||||
OPENCODE_DISABLE_CLAUDE_CODE_SKILLS boolean Disable loading .claude/skills
|
||||
OPENCODE_DISABLE_MODELS_FETCH boolean Disable fetching models from remote sources
|
||||
OPENCODE_FAKE_VCS string Fake VCS provider for testing purposes
|
||||
OPENCODE_DISABLE_FILETIME_CHECK boolean Disable file time checking for optimization
|
||||
OPENCODE_CLIENT string Client identifier (defaults to cli)
|
||||
OPENCODE_ENABLE_EXA boolean Enable Exa web search tools
|
||||
OPENCODE_SERVER_PASSWORD string Enable basic auth for serve/web
|
||||
OPENCODE_SERVER_USERNAME string Override basic auth username (default opencode)
|
||||
OPENCODE_MODELS_URL string Custom URL for fetching models configuration
|
||||
Experimental
|
||||
|
||||
These environment variables enable experimental features that may change or be removed.
|
||||
Variable Type Description
|
||||
OPENCODE_EXPERIMENTAL boolean Enable all experimental features
|
||||
OPENCODE_EXPERIMENTAL_ICON_DISCOVERY boolean Enable icon discovery
|
||||
OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT boolean Disable copy on select in TUI
|
||||
OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS number Default timeout for bash commands in ms
|
||||
OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX number Max output tokens for LLM responses
|
||||
OPENCODE_EXPERIMENTAL_FILEWATCHER boolean Enable file watcher for entire dir
|
||||
OPENCODE_EXPERIMENTAL_OXFMT boolean Enable oxfmt formatter
|
||||
OPENCODE_EXPERIMENTAL_LSP_TOOL boolean Enable experimental LSP tool
|
||||
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER boolean Disable file watcher
|
||||
OPENCODE_EXPERIMENTAL_EXA boolean Enable experimental Exa features
|
||||
OPENCODE_EXPERIMENTAL_LSP_TY boolean Enable experimental LSP type checking
|
||||
OPENCODE_EXPERIMENTAL_MARKDOWN boolean Enable experimental markdown features
|
||||
OPENCODE_EXPERIMENTAL_PLAN_MODE boolean Enable plan mode
|
||||
168
references/opencode/opencode-server.md
Normal file
168
references/opencode/opencode-server.md
Normal file
@@ -0,0 +1,168 @@
|
||||
|
||||
Server
|
||||
|
||||
Interact with opencode server over HTTP.
|
||||
|
||||
The opencode serve command runs a headless HTTP server that exposes an OpenAPI endpoint that an opencode client can use.
|
||||
Usage
|
||||
Terminal window
|
||||
|
||||
opencode serve [--port <number>] [--hostname <string>] [--cors <origin>]
|
||||
|
||||
Options
|
||||
Flag Description Default
|
||||
--port Port to listen on 4096
|
||||
--hostname Hostname to listen on 127.0.0.1
|
||||
--mdns Enable mDNS discovery false
|
||||
--mdns-domain Custom domain name for mDNS service opencode.local
|
||||
--cors Additional browser origins to allow []
|
||||
|
||||
--cors can be passed multiple times:
|
||||
Terminal window
|
||||
|
||||
opencode serve --cors http://localhost:5173 --cors https://app.example.com
|
||||
|
||||
Authentication
|
||||
|
||||
Set OPENCODE_SERVER_PASSWORD to protect the server with HTTP basic auth. The username defaults to opencode, or set OPENCODE_SERVER_USERNAME to override it. This applies to both opencode serve and opencode web.
|
||||
Terminal window
|
||||
|
||||
OPENCODE_SERVER_PASSWORD=your-password opencode serve
|
||||
|
||||
How it works
|
||||
|
||||
When you run opencode it starts a TUI and a server. Where the TUI is the client that talks to the server. The server exposes an OpenAPI 3.1 spec endpoint. This endpoint is also used to generate an SDK.
|
||||
|
||||
Tip
|
||||
|
||||
Use the opencode server to interact with opencode programmatically.
|
||||
|
||||
This architecture lets opencode support multiple clients and allows you to interact with opencode programmatically.
|
||||
|
||||
You can run opencode serve to start a standalone server. If you have the opencode TUI running, opencode serve will start a new server.
|
||||
Connect to an existing server
|
||||
|
||||
When you start the TUI it randomly assigns a port and hostname. You can instead pass in the --hostname and --port flags. Then use this to connect to its server.
|
||||
|
||||
The /tui endpoint can be used to drive the TUI through the server. For example, you can prefill or run a prompt. This setup is used by the OpenCode IDE plugins.
|
||||
Spec
|
||||
|
||||
The server publishes an OpenAPI 3.1 spec that can be viewed at:
|
||||
|
||||
http://<hostname>:<port>/doc
|
||||
|
||||
For example, http://localhost:4096/doc. Use the spec to generate clients or inspect request and response types. Or view it in a Swagger explorer.
|
||||
APIs
|
||||
|
||||
The opencode server exposes the following APIs.
|
||||
Global
|
||||
Method Path Description Response
|
||||
GET /global/health Get server health and version { healthy: true, version: string }
|
||||
GET /global/event Get global events (SSE stream) Event stream
|
||||
Project
|
||||
Method Path Description Response
|
||||
GET /project List all projects Project[]
|
||||
GET /project/current Get the current project Project
|
||||
Path & VCS
|
||||
Method Path Description Response
|
||||
GET /path Get the current path Path
|
||||
GET /vcs Get VCS info for the current project VcsInfo
|
||||
Instance
|
||||
Method Path Description Response
|
||||
POST /instance/dispose Dispose the current instance boolean
|
||||
Config
|
||||
Method Path Description Response
|
||||
GET /config Get config info Config
|
||||
PATCH /config Update config Config
|
||||
GET /config/providers List providers and default models { providers: Provider[], default: { [key: string]: string } }
|
||||
Provider
|
||||
Method Path Description Response
|
||||
GET /provider List all providers { all: Provider[], default: {...}, connected: string[] }
|
||||
GET /provider/auth Get provider authentication methods { [providerID: string]: ProviderAuthMethod[] }
|
||||
POST /provider/{id}/oauth/authorize Authorize a provider using OAuth ProviderAuthAuthorization
|
||||
POST /provider/{id}/oauth/callback Handle OAuth callback for a provider boolean
|
||||
Sessions
|
||||
Method Path Description Notes
|
||||
GET /session List all sessions Returns Session[]
|
||||
POST /session Create a new session body: { parentID?, title? }, returns Session
|
||||
GET /session/status Get session status for all sessions Returns { [sessionID: string]: SessionStatus }
|
||||
GET /session/:id Get session details Returns Session
|
||||
DELETE /session/:id Delete a session and all its data Returns boolean
|
||||
PATCH /session/:id Update session properties body: { title? }, returns Session
|
||||
GET /session/:id/children Get a session’s child sessions Returns Session[]
|
||||
GET /session/:id/todo Get the todo list for a session Returns Todo[]
|
||||
POST /session/:id/init Analyze app and create AGENTS.md body: { messageID, providerID, modelID }, returns boolean
|
||||
POST /session/:id/fork Fork an existing session at a message body: { messageID? }, returns Session
|
||||
POST /session/:id/abort Abort a running session Returns boolean
|
||||
POST /session/:id/share Share a session Returns Session
|
||||
DELETE /session/:id/share Unshare a session Returns Session
|
||||
GET /session/:id/diff Get the diff for this session query: messageID?, returns FileDiff[]
|
||||
POST /session/:id/summarize Summarize the session body: { providerID, modelID }, returns boolean
|
||||
POST /session/:id/revert Revert a message body: { messageID, partID? }, returns boolean
|
||||
POST /session/:id/unrevert Restore all reverted messages Returns boolean
|
||||
POST /session/:id/permissions/:permissionID Respond to a permission request body: { response, remember? }, returns boolean
|
||||
Messages
|
||||
Method Path Description Notes
|
||||
GET /session/:id/message List messages in a session query: limit?, returns { info: Message, parts: Part[]}[]
|
||||
POST /session/:id/message Send a message and wait for response body: { messageID?, model?, agent?, noReply?, system?, tools?, parts }, returns { info: Message, parts: Part[]}
|
||||
GET /session/:id/message/:messageID Get message details Returns { info: Message, parts: Part[]}
|
||||
POST /session/:id/prompt_async Send a message asynchronously (no wait) body: same as /session/:id/message, returns 204 No Content
|
||||
POST /session/:id/command Execute a slash command body: { messageID?, agent?, model?, command, arguments }, returns { info: Message, parts: Part[]}
|
||||
POST /session/:id/shell Run a shell command body: { agent, model?, command }, returns { info: Message, parts: Part[]}
|
||||
Commands
|
||||
Method Path Description Response
|
||||
GET /command List all commands Command[]
|
||||
Files
|
||||
Method Path Description Response
|
||||
GET /find?pattern=<pat> Search for text in files Array of match objects with path, lines, line_number, absolute_offset, submatches
|
||||
GET /find/file?query=<q> Find files and directories by name string[] (paths)
|
||||
GET /find/symbol?query=<q> Find workspace symbols Symbol[]
|
||||
GET /file?path=<path> List files and directories FileNode[]
|
||||
GET /file/content?path=<p> Read a file FileContent
|
||||
GET /file/status Get status for tracked files File[]
|
||||
/find/file query parameters
|
||||
|
||||
query (required) — search string (fuzzy match)
|
||||
type (optional) — limit results to "file" or "directory"
|
||||
directory (optional) — override the project root for the search
|
||||
limit (optional) — max results (1–200)
|
||||
dirs (optional) — legacy flag ("false" returns only files)
|
||||
|
||||
Tools (Experimental)
|
||||
Method Path Description Response
|
||||
GET /experimental/tool/ids List all tool IDs ToolIDs
|
||||
GET /experimental/tool?provider=<p>&model=<m> List tools with JSON schemas for a model ToolList
|
||||
LSP, Formatters & MCP
|
||||
Method Path Description Response
|
||||
GET /lsp Get LSP server status LSPStatus[]
|
||||
GET /formatter Get formatter status FormatterStatus[]
|
||||
GET /mcp Get MCP server status { [name: string]: MCPStatus }
|
||||
POST /mcp Add MCP server dynamically body: { name, config }, returns MCP status object
|
||||
Agents
|
||||
Method Path Description Response
|
||||
GET /agent List all available agents Agent[]
|
||||
Logging
|
||||
Method Path Description Response
|
||||
POST /log Write log entry. Body: { service, level, message, extra? } boolean
|
||||
TUI
|
||||
Method Path Description Response
|
||||
POST /tui/append-prompt Append text to the prompt boolean
|
||||
POST /tui/open-help Open the help dialog boolean
|
||||
POST /tui/open-sessions Open the session selector boolean
|
||||
POST /tui/open-themes Open the theme selector boolean
|
||||
POST /tui/open-models Open the model selector boolean
|
||||
POST /tui/submit-prompt Submit the current prompt boolean
|
||||
POST /tui/clear-prompt Clear the prompt boolean
|
||||
POST /tui/execute-command Execute a command ({ command }) boolean
|
||||
POST /tui/show-toast Show toast ({ title?, message, variant }) boolean
|
||||
GET /tui/control/next Wait for the next control request Control request object
|
||||
POST /tui/control/response Respond to a control request ({ body }) boolean
|
||||
Auth
|
||||
Method Path Description Response
|
||||
PUT /auth/:id Set authentication credentials. Body must match provider schema boolean
|
||||
Events
|
||||
Method Path Description Response
|
||||
GET /event Server-sent events stream. First event is server.connected, then bus events Server-sent events stream
|
||||
Docs
|
||||
Method Path Description Response
|
||||
GET /doc OpenAPI 3.1 specification HTML page with OpenAPI spec
|
||||
324
references/opencode/sdk.md
Normal file
324
references/opencode/sdk.md
Normal file
@@ -0,0 +1,324 @@
|
||||
|
||||
SDK
|
||||
|
||||
Type-safe JS client for opencode server.
|
||||
|
||||
The opencode JS/TS SDK provides a type-safe client for interacting with the server. Use it to build integrations and control opencode programmatically.
|
||||
|
||||
Learn more about how the server works. For examples, check out the projects built by the community.
|
||||
Install
|
||||
|
||||
Install the SDK from npm:
|
||||
Terminal window
|
||||
|
||||
npm install @opencode-ai/sdk
|
||||
|
||||
Create client
|
||||
|
||||
Create an instance of opencode:
|
||||
|
||||
import { createOpencode } from "@opencode-ai/sdk"
|
||||
|
||||
const { client } = await createOpencode()
|
||||
|
||||
This starts both a server and a client
|
||||
Options
|
||||
Option Type Description Default
|
||||
hostname string Server hostname 127.0.0.1
|
||||
port number Server port 4096
|
||||
signal AbortSignal Abort signal for cancellation undefined
|
||||
timeout number Timeout in ms for server start 5000
|
||||
config Config Configuration object {}
|
||||
Config
|
||||
|
||||
You can pass a configuration object to customize behavior. The instance still picks up your opencode.json, but you can override or add configuration inline:
|
||||
|
||||
import { createOpencode } from "@opencode-ai/sdk"
|
||||
|
||||
const opencode = await createOpencode({
|
||||
hostname: "127.0.0.1",
|
||||
port: 4096,
|
||||
config: {
|
||||
model: "anthropic/claude-3-5-sonnet-20241022",
|
||||
},
|
||||
})
|
||||
|
||||
console.log(`Server running at ${opencode.server.url}`)
|
||||
|
||||
opencode.server.close()
|
||||
|
||||
Client only
|
||||
|
||||
If you already have a running instance of opencode, you can create a client instance to connect to it:
|
||||
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk"
|
||||
|
||||
const client = createOpencodeClient({
|
||||
baseUrl: "http://localhost:4096",
|
||||
})
|
||||
|
||||
Options
|
||||
Option Type Description Default
|
||||
baseUrl string URL of the server http://localhost:4096
|
||||
fetch function Custom fetch implementation globalThis.fetch
|
||||
parseAs string Response parsing method auto
|
||||
responseStyle string Return style: data or fields fields
|
||||
throwOnError boolean Throw errors instead of return false
|
||||
Types
|
||||
|
||||
The SDK includes TypeScript definitions for all API types. Import them directly:
|
||||
|
||||
import type { Session, Message, Part } from "@opencode-ai/sdk"
|
||||
|
||||
All types are generated from the server’s OpenAPI specification and available in the types file.
|
||||
Errors
|
||||
|
||||
The SDK can throw errors that you can catch and handle:
|
||||
|
||||
try {
|
||||
await client.session.get({ path: { id: "invalid-id" } })
|
||||
} catch (error) {
|
||||
console.error("Failed to get session:", (error as Error).message)
|
||||
}
|
||||
|
||||
Structured Output
|
||||
|
||||
You can request structured JSON output from the model by specifying an format with a JSON schema. The model will use a StructuredOutput tool to return validated JSON matching your schema.
|
||||
Basic Usage
|
||||
|
||||
const result = await client.session.prompt({
|
||||
path: { id: sessionId },
|
||||
body: {
|
||||
parts: [{ type: "text", text: "Research Anthropic and provide company info" }],
|
||||
format: {
|
||||
type: "json_schema",
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
company: { type: "string", description: "Company name" },
|
||||
founded: { type: "number", description: "Year founded" },
|
||||
products: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
description: "Main products",
|
||||
},
|
||||
},
|
||||
required: ["company", "founded"],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Access the structured output
|
||||
console.log(result.data.info.structured_output)
|
||||
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
|
||||
|
||||
Output Format Types
|
||||
Type Description
|
||||
text Default. Standard text response (no structured output)
|
||||
json_schema Returns validated JSON matching the provided schema
|
||||
JSON Schema Format
|
||||
|
||||
When using type: 'json_schema', provide:
|
||||
Field Type Description
|
||||
type 'json_schema' Required. Specifies JSON schema mode
|
||||
schema object Required. JSON Schema object defining the output structure
|
||||
retryCount number Optional. Number of validation retries (default: 2)
|
||||
Error Handling
|
||||
|
||||
If the model fails to produce valid structured output after all retries, the response will include a StructuredOutputError:
|
||||
|
||||
if (result.data.info.error?.name === "StructuredOutputError") {
|
||||
console.error("Failed to produce structured output:", result.data.info.error.message)
|
||||
console.error("Attempts:", result.data.info.error.retries)
|
||||
}
|
||||
|
||||
Best Practices
|
||||
|
||||
Provide clear descriptions in your schema properties to help the model understand what data to extract
|
||||
Use required to specify which fields must be present
|
||||
Keep schemas focused - complex nested schemas may be harder for the model to fill correctly
|
||||
Set appropriate retryCount - increase for complex schemas, decrease for simple ones
|
||||
|
||||
APIs
|
||||
|
||||
The SDK exposes all server APIs through a type-safe client.
|
||||
Global
|
||||
Method Description Response
|
||||
global.health() Check server health and version { healthy: true, version: string }
|
||||
Examples
|
||||
|
||||
const health = await client.global.health()
|
||||
console.log(health.data.version)
|
||||
|
||||
App
|
||||
Method Description Response
|
||||
app.log() Write a log entry boolean
|
||||
app.agents() List all available agents Agent[]
|
||||
Examples
|
||||
|
||||
// Write a log entry
|
||||
await client.app.log({
|
||||
body: {
|
||||
service: "my-app",
|
||||
level: "info",
|
||||
message: "Operation completed",
|
||||
},
|
||||
})
|
||||
|
||||
// List available agents
|
||||
const agents = await client.app.agents()
|
||||
|
||||
Project
|
||||
Method Description Response
|
||||
project.list() List all projects Project[]
|
||||
project.current() Get current project Project
|
||||
Examples
|
||||
|
||||
// List all projects
|
||||
const projects = await client.project.list()
|
||||
|
||||
// Get current project
|
||||
const currentProject = await client.project.current()
|
||||
|
||||
Path
|
||||
Method Description Response
|
||||
path.get() Get current path Path
|
||||
Examples
|
||||
|
||||
// Get current path information
|
||||
const pathInfo = await client.path.get()
|
||||
|
||||
Config
|
||||
Method Description Response
|
||||
config.get() Get config info Config
|
||||
config.providers() List providers and default models { providers: Provider[], default: { [key: string]: string } }
|
||||
Examples
|
||||
|
||||
const config = await client.config.get()
|
||||
|
||||
const { providers, default: defaults } = await client.config.providers()
|
||||
|
||||
Sessions
|
||||
Method Description Notes
|
||||
session.list() List sessions Returns Session[]
|
||||
session.get({ path }) Get session Returns Session
|
||||
session.children({ path }) List child sessions Returns Session[]
|
||||
session.create({ body }) Create session Returns Session
|
||||
session.delete({ path }) Delete session Returns boolean
|
||||
session.update({ path, body }) Update session properties Returns Session
|
||||
session.init({ path, body }) Analyze app and create AGENTS.md Returns boolean
|
||||
session.abort({ path }) Abort a running session Returns boolean
|
||||
session.share({ path }) Share session Returns Session
|
||||
session.unshare({ path }) Unshare session Returns Session
|
||||
session.summarize({ path, body }) Summarize session Returns boolean
|
||||
session.messages({ path }) List messages in a session Returns { info: Message, parts: Part[]}[]
|
||||
session.message({ path }) Get message details Returns { info: Message, parts: Part[]}
|
||||
session.prompt({ path, body }) Send prompt message body.noReply: true returns UserMessage (context only). Default returns AssistantMessage with AI response. Supports body.outputFormat for structured output
|
||||
session.command({ path, body }) Send command to session Returns { info: AssistantMessage, parts: Part[]}
|
||||
session.shell({ path, body }) Run a shell command Returns AssistantMessage
|
||||
session.revert({ path, body }) Revert a message Returns Session
|
||||
session.unrevert({ path }) Restore reverted messages Returns Session
|
||||
postSessionByIdPermissionsByPermissionId({ path, body }) Respond to a permission request Returns boolean
|
||||
Examples
|
||||
|
||||
// Create and manage sessions
|
||||
const session = await client.session.create({
|
||||
body: { title: "My session" },
|
||||
})
|
||||
|
||||
const sessions = await client.session.list()
|
||||
|
||||
// Send a prompt message
|
||||
const result = await client.session.prompt({
|
||||
path: { id: session.id },
|
||||
body: {
|
||||
model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" },
|
||||
parts: [{ type: "text", text: "Hello!" }],
|
||||
},
|
||||
})
|
||||
|
||||
// Inject context without triggering AI response (useful for plugins)
|
||||
await client.session.prompt({
|
||||
path: { id: session.id },
|
||||
body: {
|
||||
noReply: true,
|
||||
parts: [{ type: "text", text: "You are a helpful assistant." }],
|
||||
},
|
||||
})
|
||||
|
||||
Files
|
||||
Method Description Response
|
||||
find.text({ query }) Search for text in files Array of match objects with path, lines, line_number, absolute_offset, submatches
|
||||
find.files({ query }) Find files and directories by name string[] (paths)
|
||||
find.symbols({ query }) Find workspace symbols Symbol[]
|
||||
file.read({ query }) Read a file { type: "raw" | "patch", content: string }
|
||||
file.status({ query? }) Get status for tracked files File[]
|
||||
|
||||
find.files supports a few optional query fields:
|
||||
|
||||
type: "file" or "directory"
|
||||
directory: override the project root for the search
|
||||
limit: max results (1–200)
|
||||
|
||||
Examples
|
||||
|
||||
// Search and read files
|
||||
const textResults = await client.find.text({
|
||||
query: { pattern: "function.*opencode" },
|
||||
})
|
||||
|
||||
const files = await client.find.files({
|
||||
query: { query: "*.ts", type: "file" },
|
||||
})
|
||||
|
||||
const directories = await client.find.files({
|
||||
query: { query: "packages", type: "directory", limit: 20 },
|
||||
})
|
||||
|
||||
const content = await client.file.read({
|
||||
query: { path: "src/index.ts" },
|
||||
})
|
||||
|
||||
TUI
|
||||
Method Description Response
|
||||
tui.appendPrompt({ body }) Append text to the prompt boolean
|
||||
tui.openHelp() Open the help dialog boolean
|
||||
tui.openSessions() Open the session selector boolean
|
||||
tui.openThemes() Open the theme selector boolean
|
||||
tui.openModels() Open the model selector boolean
|
||||
tui.submitPrompt() Submit the current prompt boolean
|
||||
tui.clearPrompt() Clear the prompt boolean
|
||||
tui.executeCommand({ body }) Execute a command boolean
|
||||
tui.showToast({ body }) Show toast notification boolean
|
||||
Examples
|
||||
|
||||
// Control TUI interface
|
||||
await client.tui.appendPrompt({
|
||||
body: { text: "Add this to prompt" },
|
||||
})
|
||||
|
||||
await client.tui.showToast({
|
||||
body: { message: "Task completed", variant: "success" },
|
||||
})
|
||||
|
||||
Auth
|
||||
Method Description Response
|
||||
auth.set({ ... }) Set authentication credentials boolean
|
||||
Examples
|
||||
|
||||
await client.auth.set({
|
||||
path: { id: "anthropic" },
|
||||
body: { type: "api", key: "your-api-key" },
|
||||
})
|
||||
|
||||
Events
|
||||
Method Description Response
|
||||
event.subscribe() Server-sent events stream Server-sent events stream
|
||||
Examples
|
||||
|
||||
// Listen to real-time events
|
||||
const events = await client.event.subscribe()
|
||||
for await (const event of events.stream) {
|
||||
console.log("Event:", event.type, event.properties)
|
||||
}
|
||||
Reference in New Issue
Block a user