SDK
opencode サーバー用の型安全な JS クライアント。
opencode JS/TS SDK は、サーバーとやり取りするための型安全なクライアントを提供します。統合を構築し、opencode をプログラムで制御するために使用します。
サーバーの動作について詳しく学ぶ。コミュニティが構築したプロジェクトの例をご覧ください。
インストール
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 | 設定オブジェクト | {} |
設定
動作をカスタマイズするために設定オブジェクトを渡すことができます。インスタンスは引き続き opencode.json を読み取りますが、インラインで設定を上書きまたは追加できます:
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 | カスタム fetch 実装 | 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 仕様から生成され、型ファイル (opens in a new tab)で利用可能です。
エラー
SDK はエラーをスローする可能性があり、キャッチして処理できます:
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}API
SDK は型安全なクライアントを通じてすべてのサーバー API を公開します。
Global
| メソッド | 説明 | レスポンス |
|---|---|---|
global.health() | サーバーの健全性とバージョンを確認 | { healthy: true, version: string } |
例
const health = await client.global.health()
console.log(health.data.version)App
| メソッド | 説明 | レスポンス |
|---|---|---|
app.log() | ログエントリを書き込む | boolean |
app.agents() | 利用可能なすべてのエージェントを一覧表示 | Agent[] (opens in a new tab) |
例
// ログエントリを書き込む
await client.app.log({
body: {
service: "my-app",
level: "info",
message: "Operation completed",
},
})
// 利用可能なエージェントを一覧表示
const agents = await client.app.agents()Project
| メソッド | 説明 | レスポンス |
|---|---|---|
project.list() | すべてのプロジェクトを一覧表示 | Project[] (opens in a new tab) |
project.current() | 現在のプロジェクトを取得 | Project (opens in a new tab) |
例
// すべてのプロジェクトを一覧表示
const projects = await client.project.list()
// 現在のプロジェクトを取得
const currentProject = await client.project.current()Path
| メソッド | 説明 | レスポンス |
|---|---|---|
path.get() | 現在のパスを取得 | Path (opens in a new tab) |
例
// 現在のパス情報を取得
const pathInfo = await client.path.get()Config
| メソッド | 説明 | レスポンス |
|---|---|---|
config.get() | 設定情報を取得 | Config (opens in a new tab) |
config.providers() | プロバイダーとデフォルトモデルを一覧表示 | { providers: Provider[] (opens in a new tab), default: { [key: string]: string } } |
例
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()Sessions
| メソッド | 説明 | 備考 |
|---|---|---|
session.list() | セッションを一覧表示 | Session[] (opens in a new tab) を返す |
session.get({ path }) | セッションを取得 | Session (opens in a new tab) を返す |
session.children({ path }) | 子セッションを一覧表示 | Session[] (opens in a new tab) を返す |
session.create({ body }) | セッションを作成 | Session (opens in a new tab) を返す |
session.delete({ path }) | セッションを削除 | boolean を返す |
session.update({ path, body }) | セッションのプロパティを更新 | Session (opens in a new tab) を返す |
session.init({ path, body }) | アプリを分析して AGENTS.md を作成 | boolean を返す |
session.abort({ path }) | 実行中のセッションを中止 | boolean を返す |
session.share({ path }) | セッションを共有 | Session (opens in a new tab) を返す |
session.unshare({ path }) | セッションの共有を解除 | Session (opens in a new tab) を返す |
session.summarize({ path, body }) | セッションを要約 | boolean を返す |
session.messages({ path }) | セッション内のメッセージを一覧表示 | { info: Message (opens in a new tab), parts: Part[] (opens in a new tab)}[] を返す |
session.message({ path }) | メッセージの詳細を取得 | { info: Message (opens in a new tab), parts: Part[] (opens in a new tab)} を返す |
session.prompt({ path, body }) | プロンプトメッセージを送信 | body.noReply: true は UserMessage を返す(コンテキストのみ)。デフォルトは AI レスポンス付きの AssistantMessage (opens in a new tab) を返す |
session.command({ path, body }) | セッションにコマンドを送信 | { info: AssistantMessage (opens in a new tab), parts: Part[] (opens in a new tab)} を返す |
session.shell({ path, body }) | シェルコマンドを実行 | AssistantMessage (opens in a new tab) を返す |
session.revert({ path, body }) | メッセージを元に戻す | Session (opens in a new tab) を返す |
session.unrevert({ path }) | 元に戻したメッセージを復元 | Session (opens in a new tab) を返す |
postSessionByIdPermissionsByPermissionId({ path, body }) | 権限リクエストに応答 | boolean を返す |
例
// セッションの作成と管理
const session = await client.session.create({
body: { title: "My session" },
})
const sessions = await client.session.list()
// プロンプトメッセージを送信
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!" }],
},
})
// AI レスポンスをトリガーせずにコンテキストを注入(プラグインに便利)
await client.session.prompt({
path: { id: session.id },
body: {
noReply: true,
parts: [{ type: "text", text: "You are a helpful assistant." }],
},
})Files
| メソッド | 説明 | レスポンス |
|---|---|---|
find.text({ query }) | ファイル内のテキストを検索 | path、lines、line_number、absolute_offset、submatches を含むマッチオブジェクトの配列 |
find.files({ query }) | 名前でファイルとディレクトリを検索 | string[](パス) |
find.symbols({ query }) | ワークスペースシンボルを検索 | Symbol[] (opens in a new tab) |
file.read({ query }) | ファイルを読み取る | { type: "raw" | "patch", content: string } |
file.status({ query? }) | 追跡されたファイルのステータスを取得 | File[] (opens in a new tab) |
find.files はいくつかのオプションのクエリフィールドをサポートしています:
type:"file"または"directory"directory:検索のプロジェクトルートを上書きlimit:最大結果数(1-200)
例
// ファイルの検索と読み取り
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
| メソッド | 説明 | レスポンス |
|---|---|---|
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 |
例
// TUI インターフェースを制御
await client.tui.appendPrompt({
body: { text: "Add this to prompt" },
})
await client.tui.showToast({
body: { message: "Task completed", variant: "success" },
})Auth
| メソッド | 説明 | レスポンス |
|---|---|---|
auth.set({ ... }) | 認証資格情報を設定 | boolean |
例
await client.auth.set({
path: { id: "anthropic" },
body: { type: "api", key: "your-api-key" },
})Events
| メソッド | 説明 | レスポンス |
|---|---|---|
event.subscribe() | サーバー送信イベントストリーム | サーバー送信イベントストリーム |
例
// リアルタイムイベントをリッスン
const events = await client.event.subscribe()
for await (const event of events.stream) {
console.log("Event:", event.type, event.properties)
}