軟體開發工具包
opencode 服务器的类型不同于安全 JS 客户端。
opencode JS/TS SDK 提供类型其他安全的客户端用于与服务器交互。 使用它以程序设计方式构建集成和控制opencode。
了解更多关于服务器如何工作的。例如,查看社区构建的projects。
安装
从npm安装SDK:
npm install @opencode-ai/sdk建立客戶端
创建opencode的示例项:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()这会同時启动服务器和客戶端
選項
| 選項 | 型別 | 描述 | 默认 |
|---|---|---|---|
hostname | string | 服务器主机名 | 127.0.0.1 |
port | number | 服务器埠 | 4096 |
signal | AbortSignal | 取消的中止讯号 | undefined |
timeout | number | 服务器启动超时(以毫秒为单位) | 5000 |
config | 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()仅限客戶
如果您已经有 opencode 的正在执行示例项,则可以创建一个客户端示例项来连线到它:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({ baseUrl: "http://localhost:4096",})選項
| 選項 | 型別 | 描述 | 默认 |
|---|---|---|---|
baseUrl | string | 服务器的 URL | http://localhost:4096 |
fetch | function | 习俗获取实现 | globalThis.fetch |
parseAs | string | 响应解析方法 | auto |
responseStyle | string | 返回样式:data 或 fields | fields |
throwOnError | boolean | 掷骰错误而不是返回 | false |
型別
SDK 包括所有 API 型以外的 TypeScript 定义。直接汇入其中:
import type { Session, Message, Part } from "@opencode-ai/sdk"所有型別均根據服务器的 OpenAPI 規範生成,并可在 型別文件 中找到。
错误
SDK 可能会丢掷错误,您可以捕获并处理这些错误:
try { await client.session.get({ path: { id: "invalid-id" } })} catch (error) { console.error("Failed to get session:", (error as Error).message)}蜜蜂
SDK跨越型别安全客户端公开所有服务器API。
全球的
| 方法 | 描述 | 回应 |
|---|---|---|
global.health() | 检查服务器健康状况和版本 | { healthy: true, version: string } |
示例
const health = await client.global.health()console.log(health.data.version)应用程序
| 方法 | 描述 | 回应 |
|---|---|---|
app.log() | 登录日志 | boolean |
app.agents() | 列出所有可用的代理 | 代理[] |
示例
// Write a log entryawait client.app.log({ body: { service: "my-app", level: "info", message: "Operation completed", },})
// List available agentsconst agents = await client.app.agents()专案
| 方法 | 描述 | 回应 |
|---|---|---|
project.list() | 列出所有专案 | 专案[] |
project.current() | 获取当前专案 | 专案 |
示例
// List all projectsconst projects = await client.project.list()
// Get current projectconst currentProject = await client.project.current()小路
| 方法 | 描述 | 回应 |
|---|---|---|
path.get() | 获取当前路徑 | 路徑 |
示例
// Get current path informationconst pathInfo = await client.path.get()配置
| 方法 | 描述 | 回应 |
|---|---|---|
config.get() | 获取配置資訊 | 配置 |
config.providers() | 列出提供商和默认模型 | { providers: 提供商[], default: { [key: string]: string } } |
示例
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()会话
| 方法 | 描述 | 筆記 |
|---|---|---|
session.list() | 列出会话 | 返回 Session[] |
session.get({ path }) | 获取会话 | 返回 会话 |
session.children({ path }) | 列出子会话 | 返回 Session[] |
session.create({ body }) | 建立会话 | 返回 会话 |
session.delete({ path }) | 离开会话 | 返回boolean |
session.update({ path, body }) | 更新会话屬性 | 返回 会话 |
session.init({ path, body }) | Analyze app and create AGENTS.md | Returns boolean |
session.abort({ path }) | 中止正在执行的会话 | 返回boolean |
session.share({ path }) | 分享会 | 返回 会话 |
session.unshare({ path }) | 取消共享会话 | 返回 会话 |
session.summarize({ path, body }) | 会议总结 | 返回boolean |
session.messages({ path }) | 列出会话中的消息 | 返回 { info: 消息, parts: 部分[]}[] |
session.message({ path }) | 获取消息详情 | 返回 { info: 消息, parts: 部分[]} |
session.prompt({ path, body }) | 发送提示資訊 | body.noReply: true 返回 UserMessage(仅限上下文)。默认返回 AssistantMessage 以及 AI 響应 |
session.command({ path, body }) | 向会话发送命令 | 返回 { info: AssistantMessage, parts: 部分[]} |
session.shell({ path, body }) | 执行 shell 命令 | 返回 AssistantMessage |
session.revert({ path, body }) | 回复消息 | 返回 会话 |
session.unrevert({ path }) | 恢复已恢复的消息 | 返回 会话 |
postSessionByIdPermissionsByPermissionId({ path, body }) | 回复许可权限请求 | 返回boolean |
示例
// Create and manage sessionsconst session = await client.session.create({ body: { title: "My session" },})
const sessions = await client.session.list()
// Send a prompt messageconst 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." }], },})文件
| 方法 | 描述 | 回应 |
|---|---|---|
find.text({ query }) | 搜索档案中文字 | 具有 path、lines、line_number、absolute_offset、submatches 的匹配对象数组 |
find.files({ query }) | 按名称查询档案和目录 | string[](路径) |
find.symbols({ query }) | 查询工作区符號 | 符號[] |
file.read({ query }) | 读取档案 | { type: "raw" | "patch", content: string } |
file.status({ query? }) | 获取跟蹤文件的狀態 | 文件[] |
find.files 支持一些可选的查询栏位:
type:"file"或"directory"directory:覆盖搜索的专案根目录limit:最大结果 (1–200)
示例
// Search and read filesconst 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
| 方法 | 描述 | 回应 |
|---|---|---|
tui.appendPrompt({ body }) | 将文字附加到提示 | boolean |
tui.openHelp() | 开启帮助对话方块 | boolean |
tui.openSessions() | 开启会话选择器 | boolean |
tui.openThemes() | 开启主题选择器 | boolean |
tui.openModels() | 开启模型选择器 | boolean |
tui.submitPrompt() | 提交当前提示 | boolean |
tui.clearPrompt() | 清除提示 | boolean |
tui.executeCommand({ body }) | 执行命令 | boolean |
tui.showToast({ body }) | 显示吐司通知 | boolean |
示例
// Control TUI interfaceawait client.tui.appendPrompt({ body: { text: "Add this to prompt" },})
await client.tui.showToast({ body: { message: "Task completed", variant: "success" },})授權
| 方法 | 描述 | 回应 |
|---|---|---|
auth.set({ ... }) | 设定身份验证凭据 | boolean |
示例
await client.auth.set({ path: { id: "anthropic" }, body: { type: "api", key: "your-api-key" },})活动
| 方法 | 描述 | 回应 |
|---|---|---|
event.subscribe() | 服务器传送的事件流 | 服务器传送的事件流 |
示例
// Listen to real-time eventsconst events = await client.event.subscribe()for await (const event of events.stream) { console.log("Event:", event.type, event.properties)}