İçeriğe geç

SDK

opencode sunucusu için type-safe JS istemcisi.

opencode JS/TS SDK, sunucu ile etkileşmek için type-safe bir istemci sağlar. opencode’u programatik olarak kontrol etmek ve entegrasyonlar oluşturmak için kullanabilirsiniz.

Sunucu sayfasında nasıl çalıştığını görebilir, örnekler için topluluğun oluşturduğu projeler bölümüne bakabilirsiniz.


Kurulum

SDK’yı npm’den yükleyin:

Terminal window
npm install @opencode-ai/sdk

İstemci Oluşturma

Bir opencode örneği oluşturun:

import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()

Bu, hem bir sunucu hem de bir istemci başlatır

Seçenekler

SeçenekTipAçıklamaVarsayılan
hostnamestringSunucu ana bilgisayar adı127.0.0.1
portnumberSunucu bağlantı noktası4096
signalAbortSignalİptal için durdurma sinyaliundefined
timeoutnumberSunucu başlatma için ms cinsinden zaman aşımı5000
configConfigYapılandırma nesnesi{}

Yapılandırma

Davranışı özelleştirmek için bir yapılandırma nesnesi iletebilirsiniz. Örnek yine de opencode.json dosyanızı alır, ancak yapılandırmayı satır içi olarak geçersiz kılabilir veya ekleyebilirsiniz:

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

Yalnızca istemci

Halihazırda çalışan bir opencode örneğiniz varsa, ona bağlanmak için bir istemci örneği oluşturabilirsiniz:

import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({
baseUrl: "http://localhost:4096",
})

Seçenekler

SeçenekTipAçıklamaVarsayılan
baseUrlstringSunucunun URL’sihttp://localhost:4096
fetchfunctionÖzel fetch uygulamasıglobalThis.fetch
parseAsstringYanıt ayrıştırma yöntemiauto
responseStylestringDönüş stili: data veya fieldsfields
throwOnErrorbooleanDönüş yerine hata fırlatfalse

Türler

SDK, tüm API türleri için TypeScript tanımlarını içerir. Bunları doğrudan içe aktarın:

import type { Session, Message, Part } from "@opencode-ai/sdk"

Tüm tipler, sunucunun OpenAPI spesifikasyonundan oluşturulur ve tipler dosyasında mevcuttur.


Hatalar

SDK, yakalayabileceğiniz ve işleyebileceğiniz hatalar fırlatabilir:

try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}

API’ler

SDK, tüm sunucu API’lerini type-safe bir istemci aracılığıyla sunar.


Global

YöntemAçıklamaYanıt
global.health()Sunucu sağlığını ve sürümünü kontrol et{ healthy: true, version: string }

Örnekler

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

App

YöntemAçıklamaYanıt
app.log()Bir günlük girdisi yazboolean
app.agents()Tüm mevcut agent’ları listeleAgent[]

Örnekler

// 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

YöntemAçıklamaYanıt
project.list()Tüm projeleri listeleProject[]
project.current()Mevcut projeyi alProject

Örnekler

// List all projects
const projects = await client.project.list()
// Get current project
const currentProject = await client.project.current()

Path

YöntemAçıklamaYanıt
path.get()Mevcut yolu alPath

Örnekler

// Get current path information
const pathInfo = await client.path.get()

Config

YöntemAçıklamaYanıt
config.get()Yapılandırma bilgisini alConfig
config.providers()Sağlayıcıları ve varsayılan modelleri listele{ providers: Provider[], default: { [key: string]: string } }

Örnekler

const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()

Oturumlar

YöntemAçıklamaNotlar
session.list()Oturumları listeleSession[] döndürür
session.get({ path })Oturum alSession döndürür
session.children({ path })Alt oturumları listeleSession[] döndürür
session.create({ body })Oturum oluşturSession döndürür
session.delete({ path })Oturum silboolean döndürür
session.update({ path, body })Oturum özelliklerini güncelleSession döndürür
session.init({ path, body })Uygulamayı analiz et ve AGENTS.md oluşturboolean döndürür
session.abort({ path })Çalışan bir oturumu iptal etboolean döndürür
session.share({ path })Oturum paylaşSession döndürür
session.unshare({ path })Oturum paylaşımını kaldırSession döndürür
session.summarize({ path, body })Oturumu özetleboolean döndürür
session.messages({ path })Oturumdaki mesajları listele{ info: Message, parts: Part[]}[] döndürür
session.message({ path })Mesaj ayrıntılarını al{ info: Message, parts: Part[]} döndürür
session.prompt({ path, body })İstem mesajı gönderbody.noReply: true UserMessage (yalnızca bağlam) döndürür. Varsayılan olarak AI yanıtıyla AssistantMessage döndürür
session.command({ path, body })Oturuma komut gönder{ info: AssistantMessage, parts: Part[]} döndürür
session.shell({ path, body })Bir kabuk komutu çalıştırAssistantMessage döndürür
session.revert({ path, body })Bir mesajı geri alSession döndürür
session.unrevert({ path })Geri alınan mesajları geri yükleSession döndürür
postSessionByIdPermissionsByPermissionId({ path, body })Bir izin isteğine yanıt verboolean döndürür

Örnekler

// 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." }],
},
})

Dosyalar

YöntemAçıklamaYanıt
find.text({ query })Dosyalarda metin arapath, lines, line_number, absolute_offset, submatches içeren eşleşme nesneleri dizisi
find.files({ query })Dosya ve dizinleri isme göre bulstring[] (yollar)
find.symbols({ query })Çalışma alanı sembollerini bulSymbol[]
file.read({ query })Bir dosyayı oku{ type: "raw" | "patch", content: string }
file.status({ query? })İzlenen dosyalar için durumu alFile[]

find.files birkaç isteğe bağlı sorgu alanını destekler:

  • type: "file" veya "directory"
  • directory: arama için proje kökünü geçersiz kılma
  • limit: maksimum sonuç (1-200)

Örnekler

// 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

YöntemAçıklamaYanıt
tui.appendPrompt({ body })İsteme metin ekleboolean
tui.openHelp()Yardım iletişim kutusunu açboolean
tui.openSessions()Oturum seçiciyi açboolean
tui.openThemes()Tema seçiciyi açboolean
tui.openModels()Model seçiciyi açboolean
tui.submitPrompt()Mevcut istemi gönderboolean
tui.clearPrompt()İstemi temizleboolean
tui.executeCommand({ body })Bir komut çalıştırboolean
tui.showToast({ body })Toast bildirimi gösterboolean

Örnekler

// Control TUI interface
await client.tui.appendPrompt({
body: { text: "Add this to prompt" },
})
await client.tui.showToast({
body: { message: "Task completed", variant: "success" },
})

Auth

YöntemAçıklamaYanıt
auth.set({ ... })Kimlik bilgilerini ayarlaboolean

Örnekler

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

Olaylar

YöntemAçıklamaYanıt
event.subscribe()Sunucu tarafından gönderilen olay akışıSunucu tarafından gönderilen olay akışı

Örnekler

// 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)
}