sdk.mdx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. ---
  2. title: SDK
  3. description: Type-safe JS client for opencode server.
  4. ---
  5. import config from "../../../config.mjs"
  6. export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts`
  7. The opencode JS/TS SDK provides a type-safe client for interacting with the server.
  8. Use it to build integrations and control opencode programmatically.
  9. [Learn more](/docs/server) about how the server works. For examples, check out the [projects](/docs/ecosystem#projects) built by the community.
  10. ---
  11. ## Install
  12. Install the SDK from npm:
  13. ```bash
  14. npm install @opencode-ai/sdk
  15. ```
  16. ---
  17. ## Create client
  18. Create an instance of opencode:
  19. ```javascript
  20. import { createOpencode } from "@opencode-ai/sdk"
  21. const { client } = await createOpencode()
  22. ```
  23. This starts both a server and a client
  24. #### Options
  25. | Option | Type | Description | Default |
  26. | ---------- | ------------- | ------------------------------ | ----------- |
  27. | `hostname` | `string` | Server hostname | `127.0.0.1` |
  28. | `port` | `number` | Server port | `4096` |
  29. | `signal` | `AbortSignal` | Abort signal for cancellation | `undefined` |
  30. | `timeout` | `number` | Timeout in ms for server start | `5000` |
  31. | `config` | `Config` | Configuration object | `{}` |
  32. ---
  33. ## Config
  34. You can pass a configuration object to customize behavior. The instance still picks up your `opencode.json`, but you can override or add configuration inline:
  35. ```javascript
  36. import { createOpencode } from "@opencode-ai/sdk"
  37. const opencode = await createOpencode({
  38. hostname: "127.0.0.1",
  39. port: 4096,
  40. config: {
  41. model: "anthropic/claude-3-5-sonnet-20241022",
  42. },
  43. })
  44. console.log(`Server running at ${opencode.server.url}`)
  45. opencode.server.close()
  46. ```
  47. ## Client only
  48. If you already have a running instance of opencode, you can create a client instance to connect to it:
  49. ```javascript
  50. import { createOpencodeClient } from "@opencode-ai/sdk"
  51. const client = createOpencodeClient({
  52. baseUrl: "http://localhost:4096",
  53. })
  54. ```
  55. #### Options
  56. | Option | Type | Description | Default |
  57. | --------------- | ---------- | -------------------------------- | ----------------------- |
  58. | `baseUrl` | `string` | URL of the server | `http://localhost:4096` |
  59. | `fetch` | `function` | Custom fetch implementation | `globalThis.fetch` |
  60. | `parseAs` | `string` | Response parsing method | `auto` |
  61. | `responseStyle` | `string` | Return style: `data` or `fields` | `fields` |
  62. | `throwOnError` | `boolean` | Throw errors instead of return | `false` |
  63. ---
  64. ## Types
  65. The SDK includes TypeScript definitions for all API types. Import them directly:
  66. ```typescript
  67. import type { Session, Message, Part } from "@opencode-ai/sdk"
  68. ```
  69. All types are generated from the server's OpenAPI specification and available in the <a href={typesUrl}>types file</a>.
  70. ---
  71. ## Errors
  72. The SDK can throw errors that you can catch and handle:
  73. ```typescript
  74. try {
  75. await client.session.get({ path: { id: "invalid-id" } })
  76. } catch (error) {
  77. console.error("Failed to get session:", (error as Error).message)
  78. }
  79. ```
  80. ---
  81. ## Structured Output
  82. You can request structured JSON output from the model by specifying an `format` with a JSON schema. The model will use a `StructuredOutput` tool to return validated JSON matching your schema.
  83. ### Basic Usage
  84. ```typescript
  85. const result = await client.session.prompt({
  86. path: { id: sessionId },
  87. body: {
  88. parts: [{ type: "text", text: "Research Anthropic and provide company info" }],
  89. format: {
  90. type: "json_schema",
  91. schema: {
  92. type: "object",
  93. properties: {
  94. company: { type: "string", description: "Company name" },
  95. founded: { type: "number", description: "Year founded" },
  96. products: {
  97. type: "array",
  98. items: { type: "string" },
  99. description: "Main products",
  100. },
  101. },
  102. required: ["company", "founded"],
  103. },
  104. },
  105. },
  106. })
  107. // Access the structured output
  108. console.log(result.data.info.structured_output)
  109. // { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
  110. ```
  111. ### Output Format Types
  112. | Type | Description |
  113. | ------------- | ------------------------------------------------------ |
  114. | `text` | Default. Standard text response (no structured output) |
  115. | `json_schema` | Returns validated JSON matching the provided schema |
  116. ### JSON Schema Format
  117. When using `type: 'json_schema'`, provide:
  118. | Field | Type | Description |
  119. | ------------ | --------------- | ---------------------------------------------------------- |
  120. | `type` | `'json_schema'` | Required. Specifies JSON schema mode |
  121. | `schema` | `object` | Required. JSON Schema object defining the output structure |
  122. | `retryCount` | `number` | Optional. Number of validation retries (default: 2) |
  123. ### Error Handling
  124. If the model fails to produce valid structured output after all retries, the response will include a `StructuredOutputError`:
  125. ```typescript
  126. if (result.data.info.error?.name === "StructuredOutputError") {
  127. console.error("Failed to produce structured output:", result.data.info.error.message)
  128. console.error("Attempts:", result.data.info.error.retries)
  129. }
  130. ```
  131. ### Best Practices
  132. 1. **Provide clear descriptions** in your schema properties to help the model understand what data to extract
  133. 2. **Use `required`** to specify which fields must be present
  134. 3. **Keep schemas focused** - complex nested schemas may be harder for the model to fill correctly
  135. 4. **Set appropriate `retryCount`** - increase for complex schemas, decrease for simple ones
  136. ---
  137. ## APIs
  138. The SDK exposes all server APIs through a type-safe client.
  139. ---
  140. ### Global
  141. | Method | Description | Response |
  142. | ----------------- | ------------------------------- | ------------------------------------ |
  143. | `global.health()` | Check server health and version | `{ healthy: true, version: string }` |
  144. ---
  145. #### Examples
  146. ```javascript
  147. const health = await client.global.health()
  148. console.log(health.data.version)
  149. ```
  150. ---
  151. ### App
  152. | Method | Description | Response |
  153. | -------------- | ------------------------- | ------------------------------------------- |
  154. | `app.log()` | Write a log entry | `boolean` |
  155. | `app.agents()` | List all available agents | <a href={typesUrl}><code>Agent[]</code></a> |
  156. ---
  157. #### Examples
  158. ```javascript
  159. // Write a log entry
  160. await client.app.log({
  161. body: {
  162. service: "my-app",
  163. level: "info",
  164. message: "Operation completed",
  165. },
  166. })
  167. // List available agents
  168. const agents = await client.app.agents()
  169. ```
  170. ---
  171. ### Project
  172. | Method | Description | Response |
  173. | ------------------- | ------------------- | --------------------------------------------- |
  174. | `project.list()` | List all projects | <a href={typesUrl}><code>Project[]</code></a> |
  175. | `project.current()` | Get current project | <a href={typesUrl}><code>Project</code></a> |
  176. ---
  177. #### Examples
  178. ```javascript
  179. // List all projects
  180. const projects = await client.project.list()
  181. // Get current project
  182. const currentProject = await client.project.current()
  183. ```
  184. ---
  185. ### Path
  186. | Method | Description | Response |
  187. | ------------ | ---------------- | ---------------------------------------- |
  188. | `path.get()` | Get current path | <a href={typesUrl}><code>Path</code></a> |
  189. ---
  190. #### Examples
  191. ```javascript
  192. // Get current path information
  193. const pathInfo = await client.path.get()
  194. ```
  195. ---
  196. ### Config
  197. | Method | Description | Response |
  198. | -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- |
  199. | `config.get()` | Get config info | <a href={typesUrl}><code>Config</code></a> |
  200. | `config.providers()` | List providers and default models | `{ providers: `<a href={typesUrl}><code>Provider[]</code></a>`, default: { [key: string]: string } }` |
  201. ---
  202. #### Examples
  203. ```javascript
  204. const config = await client.config.get()
  205. const { providers, default: defaults } = await client.config.providers()
  206. ```
  207. ---
  208. ### Sessions
  209. | Method | Description | Notes |
  210. | ---------------------------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
  211. | `session.list()` | List sessions | Returns <a href={typesUrl}><code>Session[]</code></a> |
  212. | `session.get({ path })` | Get session | Returns <a href={typesUrl}><code>Session</code></a> |
  213. | `session.children({ path })` | List child sessions | Returns <a href={typesUrl}><code>Session[]</code></a> |
  214. | `session.create({ body })` | Create session | Returns <a href={typesUrl}><code>Session</code></a> |
  215. | `session.delete({ path })` | Delete session | Returns `boolean` |
  216. | `session.update({ path, body })` | Update session properties | Returns <a href={typesUrl}><code>Session</code></a> |
  217. | `session.init({ path, body })` | Analyze app and create `AGENTS.md` | Returns `boolean` |
  218. | `session.abort({ path })` | Abort a running session | Returns `boolean` |
  219. | `session.share({ path })` | Share session | Returns <a href={typesUrl}><code>Session</code></a> |
  220. | `session.unshare({ path })` | Unshare session | Returns <a href={typesUrl}><code>Session</code></a> |
  221. | `session.summarize({ path, body })` | Summarize session | Returns `boolean` |
  222. | `session.messages({ path })` | List messages in a session | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
  223. | `session.message({ path })` | Get message details | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
  224. | `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` returns UserMessage (context only). Default returns <a href={typesUrl}><code>AssistantMessage</code></a> with AI response. Supports `body.outputFormat` for [structured output](#structured-output) |
  225. | `session.command({ path, body })` | Send command to session | Returns `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
  226. | `session.shell({ path, body })` | Run a shell command | Returns <a href={typesUrl}><code>AssistantMessage</code></a> |
  227. | `session.revert({ path, body })` | Revert a message | Returns <a href={typesUrl}><code>Session</code></a> |
  228. | `session.unrevert({ path })` | Restore reverted messages | Returns <a href={typesUrl}><code>Session</code></a> |
  229. | `postSessionByIdPermissionsByPermissionId({ path, body })` | Respond to a permission request | Returns `boolean` |
  230. ---
  231. #### Examples
  232. ```javascript
  233. // Create and manage sessions
  234. const session = await client.session.create({
  235. body: { title: "My session" },
  236. })
  237. const sessions = await client.session.list()
  238. // Send a prompt message
  239. const result = await client.session.prompt({
  240. path: { id: session.id },
  241. body: {
  242. model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" },
  243. parts: [{ type: "text", text: "Hello!" }],
  244. },
  245. })
  246. // Inject context without triggering AI response (useful for plugins)
  247. await client.session.prompt({
  248. path: { id: session.id },
  249. body: {
  250. noReply: true,
  251. parts: [{ type: "text", text: "You are a helpful assistant." }],
  252. },
  253. })
  254. ```
  255. ---
  256. ### Files
  257. | Method | Description | Response |
  258. | ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------- |
  259. | `find.text({ query })` | Search for text in files | Array of match objects with `path`, `lines`, `line_number`, `absolute_offset`, `submatches` |
  260. | `find.files({ query })` | Find files and directories by name | `string[]` (paths) |
  261. | `find.symbols({ query })` | Find workspace symbols | <a href={typesUrl}><code>Symbol[]</code></a> |
  262. | `file.read({ query })` | Read a file | `{ type: "raw" \| "patch", content: string }` |
  263. | `file.status({ query? })` | Get status for tracked files | <a href={typesUrl}><code>File[]</code></a> |
  264. `find.files` supports a few optional query fields:
  265. - `type`: `"file"` or `"directory"`
  266. - `directory`: override the project root for the search
  267. - `limit`: max results (1–200)
  268. ---
  269. #### Examples
  270. ```javascript
  271. // Search and read files
  272. const textResults = await client.find.text({
  273. query: { pattern: "function.*opencode" },
  274. })
  275. const files = await client.find.files({
  276. query: { query: "*.ts", type: "file" },
  277. })
  278. const directories = await client.find.files({
  279. query: { query: "packages", type: "directory", limit: 20 },
  280. })
  281. const content = await client.file.read({
  282. query: { path: "src/index.ts" },
  283. })
  284. ```
  285. ---
  286. ### TUI
  287. | Method | Description | Response |
  288. | ------------------------------ | ------------------------- | --------- |
  289. | `tui.appendPrompt({ body })` | Append text to the prompt | `boolean` |
  290. | `tui.openHelp()` | Open the help dialog | `boolean` |
  291. | `tui.openSessions()` | Open the session selector | `boolean` |
  292. | `tui.openThemes()` | Open the theme selector | `boolean` |
  293. | `tui.openModels()` | Open the model selector | `boolean` |
  294. | `tui.submitPrompt()` | Submit the current prompt | `boolean` |
  295. | `tui.clearPrompt()` | Clear the prompt | `boolean` |
  296. | `tui.executeCommand({ body })` | Execute a command | `boolean` |
  297. | `tui.showToast({ body })` | Show toast notification | `boolean` |
  298. ---
  299. #### Examples
  300. ```javascript
  301. // Control TUI interface
  302. await client.tui.appendPrompt({
  303. body: { text: "Add this to prompt" },
  304. })
  305. await client.tui.showToast({
  306. body: { message: "Task completed", variant: "success" },
  307. })
  308. ```
  309. ---
  310. ### Auth
  311. | Method | Description | Response |
  312. | ------------------- | ------------------------------ | --------- |
  313. | `auth.set({ ... })` | Set authentication credentials | `boolean` |
  314. ---
  315. #### Examples
  316. ```javascript
  317. await client.auth.set({
  318. path: { id: "anthropic" },
  319. body: { type: "api", key: "your-api-key" },
  320. })
  321. ```
  322. ---
  323. ### Events
  324. | Method | Description | Response |
  325. | ------------------- | ------------------------- | ------------------------- |
  326. | `event.subscribe()` | Server-sent events stream | Server-sent events stream |
  327. ---
  328. #### Examples
  329. ```javascript
  330. // Listen to real-time events
  331. const events = await client.event.subscribe()
  332. for await (const event of events.stream) {
  333. console.log("Event:", event.type, event.properties)
  334. }
  335. ```