SDK
Das opencode JS/TS SDK bietet einen typsicheren Client fuer die Server-API. Damit kannst du Integrationen bauen und opencode programmatisch steuern.
Mehr zum Server. Beispiele findest du in den Community-Projekten.
Installiere das SDK ueber npm:
npm install @opencode-ai/sdkErstelle eine opencode-Instanz:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()Das startet Server und Client.
Optionen
| Option | Type | Description | Default |
|---|---|---|---|
hostname | string | Server hostname | 127.0.0.1 |
port | number | Server port | 4096 |
signal | AbortSignal | Abort signal for cancellation | undefined |
timeout | number | Timeout in ms for server start | 5000 |
config | Config | Configuration object | {} |
Du kannst ein Konfigurationsobjekt uebergeben, um das Verhalten anzupassen.
opencode.json wird weiterhin geladen, kann aber inline ueberschrieben oder erweitert werden:
import { createOpencode } from "@opencode-ai/sdk"
const opencode = await createOpencode({
hostname: "127.0.0.1",
port: 4096,
config: {
model: "anthropic/claude-sonnet-5-5",
},
})
console.log(`Server running at ${opencode.server.url}`)
opencode.server.close()Wenn opencode bereits laeuft, kannst du nur einen Client erstellen und verbinden:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({
baseUrl: "http://localhost:4096",
})Optionen
| Option | Type | Description | Default |
|---|---|---|---|
baseUrl | string | URL of the server | 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 |
Das SDK bringt TypeScript-Definitionen fuer alle API-Typen mit. Du kannst sie direkt importieren:
import type { Session, Message, Part } from "@opencode-ai/sdk"Alle Typen werden aus der OpenAPI-Spezifikation des Servers generiert und sind in der Typdatei verfuegbar.
Das SDK kann Fehler werfen, die du abfangen und behandeln kannst:
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}Du kannst eine strukturierte JSON-Ausgabe vom Modell anfordern, indem du ein format mit einem JSON-Schema angibst. Das Modell verwendet dann ein StructuredOutput-Tool, um validiertes JSON zurueckzugeben, das deinem Schema entspricht.
const result = await client.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: "text", text: "Recherchiere Anthropic und gib Firmeninfos zurueck" }],
format: {
type: "json_schema",
schema: {
type: "object",
properties: {
company: { type: "string", description: "Firmenname" },
founded: { type: "number", description: "Gruendungsjahr" },
products: {
type: "array",
items: { type: "string" },
description: "Hauptprodukte",
},
},
required: ["company", "founded"],
},
},
},
})
// Zugriff auf die strukturierte Ausgabe
console.log(result.data.info.structured_output)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }| Type | Description |
|---|---|
text | Standard. Normale Textantwort (keine strukturierte Ausgabe) |
json_schema | Gibt validiertes JSON zurueck, das dem Schema entspricht |
Bei Verwendung von type: 'json_schema' musst du Folgendes angeben:
| Field | Type | Description |
|---|---|---|
type | 'json_schema' | Erforderlich. Gibt den JSON-Schema-Modus an |
schema | object | Erforderlich. JSON-Schema-Objekt, das die Struktur definiert |
retryCount | number | Optional. Anzahl der Validierungswiederholungen (Standard: 2) |
Wenn das Modell nach allen Wiederholungen keine valide strukturierte Ausgabe liefert, enthaelt die Antwort einen StructuredOutputError:
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Strukturierte Ausgabe fehlgeschlagen:", result.data.info.error.message)
console.error("Versuche:", result.data.info.error.retries)
}- Klare Beschreibungen: Gib in deinen Schema-Properties klare Beschreibungen an, damit das Modell versteht, welche Daten extrahiert werden sollen.
requirednutzen: Definiere, welche Felder zwingend vorhanden sein muessen.- Schemas einfach halten: Komplexe verschachtelte Schemas sind fuer das Modell schwerer korrekt auszufuellen.
retryCountanpassen: Erhoehe den Wert bei komplexen Schemas, verringere ihn bei einfachen.
Das SDK stellt alle Server-APIs ueber einen typsicheren Client bereit.
| Method | Description | Response |
|---|---|---|
global.health() | Prueft Server-Status und Version | { healthy: true, version: string } |
Beispiele
const health = await client.global.health()
console.log(health.data.version)| Method | Description | Response |
|---|---|---|
app.log() | Schreibt einen Log-Eintrag | boolean |
app.agents() | Listet alle verfuegbaren Agenten | Agent[] |
Beispiele
// 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()| Method | Description | Response |
|---|---|---|
project.list() | Listet alle Projekte | Project[] |
Beispiele
// List all projects
const projects = await client.project.list()
| Method | Description | Response |
|---|---|---|
path.get() | Ruft den aktuellen Pfad ab | Path |
Beispiele
// Get current path information
const pathInfo = await client.path.get()| Method | Description | Response |
|---|---|---|
config.get() | Ruft Konfigurationsinfos ab | Config |
config.providers() | Listet Provider und Standard-Modelle | { providers: Provider[], default: { [key: string]: string } } |
Beispiele
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()| Method | Description | Notes |
|---|---|---|
session.list() | Listet Sessions | Gibt Session[] zurueck |
session.get({ path }) | Ruft Session ab | Gibt Session zurueck |
session.children({ path }) | Listet Kind-Sessions | Gibt Session[] zurueck |
session.create({ body }) | Erstellt Session | Gibt Session zurueck |
session.delete({ path }) | Loescht Session | Gibt boolean zurueck |
session.update({ path, body }) | Aktualisiert Session-Eigenschaften | Gibt Session zurueck |
session.init({ path, body }) | Analysiert App und erstellt AGENTS.md | Gibt boolean zurueck |
session.abort({ path }) | Bricht eine laufende Session ab | Gibt boolean zurueck |
session.share({ path }) | Teilt Session | Gibt Session zurueck |
session.unshare({ path }) | Hebt Teilen der Session auf | Gibt Session zurueck |
session.summarize({ path, body }) | Fasst Session zusammen | Gibt boolean zurueck |
session.messages({ path }) | Listet Nachrichten einer Session | Gibt { info: Message, parts: Part[]}[] zurueck |
session.message({ path }) | Ruft Nachrichtendetails ab | Gibt { info: Message, parts: Part[]} zurueck |
session.prompt({ path, body }) | Sendet Prompt-Nachricht | body.noReply: true gibt UserMessage (nur Kontext) zurueck. Standard gibt AssistantMessage mit AI-Antwort zurueck. Unterstuetzt body.outputFormat fuer strukturierte Ausgabe |
session.command({ path, body }) | Sendet Befehl an Session | Gibt { info: AssistantMessage, parts: Part[]} zurueck |
session.shell({ path, body }) | Fuehrt Shell-Befehl aus | Gibt AssistantMessage zurueck |
session.revert({ path, body }) | Setzt Nachricht zurueck | Gibt Session zurueck |
session.unrevert({ path }) | Stellt zurueckgesetzte Nachrichten wieder her | Gibt Session zurueck |
postSessionByIdPermissionsByPermissionId({ path, body }) | Antwortet auf eine Berechtigungsanfrage | Gibt boolean zurueck |
Beispiele
// 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-sonnet-5-5" },
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." }],
},
})| Method | Description | Response |
|---|---|---|
find.text({ query }) | Sucht Text in Dateien | Array of match objects with path, lines, line_number, absolute_offset, submatches |
find.files({ query }) | Findet Dateien und Verzeichnisse nach Namen | string[] (paths) |
find.symbols({ query }) | Findet Workspace-Symbole | Symbol[] |
file.read({ query }) | Liest eine Datei | { type: "raw" | "patch", content: string } |
file.status({ query? }) | Ruft Status fuer getrackte Dateien ab | File[] |
find.files unterstuetzt einige optionale Query-Felder:
type:"file"oder"directory"directory: Ueberschreibt das Projekt-Root fuer die Suchelimit: Maximale Ergebnisse (1–200)
Beispiele
// 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" },
})| Method | Description | Response |
|---|---|---|
tui.appendPrompt({ body }) | Haengt Text an den Prompt an | boolean |
tui.openHelp() | Oeffnet den Hilfedialog | boolean |
tui.openSessions() | Oeffnet die Session-Auswahl | boolean |
tui.openThemes() | Oeffnet die Theme-Auswahl | boolean |
tui.openModels() | Oeffnet die Modell-Auswahl | boolean |
tui.submitPrompt() | Sendet den aktuellen Prompt ab | boolean |
tui.clearPrompt() | Leert den Prompt | boolean |
tui.executeCommand({ body }) | Fuehrt einen Befehl aus | boolean |
tui.showToast({ body }) | Zeigt Toast-Benachrichtigung | boolean |
Beispiele
// Control TUI interface
await client.tui.appendPrompt({
body: { text: "Add this to prompt" },
})
await client.tui.showToast({
body: { message: "Task completed", variant: "success" },
})| Method | Description | Response |
|---|---|---|
auth.set({ ... }) | Setzt Authentifizierungsdaten | boolean |
Beispiele
await client.auth.set({
path: { id: "anthropic" },
body: { type: "api", key: "your-api-key" },
})| Method | Description | Response |
|---|---|---|
event.subscribe() | Server-Sent Events Stream | Server-sent events stream |
Beispiele
// 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)
}