Files
tf_code/packages/web/src/content/docs/pl/sdk.mdx
opencode-agent[bot] d578f80f00 chore: generate
2026-02-09 17:35:30 +00:00

392 lines
16 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
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 <a href={typesUrl}>pliku typów</a>.
---
## 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 | <a href={typesUrl}><code>Agent[]</code></a> |
---
#### 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 | <a href={typesUrl}><code>Projekt[]</code></a> |
| `project.current()` | Get current project | <a href={typesUrl}><code>Project</code></a> |
---
#### 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 | <a href={typesUrl}><code>Path</code></a> |
---
#### Examples
```javascript
// Get current path information
const pathInfo = await client.path.get()
```
---
### Config
| Method | Description | Response |
| -------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `config.get()` | Get config info | <a href={typesUrl}><code>Config</code></a> |
| `config.providers()` | Lista dostawców i modeli domyślnych | `{ providers: `<a href={typesUrl}><code>Dostawca[]</code></a>`, 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 <a href={typesUrl}><code>Sesja[]</code></a> |
| `session.get({ path })` | Uzyskaj sesję | Zwraca <a href={typesUrl}><code>Sesja</code></a> |
| `session.children({ path })` | Lista sesji podrzędnych | Zwraca <a href={typesUrl}><code>Sesja[]</code></a> |
| `session.create({ body })` | Utwórz sesję | Zwraca <a href={typesUrl}><code>Sesja</code></a> |
| `session.delete({ path })` | Usuń sesję | Zwraca `boolean` |
| `session.update({ path, body })` | Aktualizuj właściwości sesji | Zwraca <a href={typesUrl}><code>Sesja</code></a> |
| `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 <a href={typesUrl}><code>Sesja</code></a> |
| `session.unshare({ path })` | Cofnij udostępnianie sesji | Zwraca <a href={typesUrl}><code>Sesja</code></a> |
| `session.summarize({ path, body })` | Podsumowanie sesji | Zwraca `boolean` |
| `session.messages({ path })` | Lista wiadomości w sesji | Zwraca `{ info: `<a href={typesUrl}><code>Wiadomość</code></a>`, parts: `<a href={typesUrl}><code>Część[]</code></a>`}[]` |
| `session.message({ path })` | Uzyskaj szczegóły wiadomości | Zwraca `{ info: `<a href={typesUrl}><code>Wiadomość</code></a>`, parts: `<a href={typesUrl}><code>Część[]</code></a>`}` |
| `session.prompt({ path, body })` | Wyślij wiadomość | `body.noReply: true` zwraca UserMessage (tylko kontekst). Domyślnie zwraca <a href={typesUrl}><code>AssistantMessage</code></a> z odpowiedzią AI |
| `session.command({ path, body })` | Wyślij polecenie do sesji | Zwraca `{ info: `<a href={typesUrl}><code>Wiadomość Asystenta</code></a>`, parts: `<a href={typesUrl}><code>Część[]</code></a>`}` |
| `session.shell({ path, body })` | Uruchom polecenie powłoki | Zwraca <a href={typesUrl}><code>Wiadomość Asystenta</code></a> |
| `session.revert({ path, body })` | Przywróć wiadomość | Zwraca <a href={typesUrl}><code>Sesja</code></a> |
| `session.unrevert({ path })` | Przywróć przywrócone wiadomości | Zwraca <a href={typesUrl}><code>Sesja</code></a> |
| `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 | <a href={typesUrl}><code>Symbol[]</code></a> |
| `file.read({ query })` | Read a file | `{ type: "raw" \| "patch", content: string }` |
| `file.status({ query? })` | Uzyskaj status śledzonych plików | <a href={typesUrl}><code>Plik[]</code></a> |
`find.files` supports a few optional query fields:
- `type`: `"file"` or `"directory"`
- `directory`: zastąp katalog główny projektu dla wyszukiwania
- `limit`: max results (1200)
---
#### 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)
}
```