日本語
ドキュメント
SDK

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()

これにより、サーバーとクライアントの両方が起動します。

オプション

オプション型説明デフォルト
hostnamestringサーバーのホスト名127.0.0.1
portnumberサーバーのポート4096
signalAbortSignalキャンセル用の中止シグナルundefined
timeoutnumberサーバー起動のタイムアウト(ミリ秒)5000
configConfig設定オブジェクト{}

設定

動作をカスタマイズするために設定オブジェクトを渡すことができます。インスタンスは引き続き 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",
})

オプション

オプション型説明デフォルト
baseUrlstringサーバーの URLhttp://localhost:4096
fetchfunctionカスタム fetch 実装globalThis.fetch
parseAsstringレスポンスの解析方法auto
responseStylestring戻り値のスタイル:data または fieldsfields
throwOnErrorboolean戻り値の代わりにエラーをスロー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)
}

構造化出力(SDK 1.18.31)

この例では @opencode-ai/sdk/v2 を使います。このページの他の例は従来のルートエクスポートと path/body 形式を使います。

起動済みのローカル v1 サーバー(opencode serve)に接続します。先にプロバイダーとモデルを設定してください。回答の生成にはプロバイダーの料金が発生する場合があります。

import { createOpencodeClient } from "@opencode-ai/sdk/v2"
 
const client = createOpencodeClient({ baseUrl: "http://localhost:4096" })
const session = await client.session.create({ title: "Schema example" }, { throwOnError: true })
const result = await client.session.prompt({
  sessionID: session.data.id,
  parts: [{ type: "text", text: "Return the name and language of this project." }],
  format: {
    type: "json_schema",
    schema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Project name" },
        language: { type: "string", description: "Primary programming language" },
      },
      required: ["name", "language"],
      additionalProperties: false,
    },
    retryCount: 2,
  },
}, { throwOnError: true })
 
const info = result.data.info
if (info.error) {
  if (info.error.name === "StructuredOutputError") {
    console.error(info.error.data.message, info.error.data.retries)
  } else {
    console.error(info.error)
  }
} else {
  console.log(info.structured)
}

format は text または json_schema を指定します。JSON 出力には schema に JSON Schema を渡します。retryCount は検証の再試行回数で、既定値は 2 です。必須項目を required で指定し、各項目を明確に説明して、スキーマを簡潔に保ちます。

throwOnError を有効にしない場合、通信や API の失敗は error に返されます。モデルの失敗は別途 info.error で確認します。StructuredOutputError の詳細は error.data.message と error.data.retries、成功したデータは info.structured にあります。

この例は @opencode-ai/sdk v1.18.31 を使用します。インターフェースの定義は SDK のソース (opens in a new tab)を参照してください。


API

SDK は型安全なクライアントを通じてすべてのサーバー API を公開します。


グローバル

メソッド説明レスポンス
global.health()サーバーの健全性とバージョンを確認{ healthy: true, version: string }

例

const health = await client.global.health()
console.log(health.data.version)

アプリ

メソッド説明レスポンス
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.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.get()現在のパスを取得Path (opens in a new tab)

例

// 現在のパス情報を取得
const pathInfo = await client.path.get()

設定

メソッド説明レスポンス
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()

セッション

メソッド説明備考
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." }],
  },
})

ファイル

メソッド説明レスポンス
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.set({ ... })認証資格情報を設定boolean

例

await client.auth.set({
  path: { id: "anthropic" },
  body: { type: "api", key: "your-api-key" },
})

イベント

メソッド説明レスポンス
event.subscribe()サーバー送信イベントストリームサーバー送信イベントストリーム

例

// リアルタイムイベントをリッスン
const events = await client.event.subscribe()
for await (const event of events.stream) {
  console.log("Event:", event.type, event.properties)
}

文書の出典(MIT)