SDK
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 | キャンセル用の Abort シグナル | undefined |
timeout | number | サーバー起動のタイムアウト (ms) | 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 仕様から生成され、types ファイル で参照できます。
エラー
SDK はエラーをスローすることがあるため、それらをキャッチして処理できます。
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}
構造化出力
JSON スキーマを持つ format を指定することで、モデルから構造化された JSON 出力を要求できます。モデルは StructuredOutput ツールを使用して、スキーマに合致する検証済みの JSON を返します。
基本的な使用方法
const result = await client.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: "text", text: "Anthropic について調査し、会社情報を提供してください" }],
format: {
type: "json_schema",
schema: {
type: "object",
properties: {
company: { type: "string", description: "会社名" },
founded: { type: "number", description: "設立年" },
products: {
type: "array",
items: { type: "string" },
description: "主要製品",
},
},
required: ["company", "founded"],
},
},
},
})
// 構造化出力にアクセス
console.log(result.data.info.structured_output)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
出力フォーマットの種類
| 型 | 説明 |
|---|---|
text | デフォルト。標準的なテキスト応答 (構造化出力なし) |
json_schema | 提供されたスキーマに合致する検証済みの JSON を返します |
JSON スキーマ形式
type: 'json_schema' を使用する場合、次の項目を指定します。
| フィールド | 型 | 説明 |
|---|---|---|
type | 'json_schema' | 必須。JSON スキーマモードを指定します |
schema | object | 必須。出力構造を定義する JSON Schema オブジェクト |
retryCount | number | 任意。検証の再試行回数 (デフォルト:2) |
エラー処理
すべての再試行後にモデルが有効な構造化出力を生成できなかった場合、レスポンスには 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)
}
ベストプラクティス
- スキーマのプロパティに 明確な説明を記載する ことで、モデルが抽出するデータを理解できるようにします
- どのフィールドが必須かを指定するために
requiredを使用します - スキーマを集中させる — 複雑なネストされたスキーマは、モデルが正しく埋められない場合があります
- 適切な
retryCountを設定する — 複雑なスキーマでは増やし、単純なものでは減らします
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[] |
例
// ログエントリを書き込み
await client.app.log({
body: {
service: "my-app",
level: "info",
message: "Operation completed",
},
})
// 利用可能なエージェントを列挙
const agents = await client.app.agents()
Project
| メソッド | 説明 | レスポンス |
|---|---|---|
project.list() | すべてのプロジェクトを列挙 | Project[] |
project.current() | 現在のプロジェクトを取得 | Project |
例
// すべてのプロジェクトを列挙
const projects = await client.project.list()
// 現在のプロジェクトを取得
const currentProject = await client.project.current()
Path
| メソッド | 説明 | レスポンス |
|---|---|---|
path.get() | 現在のパスを取得 | Path |
例
// 現在のパス情報を取得
const pathInfo = await client.path.get()
Config
| メソッド | 説明 | レスポンス |
|---|---|---|
config.get() | 設定情報を取得 | Config |
config.providers() | プロバイダとデフォルトモデルを列挙 | { providers: Provider[], default: { [key: string]: string } } |
例
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()
Sessions
| メソッド | 説明 | 注記 |
|---|---|---|
session.list() | セッションを列挙 | Session[] を返す |
session.get({ path }) | セッションを取得 | Session を返す |
session.children({ path }) | 子セッションを列挙 | Session[] を返す |
session.create({ body }) | セッションを作成 | Session を返す |
session.delete({ path }) | セッションを削除 | boolean を返す |
session.update({ path, body }) | セッションのプロパティを更新 | Session を返す |
session.init({ path, body }) | アプリを分析して AGENTS.md を作成 | boolean を返す |
session.abort({ path }) | 実行中のセッションを中断 | boolean を返す |
session.share({ path }) | セッションを共有 | Session を返す |
session.unshare({ path }) | セッションの共有を解除 | Session を返す |
session.summarize({ path, body }) | セッションを要約 | boolean を返す |
session.messages({ path }) | セッション内のメッセージを列挙 | { info: Message, parts: Part[] }[] を返す |
session.message({ path }) | メッセージの詳細を取得 | { info: Message, parts: Part[] } を返す |
session.prompt({ path, body }) | プロンプトメッセージを送信 | body.noReply: true は UserMessage (コンテキストのみ) を返します。デフォルトは AssistantMessage を返し、AI 応答を含みます。構造化出力 用の body.outputFormat をサポートします |
session.command({ path, body }) | セッションにコマンドを送信 | { info: AssistantMessage, parts: Part[] } を返す |
session.shell({ path, body }) | シェルコマンドを実行 | AssistantMessage を返す |
session.revert({ path, body }) | メッセージを取り消す | Session を返す |
session.unrevert({ path }) | 取り消したメッセージを復元 | Session を返す |
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[] |
file.read({ query }) | ファイルを読み込む | { type: "raw" | "patch", content: string } |
file.status({ query? }) | 追跡対象ファイルのステータスを取得 | File[] |
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)
}