SDK
Client JS con tipi per il server opencode.
L’SDK JS/TS di opencode fornisce un client con tipi per interagire con il server. Usalo per creare integrazioni e controllare opencode programmaticamente.
Ulteriori informazioni sul funzionamento del server. Per esempi, consulta i progetti creati dalla community.
Installazione
Installa l’SDK da npm:
npm install @opencode-ai/sdkCreare client
Crea un’istanza di opencode:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()Questo avvia sia un server che un client
Opzioni
| Option | Type | Description | Default |
|---|---|---|---|
hostname | string | Nome host del server | 127.0.0.1 |
port | number | Porta del server | 4096 |
signal | AbortSignal | Segnale di aborto per la cancellazione | undefined |
timeout | number | Timeout in ms per l’avvio del server | 5000 |
config | Config | Oggetto di configurazione | {} |
Config
Puoi passare un oggetto di configurazione per personalizzare il comportamento. L’istanza recupera ancora il tuo opencode.json, ma puoi sovrascrivere o aggiungere configurazione inline:
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 in esecuzione su ${opencode.server.url}`)
opencode.server.close()Solo client
Se hai gi un’istanza di opencode in esecuzione, puoi creare un’istanza client per connetterti ad essa:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({ baseUrl: "http://localhost:4096",})Opzioni
| Option | Type | Description | Default |
|---|---|---|---|
baseUrl | string | URL del server | http://localhost:4096 |
fetch | function | Implementazione fetch personalizzata | globalThis.fetch |
parseAs | string | Metodo di parsing della risposta | auto |
responseStyle | string | Stile di ritorno: data o fields | fields |
throwOnError | boolean | Lanciare errori invece di restituire | false |
Tipi
L’SDK include le definizioni TypeScript per tutti i tipi API. Importali direttamente:
import type { Session, Message, Part } from "@opencode-ai/sdk"Tutti i tipi sono generati dalla specifica OpenAPI del server e sono disponibili nel file dei tipi.
Errori
L’SDK pu lanciare errori che puoi catturare e gestire:
try { await client.session.get({ path: { id: "invalid-id" } })} catch (error) { console.error("Impossibile ottenere la sessione:", (error as Error).message)}API
L’SDK espone tutte le API del server attraverso un client con tipi.
Global
| Method | Description | Response |
|---|---|---|
global.health() | Verificare lo stato del server e la versione | { healthy: true, version: string } |
Esempi
const health = await client.global.health()console.log(health.data.version)App
| Method | Description | Response |
|---|---|---|
app.log() | Scrivere una voce di log | boolean |
app.agents() | Elencare tutti gli agent disponibili | Agent[] |
Esempi
// Scrivere una voce di logawait client.app.log({ body: { service: "my-app", level: "info", message: "Operazione completata", },})
// Elencare gli agenti disponibiliconst agents = await client.app.agents()Project
| Method | Description | Response |
|---|---|---|
project.list() | Elencare tutti i progetti | Project[] |
project.current() | Ottenere il progetto attuale | Project |
Esempi
// Elencare tutti i progetticonst projects = await client.project.list()
// Ottenere il progetto attualeconst currentProject = await client.project.current()Path
| Method | Description | Response |
|---|---|---|
path.get() | Ottenere il percorso attuale | Path |
Esempi
// Ottenere informazioni sul percorso attualeconst pathInfo = await client.path.get()Config
| Method | Description | Response |
|---|---|---|
config.get() | Ottenere informazioni di configurazione | Config |
config.providers() | Elencare provider e modelli predefiniti | { providers: Provider[], default: { [key: string]: string } } |
Esempi
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()Sessions
| Method | Description | Notes |
|---|---|---|
session.list() | Elencare le sessioni | Restituisce Session[] |
session.get({ path }) | Ottenere session | Restituisce Session |
session.children({ path }) | Elencare le sessioni figlie | Restituisce Session[] |
session.create({ body }) | Creare session | Restituisce Session |
session.delete({ path }) | Eliminare session e tutti i suoi dati | Restituisce boolean |
session.update({ path, body }) | Aggiornare le propriet della session | Restituisce Session |
session.init({ path, body }) | Analizzare app e creare AGENTS.md | Restituisce boolean |
session.abort({ path }) | Abortare una sessione in esecuzione | Restituisce boolean |
session.share({ path }) | Condividere session | Restituisce Session |
session.unshare({ path }) | Annullare la condivisione della session | Restituisce Session |
session.summarize({ path, body }) | Riassumere la session | Restituisce boolean |
session.messages({ path }) | Elencare i messaggi in una sessione | Restituisce { info: Message, parts: Part[]}[] |
session.message({ path }) | Ottenere dettagli del messaggio | Restituisce { info: Message, parts: Part[]} |
session.prompt({ path, body }) | Inviare messaggio di prompt | body.noReply: true restituisce UserMessage (solo contesto). Il default restituisce AssistantMessage con risposta AI |
session.command({ path, body }) | Inviare comando alla sessione | Restituisce { info: AssistantMessage, parts: Part[]} |
session.shell({ path, body }) | Eseguire un comando shell | Restituisce AssistantMessage |
session.revert({ path, body }) | Revertire un messaggio | Restituisce Session |
session.unrevert({ path }) | Ripristinare i messaggi revertiti | Restituisce Session |
postSessionByIdPermissionsByPermissionId({ path, body }) | Rispondere a una richiesta di autorizzazione | Restituisce boolean |
Esempi
// Creare e gestire sessioniconst session = await client.session.create({ body: { title: "La mia sessione" },})
const sessions = await client.session.list()
// Inviare un messaggio di promptconst result = await client.session.prompt({ path: { id: session.id }, body: { model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, parts: [{ type: "text", text: "Ciao!" }], },})
// Iniettare contesto senza attivare risposta AI (utile per i plugin)await client.session.prompt({ path: { id: session.id }, body: { noReply: true, parts: [{ type: "text", text: "Sei un assistente utile." }], },})Files
| Method | Description | Response |
|---|---|---|
find.text({ query }) | Cercare testo nei file | Array di oggetti di corrispondenza con path, lines, line_number, absolute_offset, submatches |
find.files({ query }) | Trovare file e directory per nome | string[] (percorsi) |
find.symbols({ query }) | Trovare simboli dello spazio di lavoro | Symbol[] |
file.read({ query }) | Leggere un file | { type: "raw" | "patch", content: string } |
file.status({ query? }) | Ottenere stato per i file tracciati | File[] |
find.files supporta alcuni campi di query opzionali:
type:"file"o"directory"directory: sovrascrivere la radice del progetto per la ricercalimit: risultati massimi (1-200)
Esempi
// Cercare e leggere fileconst 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 }) | Aggiungere testo al prompt | boolean |
tui.openHelp() | Aprire la finestra di aiuto | boolean |
tui.openSessions() | Aprire il selettore di sessione | boolean |
tui.openThemes() | Aprire il selettore di temi | boolean |
tui.openModels() | Aprire il selettore di modelli | boolean |
tui.submitPrompt() | Inviare il prompt attuale | boolean |
tui.clearPrompt() | Cancella il prompt | boolean |
tui.executeCommand({ body }) | Eseguire un comando | boolean |
tui.showToast({ body }) | Mostrare notifica toast | boolean |
Esempi
// Controllare l'interfaccia TUIawait client.tui.appendPrompt({ body: { text: "Aggiungi questo al prompt" },})
await client.tui.showToast({ body: { message: "Attivit completata", variant: "success" },})Auth
| Method | Description | Response |
|---|---|---|
auth.set({ ... }) | Impostare credenziali di autenticazione | boolean |
Esempi
await client.auth.set({ path: { id: "anthropic" }, body: { type: "api", key: "your-api-key" },})Events
| Method | Description | Response |
|---|---|---|
event.subscribe() | Flusso di eventi inviati dal server | Flusso di eventi inviati dal server |
Esempi
// Ascoltare eventi in tempo realeconst events = await client.event.subscribe()for await (const event of events.stream) { console.log("Evento:", event.type, event.properties)}