SDK
Klient JS bezpieczny dla typu dla serwera opencode.
Pakiet SDK JS/TS z opencode zapewnia klienta bezpiecznego typu do interakcji z serwerem. Użyj go do budowania integracji i programowej kontroli otwartego kodu.
Dowiedz się więcej o działaniu serwera. Przykłady znajdziesz w projektach stworzonych przez społeczność.
Zainstalować
Zainstaluj pakiet SDK z npm:
npm install @opencode-ai/sdkUtwórz klienta
Utwórz instancję otwartego kodu:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()Spowoduje to uruchomienie zarówno serwera, jak i klienta
Options
| Opcja | Wpisz | Opis | Domyślne |
|---|---|---|---|
hostname | string | Nazwa hosta serwera | 127.0.0.1 |
port | number | Port serwera | 4096 |
signal | AbortSignal | Sygnał przerwania w celu anulowania | undefined |
timeout | number | Limit czasu w ms dla uruchomienia serwera | 5000 |
config | Config | Configuration object | {} |
Config
Można przekazać obiekt konfiguracyjny, aby dostosować zachowanie. Instancja nadal pobiera opencode.json, ale możesz zastąpić lub dodać konfigurację bezpośrednio:
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()Client only
Jeśli masz już działającą instancję opencode, możesz utworzyć instancję klienta, aby się z nią połączyć:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({ baseUrl: "http://localhost:4096",})Options
| Opcja | Wpisz | Opis | Domyślne |
|---|---|---|---|
baseUrl | string | Adres URL serwera | http://localhost:4096 |
fetch | function | Custom fetch implementation | globalThis.fetch |
parseAs | string | Response parsing method | auto |
responseStyle | string | Return style: data or fields | fields |
throwOnError | boolean | Throw errors instead of return | false |
Types
Zestaw SDK zawiera definicje TypeScript dla wszystkich typów API. Zaimportuj je bezpośrednio:
import type { Session, Message, Part } from "@opencode-ai/sdk"Wszystkie typy są generowane na podstawie specyfikacji OpenAPI serwera i dostępne w pliku typów.
Errors
SDK może generować błędy, które można przechwycić i obsłużyć:
try { await client.session.get({ path: { id: "invalid-id" } })} catch (error) { console.error("Failed to get session:", (error as Error).message)}APIs
Zestaw SDK udostępnia wszystkie interfejsy API serwera za pośrednictwem klienta bezpiecznego typu.
Global
| Method | Description | Response |
|---|---|---|
global.health() | Sprawdź stan i wersję serwera | { healthy: true, version: string } |
Examples
const health = await client.global.health()console.log(health.data.version)App
| Method | Description | Response |
|---|---|---|
app.log() | Write a log entry | boolean |
app.agents() | Lista wszystkich dostępnych agentów | Agent[] |
Examples
// 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
| Method | Description | Response |
|---|---|---|
project.list() | Lista wszystkich projektów | Project[] |
project.current() | Get current project | Project |
Examples
// List all projectsconst projects = await client.project.list()
// Get current projectconst currentProject = await client.project.current()Path
| Method | Description | Response |
|---|---|---|
path.get() | Get current path | Path |
Examples
// Get current path informationconst pathInfo = await client.path.get()Config
| Method | Description | Response |
|---|---|---|
config.get() | Get config info | Config |
config.providers() | Lista dostawców i modeli domyślnych | { providers: Provider[], default: { [key: string]: string } } |
Examples
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()Sessions
| Method | Description | Notes |
|---|---|---|
session.list() | Lista sesji | Zwraca Session[] |
session.get({ path }) | Uzyskaj sesję | Zwraca Session |
session.children({ path }) | Lista sesji podrzędnych | Zwraca Session[] |
session.create({ body }) | Utwórz sesję | Zwraca Session |
session.delete({ path }) | Usuń sesję | Zwraca boolean |
session.update({ path, body }) | Aktualizuj właściwości sesji | Zwraca Session |
session.init({ path, body }) | Przeanalizuj aplikację i utwórz AGENTS.md | Zwraca boolean |
session.abort({ path }) | Przerwij trwającą sesję | Zwraca boolean |
session.share({ path }) | Udostępnij sesję | Zwraca Session |
session.unshare({ path }) | Cofnij udostępnianie sesji | Zwraca Session |
session.summarize({ path, body }) | Podsumowanie sesji | Zwraca boolean |
session.messages({ path }) | Lista wiadomości w sesji | Zwraca { info: Message, parts: Part[]}[] |
session.message({ path }) | Uzyskaj szczegóły wiadomości | Zwraca { info: Message, parts: Part[]} |
session.prompt({ path, body }) | Wyślij wiadomość | body.noReply: true zwraca UserMessage (tylko kontekst). Domyślnie zwraca AssistantMessage z odpowiedzią AI |
session.command({ path, body }) | Wyślij polecenie do sesji | Zwraca { info: AssistantMessage, parts: Part[]} |
session.shell({ path, body }) | Uruchom polecenie shell | Zwraca AssistantMessage |
session.revert({ path, body }) | Przywróć wiadomość | Zwraca Session |
session.unrevert({ path }) | Przywróć przywrócone wiadomości | Zwraca Session |
postSessionByIdPermissionsByPermissionId({ path, body }) | Respond to a permission request | Returns boolean |
Examples
// 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." }], },})Files
| Method | Description | Response |
|---|---|---|
find.text({ query }) | Szukaj tekstu w plikach | Tablica obiektów dopasowania z path, lines, line_number, absolute_offset, submatches |
find.files({ query }) | Znajdź pliki i katalogi według nazwy | string[] (ścieżki) |
find.symbols({ query }) | Find workspace symbols | Symbol[] |
file.read({ query }) | Read a file | { type: "raw" | "patch", content: string } |
file.status({ query? }) | Uzyskaj status śledzonych plików | File[] |
find.files supports a few optional query fields:
type:"file"or"directory"directory: zastąp katalog główny projektu dla wyszukiwanialimit: max results (1–200)
Examples
// 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
| Method | Description | Response |
|---|---|---|
tui.appendPrompt({ body }) | Dołącz tekst do zachęty | boolean |
tui.openHelp() | Otwórz okno pomocy | boolean |
tui.openSessions() | Otwórz selektor sesji | boolean |
tui.openThemes() | Otwórz selektor motywów | boolean |
tui.openModels() | Otwórz selektor modelu | boolean |
tui.submitPrompt() | Prześlij bieżący monit | boolean |
tui.clearPrompt() | Wyczyść monit | boolean |
tui.executeCommand({ body }) | Wykonaj polecenie | boolean |
tui.showToast({ body }) | Pokaż powiadomienie tostowe | boolean |
Examples
// Control TUI interfaceawait client.tui.appendPrompt({ body: { text: "Add this to prompt" },})
await client.tui.showToast({ body: { message: "Task completed", variant: "success" },})Auth
| Method | Description | Response |
|---|---|---|
auth.set({ ... }) | Set authentication credentials | boolean |
Examples
await client.auth.set({ path: { id: "anthropic" }, body: { type: "api", key: "your-api-key" },})Events
| Method | Description | Response |
|---|---|---|
event.subscribe() | Strumień zdarzeń wysłanych przez serwer | Strumień zdarzeń wysłanych przez serwer |
Examples
// Listen to real-time eventsconst events = await client.event.subscribe()for await (const event of events.stream) { console.log("Event:", event.type, event.properties)}