---
title: SDK
description: Klient JS bezpieczny dla typu dla serwera opencode.
---
import config from "../../../../config.mjs"
export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts`
Pakiet SDK JS/TS z otwartym kodem zapewnia klienta bezpiecznego typu do interakcji z serwerem.
Użyj go do budowania integracji i programowej kontroli otwartego kodu.
[Dowiedz się więcej](/docs/server) o działaniu serwera. Przykłady znajdziesz w [projektach](/docs/ecosystem#projects) stworzonych przez społeczność.
---
## Zainstalować
Zainstaluj pakiet SDK z npm:
```bash
npm install @opencode-ai/sdk
```
---
## Utwórz klienta
Utwórz instancję otwartego kodu:
```javascript
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:
```javascript
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ć:
```javascript
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:
```typescript
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ć:
```typescript
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
```javascript
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
```javascript
// 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
| Method | Description | Response |
| ------------------- | -------------------------- | --------------------------------------------- |
| `project.list()` | Lista wszystkich projektów | Projekt[] |
| `project.current()` | Get current project | Project |
---
#### Examples
```javascript
// List all projects
const projects = await client.project.list()
// Get current project
const currentProject = await client.project.current()
```
---
### Path
| Method | Description | Response |
| ------------ | ---------------- | ---------------------------------------- |
| `path.get()` | Get current path | Path |
---
#### Examples
```javascript
// Get current path information
const 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: `Dostawca[]`, default: { [key: string]: string } }` |
---
#### Examples
```javascript
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()
```
---
### Sessions
| Method | Description | Notes |
| ---------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `session.list()` | Lista sesji | Zwraca Sesja[] |
| `session.get({ path })` | Uzyskaj sesję | Zwraca Sesja |
| `session.children({ path })` | Lista sesji podrzędnych | Zwraca Sesja[] |
| `session.create({ body })` | Utwórz sesję | Zwraca Sesja |
| `session.delete({ path })` | Usuń sesję | Zwraca `boolean` |
| `session.update({ path, body })` | Aktualizuj właściwości sesji | Zwraca Sesja |
| `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 Sesja |
| `session.unshare({ path })` | Cofnij udostępnianie sesji | Zwraca Sesja |
| `session.summarize({ path, body })` | Podsumowanie sesji | Zwraca `boolean` |
| `session.messages({ path })` | Lista wiadomości w sesji | Zwraca `{ info: `Wiadomość`, parts: `Część[]`}[]` |
| `session.message({ path })` | Uzyskaj szczegóły wiadomości | Zwraca `{ info: `Wiadomość`, parts: `Część[]`}` |
| `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: `Wiadomość Asystenta`, parts: `Część[]`}` |
| `session.shell({ path, body })` | Uruchom polecenie powłoki | Zwraca Wiadomość Asystenta |
| `session.revert({ path, body })` | Przywróć wiadomość | Zwraca Sesja |
| `session.unrevert({ path })` | Przywróć przywrócone wiadomości | Zwraca Sesja |
| `postSessionByIdPermissionsByPermissionId({ path, body })` | Respond to a permission request | Returns `boolean` |
---
#### Examples
```javascript
// 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." }],
},
})
```
---
### 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 | Plik[] |
`find.files` supports a few optional query fields:
- `type`: `"file"` or `"directory"`
- `directory`: zastąp katalog główny projektu dla wyszukiwania
- `limit`: max results (1–200)
---
#### Examples
```javascript
// 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
| 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
```javascript
// Control TUI interface
await 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
```javascript
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
```javascript
// 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)
}
```