feat(core): generate the opencode skill's API reference from openapi.json (#65836)

This commit is contained in:
Aiden Cline 2026-11-24 00:49:21 -06:00 • committed by GitHub
parent 1d9a0a0000
commit 10b9adbac5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 1342 additions and 10 deletions

View file

@ -2,4 +2,5 @@ sst-env.d.ts
packages/desktop/src/bindings.ts
packages/client/src/generated/
packages/client/src/generated-effect/
packages/core/src/plugin/skill/opencode/
packages/plugins/figma/skills/

View file

@ -22,6 +22,7 @@
"build": "bun run script/build.ts",
"pack": "bun run script/pack.ts",
"update-models-snapshot": "bun run script/update-models-snapshot.ts",
"generate:api-skill": "bun run script/generate-api-skill.ts",
"test": "bun run script/test.ts",
"typecheck": "bun check --no-script -b -p tsconfig.tests.json",
"typecheck:tsc": "tsc -b tsconfig.json tsconfig.tests.json"

View file

@ -0,0 +1,360 @@
#!/usr/bin/env bun
// Writes the `opencode` skill's API reference (`skill://opencode/api.md` and `api/<group>.md`) from the protocol's
// OpenAPI document. Protocol's `bun run generate` runs it after writing openapi.json; `bun run generate:api-skill` from
// packages/core runs it alone. test/opencode-api-skill.test.ts fails when the files are stale.
import fs from "node:fs/promises"
import path from "node:path"
type Schema = {
readonly $ref?: string
readonly type?: string | ReadonlyArray<string>
readonly enum?: ReadonlyArray<unknown>
readonly const?: unknown
readonly properties?: Readonly<Record<string, Schema>>
readonly required?: ReadonlyArray<string>
readonly items?: Schema
readonly additionalProperties?: boolean | Schema
readonly anyOf?: ReadonlyArray<Schema>
readonly oneOf?: ReadonlyArray<Schema>
readonly allOf?: ReadonlyArray<Schema>
readonly description?: string
}
type Parameter = {
readonly name: string
readonly in: string
readonly required?: boolean
readonly description?: string
readonly schema?: Schema
}
type Operation = {
readonly summary?: string
readonly description?: string
readonly parameters?: ReadonlyArray<Parameter>
readonly requestBody?: { readonly content?: Readonly<Record<string, { readonly schema?: Schema }>> }
readonly responses?: Readonly<
Record<string, { readonly content?: Readonly<Record<string, { readonly schema?: Schema }>> }>
>
}
type Document = {
readonly paths: Readonly<Record<string, Readonly<Record<string, Operation>>>>
readonly components?: { readonly schemas?: Readonly<Record<string, Schema>> }
}
type Endpoint = {
readonly method: string
readonly path: string
readonly group: string
readonly experimental: boolean
readonly operation: Operation
}
// Endpoints the reference documents, as `METHOD /path` with `*` matching anything. Anything not listed, including new
// routes, stays out until it's added here.
const SHOWN = [
// Sessions: hand work to other sessions, follow it and answer what they ask.
"GET /api/session",
"POST /api/session",
"GET /api/session/active",
"GET /api/session/{sessionID}",
"PATCH /api/session/{sessionID}",
"POST /api/session/{sessionID}/fork",
"POST /api/session/{sessionID}/agent",
"POST /api/session/{sessionID}/model",
"POST /api/session/{sessionID}/prompt",
"POST /api/session/{sessionID}/command",
"POST /api/session/{sessionID}/synthetic",
"POST /api/session/{sessionID}/compact",
"POST /api/session/{sessionID}/interrupt",
"POST /api/session/{sessionID}/generate",
"POST /api/experimental/session/{sessionID}/wait",
"GET /api/session/{sessionID}/context",
"GET /api/session/{sessionID}/diff",
"* /api/session/{sessionID}/inbox*",
"GET /api/session/{sessionID}/message*",
"GET /api/session/{sessionID}/form*",
"POST /api/session/{sessionID}/form/{formID}/reply",
"GET /api/session/{sessionID}/permission*",
"GET /api/form",
"GET /api/permission/request",
// Scheduling.
"* /api/experimental/automation*",
// Where the session is: location, projects, worktrees and version control.
"* /api/location*",
"* /api/project*",
"* /api/worktree*",
"* /api/vcs*",
// What's available.
"GET /api/info",
"GET /api/agent*",
"GET /api/command",
"GET /api/skill",
"GET /api/model*",
"GET /api/provider*",
// Generation, and the stored blobs it returns.
"* /api/experimental/generate*",
"GET /api/experimental/blob/*",
]
const INDEX_HEADER = [
"# OpenCode HTTP API",
"",
'Call any endpoint below from Code Mode with `fetch("opencode:///api/...")`. Each group\'s file lists its parameters, bodies and responses.',
"",
"- `current` in place of a session ID names the calling session, as in `opencode:///api/session/current`.",
"- Requests use the session's directory unless the `location[directory]` query or `x-opencode-directory` header sets one.",
"- Failed requests return a non-2xx status with `{ _tag, message }`.",
"",
]
const METHODS = ["get", "post", "put", "patch", "delete"]
// Types written out longer than this list only their field names.
const COMPACT = 240
export const directory = path.join(import.meta.dir, "../src/plugin/skill/opencode")
export async function render(): Promise<Record<string, string>> {
const document: Document = await Bun.file(path.join(import.meta.dir, "../../protocol/openapi.json")).json()
const schemas = document.components?.schemas ?? {}
const endpoints = Object.entries(document.paths)
.filter(([route]) => route.startsWith("/api/"))
.flatMap(([route, methods]) =>
METHODS.flatMap((method) => {
const operation = methods[method]
const experimental = route.startsWith("/api/experimental/")
if (!operation || !SHOWN.some((pattern) => matches(pattern, `${method.toUpperCase()} ${route}`))) return []
return [
{
method: method.toUpperCase(),
path: route,
group: route.slice(experimental ? "/api/experimental/".length : "/api/".length).split("/")[0]!,
experimental,
operation,
},
]
}),
)
const groups = Map.groupBy(endpoints, (endpoint) => endpoint.group)
const names = Array.from(groups.keys()).toSorted()
const index = [
...INDEX_HEADER,
...names.flatMap((name) => [
`## api/${name}.md`,
"",
...groups.get(name)!.map((endpoint) => `- ${heading(endpoint)}: ${endpoint.operation.summary ?? ""}`.trimEnd()),
"",
]),
]
return {
"api.md": `${index.join("\n").trimEnd()}\n`,
...Object.fromEntries(names.map((name) => [`api/${name}.md`, renderGroup(name, groups.get(name)!, schemas)])),
}
}
function renderGroup(name: string, endpoints: ReadonlyArray<Endpoint>, schemas: Readonly<Record<string, Schema>>) {
const types = new Set<string>()
const format = (schema: Schema | undefined) => formatSchema(schema, schemas, types)
const sections = endpoints.map((endpoint) => {
const operation = endpoint.operation
const description = (operation.description ?? operation.summary ?? "").split("Experimental:")[0]!.trim()
// Path parameters are named in the path itself, so they're listed only when described.
const parameters = (operation.parameters ?? []).filter(
(parameter) => parameter.name !== "location" && (parameter.in === "query" || describe(parameter, schemas)),
)
const body = operation.requestBody?.content?.["application/json"]?.schema
const bodyObject = body ? resolve(body, schemas) : undefined
const required = new Set(bodyObject?.required)
const fields = Object.entries(bodyObject?.properties ?? {})
return [
`## ${heading(endpoint)}`,
"",
...(description ? [description, ""] : []),
...(parameters.length > 0
? [
"Parameters:",
...parameters.map((parameter) =>
item(parameter.name, parameter.required ?? false, format(parameter.schema), describe(parameter, schemas)),
),
"",
]
: []),
...(fields.length > 0
? [
"Body:",
...fields.map(([field, schema]) =>
item(field, required.has(field), format(schema), describe({ schema }, schemas)),
),
"",
]
: []),
`Returns: ${returns(operation, format)}`,
].join("\n")
})
const expanded = expand(types, schemas)
return [
`# ${name}`,
"",
sections.join("\n\n"),
...(expanded.length > 0
? [
"",
"## Types",
"",
...expanded.map(
([type, shape]) =>
`- \`${type}\`: \`${shape}\`${schemas[type]?.description ? ` ${schemas[type]!.description}` : ""}`,
),
]
: []),
"",
].join("\n")
}
function matches(pattern: string, value: string) {
const parts = pattern.split("*")
if (parts.length === 1) return pattern === value
if (!value.startsWith(parts[0]!) || !value.endsWith(parts.at(-1)!)) return false
return (
parts.slice(1, -1).reduce<number | undefined>((at, part) => {
if (at === undefined) return undefined
const found = value.indexOf(part, at)
return found === -1 ? undefined : found + part.length
}, parts[0]!.length) !== undefined
)
}
function heading(endpoint: Endpoint) {
return `${endpoint.method} ${endpoint.path}${endpoint.experimental ? " (experimental)" : ""}`
}
function item(name: string, required: boolean, type: string, description: string | undefined) {
return `- \`${name}${required ? "" : "?"}: ${type}\`${description ? ` ${description}` : ""}`
}
// Aliases of a primitive, such as Session.ID for a string, read better as the primitive.
function alias(schema: Schema) {
return !schema.$ref && !schema.properties && !schema.items && !schema.anyOf && !schema.oneOf && !schema.allOf
}
// An inlined alias's description, such as steer vs queue on Session.Inbox.Delivery, belongs on the field; other named
// types carry theirs in the Types section.
function describe(
input: { readonly description?: string; readonly schema?: Schema },
schemas: Readonly<Record<string, Schema>>,
) {
const branches = [input.schema, ...(input.schema?.anyOf ?? [])].filter((branch) => branch !== undefined)
return (
input.description ??
branches.map((branch) => branch.description).find(Boolean) ??
branches
.map((branch) => (branch.$ref ? schemas[refName(branch.$ref)] : undefined))
.find((target) => target?.description && alias(target))?.description
)
}
function returns(operation: Operation, format: (schema: Schema | undefined) => string) {
const status = Object.keys(operation.responses ?? {})
.filter((code) => code.startsWith("2"))
.toSorted()[0]
const content = status ? operation.responses?.[status]?.content : undefined
if (!content) return "nothing"
if ("text/event-stream" in content) return "an event stream"
const json = content["application/json"]?.schema
if (json) return `\`${format(json)}\``
return Object.keys(content)[0] ?? "nothing"
}
// The named types a group mentions, each written out one level deep. Large ones list only their field names.
function expand(types: ReadonlySet<string>, schemas: Readonly<Record<string, Schema>>) {
const written = new Map<string, string>()
const pending = Array.from(types)
while (pending.length > 0) {
const type = pending.shift()!
if (written.has(type)) continue
const nested = new Set<string>()
const full = formatSchema(schemas[type], schemas, nested, 1)
const fields = Object.keys(resolve(schemas[type] ?? {}, schemas).properties ?? {})
const compact = full.length > COMPACT && fields.length > 0
written.set(type, compact ? `{ ${fields.join(", ")} }` : full)
if (!compact) pending.push(...nested)
}
return Array.from(written).toSorted(([a], [b]) => a.localeCompare(b))
}
function resolve(schema: Schema, schemas: Readonly<Record<string, Schema>>): Schema {
return schema.$ref ? resolve(schemas[refName(schema.$ref)] ?? {}, schemas) : schema
}
function refName(ref: string) {
return ref.slice("#/components/schemas/".length)
}
function formatSchema(
schema: Schema | undefined,
schemas: Readonly<Record<string, Schema>>,
types: Set<string>,
depth = 2,
): string {
if (!schema) return "unknown"
if (schema.$ref) {
const target = schemas[refName(schema.$ref)]
if (target && alias(target)) return formatSchema(target, schemas, types, depth)
types.add(refName(schema.$ref))
return refName(schema.$ref)
}
if (schema.const !== undefined) return JSON.stringify(schema.const)
if (schema.enum) return schema.enum.map((value) => JSON.stringify(value)).join(" | ")
const union = schema.anyOf ?? schema.oneOf
// Optional fields are encoded as `T | null`, where the field's `?` already says it can be left out, and numbers
// also accept the strings "Infinity", "-Infinity" and "NaN", which no caller needs to know.
if (union)
return Array.from(
new Set(
union
.filter((branch) => branch.type !== "null" && !branch.enum?.includes("NaN"))
.map((branch) => formatSchema(branch, schemas, types, depth)),
),
).join(" | ")
if (schema.allOf) return schema.allOf.map((branch) => formatSchema(branch, schemas, types, depth)).join(" & ")
if (Array.isArray(schema.type)) return schema.type.filter((type) => type !== "null").join(" | ")
if (schema.type === "array") {
const inner = formatSchema(schema.items, schemas, types, Math.max(0, depth - 1))
return inner.includes(" | ") ? `(${inner})[]` : `${inner}[]`
}
if (schema.type === "object" || schema.properties) {
const fields = Object.entries(schema.properties ?? {})
if (fields.length === 0)
return typeof schema.additionalProperties === "object"
? `Record<string, ${formatSchema(schema.additionalProperties, schemas, types, Math.max(0, depth - 1))}>`
: "Record<string, unknown>"
if (depth <= 0) return `{ ${fields.map(([field]) => field).join(", ")} }`
const required = new Set(schema.required)
return `{ ${fields.map(([field, value]) => `${field}${required.has(field) ? "" : "?"}: ${formatSchema(value, schemas, types, depth - 1)}`).join("; ")} }`
}
if (schema.type === "integer") return "number"
return typeof schema.type === "string" ? schema.type : "unknown"
}
if (import.meta.main) {
const files = await render()
await fs.rm(path.join(directory, "api"), { recursive: true, force: true })
await Promise.all(Object.entries(files).map(([file, content]) => Bun.write(path.join(directory, file), content)))
await Bun.write(
path.join(directory, "api.ts"),
[
'/// <reference path="../../../markdown.d.ts" />',
"// Generated by script/generate-api-skill.ts.",
"",
...Object.keys(files).map((file, i) => `import file${i} from "./${file}" with { type: "text" }`),
"",
"export const files: Record<string, string> = {",
...Object.keys(files).map((file, i) => ` ${JSON.stringify(file)}: file${i},`),
"}",
"",
].join("\n"),
)
}

View file

@ -8,9 +8,12 @@ import { Effect } from "effect"
import { AbsolutePath } from "../schema.js"
import { Skill } from "../skill.js"
import { Config } from "../config.js"
import { Flag } from "../flag.js"
import os from "os"
import opencodeContent from "./skill/opencode.md" with { type: "text" }
import reportContent from "./skill/report.md" with { type: "text" }
import apiContent from "./skill/opencode-api.md" with { type: "text" }
import { files as apiFiles } from "./skill/opencode/api.js"
export const OpencodeContent = opencodeContent
export const ReportContent = reportContent
@ -24,15 +27,20 @@ export const Plugin = define({
id: "opencode.skill",
effect: Effect.fn(function* (ctx) {
const reportContent = yield* reportContentWithDiagnostics(ctx.app)
yield* ctx.skill.transform((editor) => {
const api = yield* Flag.enabled("opencode_api")
const skills = yield* Skill.Service
// Skill.Service rather than ctx.skill, whose editor can't add a skill's files.
yield* skills.transform((editor) => {
editor.add(
Skill.Info.make({
id: Skill.ID.make("opencode"),
name: Skill.Name.make("OpenCode"),
description: OpencodeDescription,
path: AbsolutePath.make("skill://opencode/SKILL.md"),
content: OpencodeContent,
// With opencode:// fetch, its API section points there instead of the `opencode api` command.
content: api ? OpencodeContent.replace(/## \[API\][^]*?(?=## \[Client\])/, apiContent) : OpencodeContent,
}),
api ? apiFiles : undefined,
)
editor.add(
Skill.Info.make({

View file

@ -0,0 +1,17 @@
## [API](https://opencode.ai/docs/api)
OpenCode exposes an HTTP API from its server.
In Code Mode, use the built-in `opencode` tool namespace first, called inside
`execute` as `tools.opencode.*`; find its tools with Code Mode's `search`, for
example `search({ namespace: "opencode" })`. For anything they do not cover, call
the API with `fetch("opencode:///api/...")`. It reaches this OpenCode server,
already signed in, and uses the session's directory. `current` in place of a
session ID names the calling session:
```js
const session = await (await fetch("opencode:///api/session/current")).json()
```
Read `skill://opencode/api.md` for the available endpoints, then the file it
points to for the group you need.

View file

@ -0,0 +1,120 @@
# OpenCode HTTP API
Call any endpoint below from Code Mode with `fetch("opencode:///api/...")`. Each group's file lists its parameters, bodies and responses.
- `current` in place of a session ID names the calling session, as in `opencode:///api/session/current`.
- Requests use the session's directory unless the `location[directory]` query or `x-opencode-directory` header sets one.
- Failed requests return a non-2xx status with `{ _tag, message }`.
## api/agent.md
- GET /api/agent: List agents
- GET /api/agent/{agentID}: Get agent
## api/automation.md
- GET /api/experimental/automation (experimental): List automations
- POST /api/experimental/automation (experimental): Create automation
- GET /api/experimental/automation/{automationID} (experimental): Get automation
- DELETE /api/experimental/automation/{automationID} (experimental): Delete automation
- POST /api/experimental/automation/{automationID}/pause (experimental): Pause automation
- POST /api/experimental/automation/{automationID}/resume (experimental): Resume automation
## api/blob.md
- GET /api/experimental/blob/{id} (experimental): Read a blob
## api/command.md
- GET /api/command: List commands
## api/form.md
- GET /api/form: List pending forms
## api/generate.md
- POST /api/experimental/generate/text (experimental): Generate text
- POST /api/experimental/generate (experimental): Generate text (deprecated path)
- POST /api/experimental/generate/image (experimental): Generate images
- POST /api/experimental/generate/video (experimental): Create a video generation
- GET /api/experimental/generate/video/{id} (experimental): Read a video generation
- POST /api/experimental/generate/decisions (experimental): Generate decisions
## api/info.md
- GET /api/info: Get server info
## api/location.md
- GET /api/location: Get location
- POST /api/location/reload: Reload configuration
## api/model.md
- GET /api/model: List models
- GET /api/model/default: Get default model
## api/permission.md
- GET /api/permission/request: List pending permission requests
## api/project.md
- GET /api/project: List projects
- PATCH /api/project/{projectID}: Update project
## api/provider.md
- GET /api/provider: List providers
- GET /api/provider/{providerID}: Get provider
## api/session.md
- GET /api/session: List sessions
- POST /api/session: Create session
- GET /api/session/active: List active sessions
- GET /api/session/{sessionID}: Get session
- PATCH /api/session/{sessionID}: Update session
- POST /api/session/{sessionID}/fork: Fork session
- POST /api/session/{sessionID}/agent: Switch session agent
- POST /api/session/{sessionID}/model: Switch session model
- POST /api/session/{sessionID}/prompt: Send message
- POST /api/session/{sessionID}/command: Run command
- POST /api/session/{sessionID}/synthetic: Add synthetic message
- POST /api/session/{sessionID}/compact: Compact session
- POST /api/experimental/session/{sessionID}/wait (experimental): Wait for session
- GET /api/session/{sessionID}/context: Get session context
- GET /api/session/{sessionID}/diff: Diff session turns
- GET /api/session/{sessionID}/inbox: List session inbox
- PATCH /api/session/{sessionID}/inbox/{inboxID}: Update inbox item
- DELETE /api/session/{sessionID}/inbox/{inboxID}: Cancel inbox input
- POST /api/session/{sessionID}/generate: Generate text from session context
- POST /api/session/{sessionID}/interrupt: Interrupt session execution
- GET /api/session/{sessionID}/message/{messageID}: Get session message
- GET /api/session/{sessionID}/form: List session forms
- GET /api/session/{sessionID}/form/{formID}: Get session form
- POST /api/session/{sessionID}/form/{formID}/reply: Reply to form
- GET /api/session/{sessionID}/message: Get session messages
- GET /api/session/{sessionID}/permission: List session permission requests
- GET /api/session/{sessionID}/permission/{requestID}: Get permission request
## api/skill.md
- GET /api/skill: List skills
## api/vcs.md
- POST /api/vcs/init: Initialize VCS repository
- GET /api/vcs: VCS info
- GET /api/vcs/base: VCS review base
- GET /api/vcs/status: VCS status
- GET /api/vcs/branch: VCS branches
- GET /api/vcs/diff: VCS diff
## api/worktree.md
- GET /api/worktree: List worktrees
- POST /api/worktree: Create worktree
- DELETE /api/worktree: Remove worktree
- POST /api/worktree/refresh: Refresh worktrees

View file

@ -0,0 +1,40 @@
/// <reference path="../../../markdown.d.ts" />
// Generated by script/generate-api-skill.ts.
import file0 from "./api.md" with { type: "text" }
import file1 from "./api/agent.md" with { type: "text" }
import file2 from "./api/automation.md" with { type: "text" }
import file3 from "./api/blob.md" with { type: "text" }
import file4 from "./api/command.md" with { type: "text" }
import file5 from "./api/form.md" with { type: "text" }
import file6 from "./api/generate.md" with { type: "text" }
import file7 from "./api/info.md" with { type: "text" }
import file8 from "./api/location.md" with { type: "text" }
import file9 from "./api/model.md" with { type: "text" }
import file10 from "./api/permission.md" with { type: "text" }
import file11 from "./api/project.md" with { type: "text" }
import file12 from "./api/provider.md" with { type: "text" }
import file13 from "./api/session.md" with { type: "text" }
import file14 from "./api/skill.md" with { type: "text" }
import file15 from "./api/vcs.md" with { type: "text" }
import file16 from "./api/worktree.md" with { type: "text" }
export const files: Record<string, string> = {
"api.md": file0,
"api/agent.md": file1,
"api/automation.md": file2,
"api/blob.md": file3,
"api/command.md": file4,
"api/form.md": file5,
"api/generate.md": file6,
"api/info.md": file7,
"api/location.md": file8,
"api/model.md": file9,
"api/permission.md": file10,
"api/project.md": file11,
"api/provider.md": file12,
"api/session.md": file13,
"api/skill.md": file14,
"api/vcs.md": file15,
"api/worktree.md": file16,
}

View file

@ -0,0 +1,18 @@
# agent
## GET /api/agent
Retrieve currently registered agents.
Returns: `{ location: Location.PublicRef; data: Agent.Info[] }`
## GET /api/agent/{agentID}
Retrieve a single currently registered agent.
Returns: `{ location: Location.PublicRef; data: Agent.Info }`
## Types
- `Agent.Info`: `{ id, name, model, request, system, instructions, description, mode, hidden, color, steps, permissions }`
- `Location.PublicRef`: `{ directory: string }`

View file

@ -0,0 +1,63 @@
# automation
## GET /api/experimental/automation (experimental)
List automations, oldest first.
Parameters:
- `sessionID?: string` Only automations created by this Session.
- `directory?: string` Only automations in the project that owns this directory.
Returns: `{ data: Automation.Info[] }`
## POST /api/experimental/automation (experimental)
Create an automation that sends a prompt, runs a Code Mode program, or runs a shell command at a time, every interval, or on a cron. Creating an MCP event watch requires the automation_create tool in a local session; a session ID over HTTP is not a watch authorization.
Body:
- `sessionID?: string`
- `directory?: string` Where it runs when there is no Session. Defaults to the server user's home folder.
- `name: string` A short label shown in lists.
- `trigger: Automation.Trigger`
- `action: Automation.ActionInput`
- `expires?: string`
Returns: `{ data: Automation.Info }`
## GET /api/experimental/automation/{automationID} (experimental)
Read one automation.
Returns: `{ data: Automation.Info }`
## DELETE /api/experimental/automation/{automationID} (experimental)
Delete an automation.
Returns: nothing
## POST /api/experimental/automation/{automationID}/pause (experimental)
Stop an automation from running until it is resumed.
Returns: `{ data: Automation.Info }`
## POST /api/experimental/automation/{automationID}/resume (experimental)
Resume a paused automation. A missed `at` runs once; repeating timers resume at their next slot. Event watches request replay from their saved cursor.
Returns: `{ data: Automation.Info }`
## Types
- `Automation.ActionInput`: `Automation.PromptActionInput | Automation.CodeActionInput | Automation.ShellActionInput` What it does: { type: "prompt", prompt, to? } sends a prompt; { type: "code", code, args? } runs Code Mode; { type: "shell", command } runs a fixed shell command.
- `Automation.CodeActionInput`: `{ type: "code"; code: string; args?: unknown }`
- `Automation.Info`: `{ id, name, projectID, sessionID, directory, trigger, tz, action, expires, status, nextDueAt, runCount, lastRunAt, lastOutcome, lastOutput, state, time }`
- `Automation.PromptActionInput`: `{ type: "prompt"; prompt: string; to?: Automation.Target }`
- `Automation.ShellActionInput`: `{ type: "shell"; command: string }`
- `Automation.Target`: `{ session: string; subagent?: unknown } | { subagent: string; session?: unknown }`
- `Automation.Trigger`: `Automation.Trigger.At | Automation.Trigger.Every | Automation.Trigger.Cron | Automation.Trigger.Event` When it runs: { type: "at", at: "in 20 minutes" | "2026-10-27T09:00" }, { type: "every", every: "1 hour" } or { type: "cron", cron: "0 9 * * 1-5" }, each with an optional tz. Or { type: "event", server, event, args? } for a connected MCP server advertising push delivery.
- `Automation.Trigger.At`: `{ type: "at"; at: string; tz?: string }`
- `Automation.Trigger.Cron`: `{ type: "cron"; cron: string; tz?: string }`
- `Automation.Trigger.Event`: `{ type: "event"; server: string; event: string; args?: Record<string, unknown> }`
- `Automation.Trigger.Every`: `{ type: "every"; every: string; tz?: string }`

View file

@ -0,0 +1,10 @@
# blob
## GET /api/experimental/blob/{id} (experimental)
Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. A blob is deleted a week after it was stored.
Parameters:
- `id: string` A stored blob, such as a generated video, which outlives the job that made it
Returns: application/octet-stream

View file

@ -0,0 +1,12 @@
# command
## GET /api/command
Retrieve currently registered commands.
Returns: `{ location: Location.PublicRef; data: Command.Info[] }`
## Types
- `Command.Info`: `{ name: string; description?: string }`
- `Location.PublicRef`: `{ directory: string }`

View file

@ -0,0 +1,22 @@
# form
## GET /api/form
Retrieve pending forms for a location.
Returns: `{ location: Location.PublicRef; data: Form.Info[] }`
## Types
- `Form.BooleanField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "boolean"; default?: boolean }`
- `Form.ExternalField`: `{ key: string; type: "external"; url: string; title?: string; description?: string }`
- `Form.Field`: `Form.StringField | Form.NumberField | Form.IntegerField | Form.BooleanField | Form.MultiselectField | Form.ExternalField`
- `Form.Fields`: `Form.Field[]`
- `Form.Info`: `{ id: string; sessionID: string; title: string; metadata?: Record<string, unknown>; fields: Form.Fields }`
- `Form.IntegerField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "integer"; minimum?: number; maximum?: number; default?: number }`
- `Form.MultiselectField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "multiselect"; options: Form.Option[]; minItems?: number; maxItems?: number; custom?: boolean; default?: string[] }`
- `Form.NumberField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "number"; minimum?: number; maximum?: number; default?: number }`
- `Form.Option`: `{ value: string; label: string; description?: string }`
- `Form.StringField`: `{ key, title, description, required, hidden, when, type, format, minLength, maxLength, pattern, placeholder, default, options, custom }`
- `Form.When`: `{ key: string; op: "eq" | "neq"; value: string | number | boolean }`
- `Location.PublicRef`: `{ directory: string }`

View file

@ -0,0 +1,106 @@
# generate
## POST /api/experimental/generate/text (experimental)
Run one stateless model generation using the server's base configuration and return the assistant text. Uses the base configuration's default model when none is specified.
Body:
- `prompt: string`
- `model?: Model.Ref`
Returns: `GenerateTextResponse`
## POST /api/experimental/generate (experimental)
Deprecated alias of POST /api/experimental/generate/text.
Body:
- `prompt: string`
- `model?: Model.Ref`
Returns: `GenerateTextResponse`
## POST /api/experimental/generate/image (experimental)
Generate or edit images with an image model using the server's base configuration and return them as base64. Stateless: nothing is stored.
Body:
- `model: Model.Ref`
- `prompt: string`
- `images?: Generate.File[]`
- `n?: number`
- `aspect?: string` Aspect ratio as width:height, for example 16:9
- `resolution?: Generate.ImageResolution`
Returns: `GenerateImageResponse`
## POST /api/experimental/generate/video (experimental)
Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished videos as blobs; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id.
Body:
- `model: Model.Ref`
- `prompt: string`
- `start?: Generate.ImageFile`
- `end?: Generate.ImageFile`
- `references?: Generate.File[]`
- `duration?: number`
- `aspect?: Generate.VideoAspect`
- `resolution?: Generate.VideoResolution`
- `sound?: boolean`
Returns: `GenerateVideoCreateResponse`
## GET /api/experimental/generate/video/{id} (experimental)
Read a video job: running, completed with its videos' blobs, or error with a reason. Jobs survive a server restart, which resumes polling running ones. A job is not found 24 hours after it finished, or once none of its blobs remain.
Returns: `GenerateVideoGetResponse`
## POST /api/experimental/generate/decisions (experimental)
Ask a decision model typed predicate, choice and score questions about the input and return one probability-bearing answer per question, in question order. Stateless: nothing is stored.
Body:
- `model: Model.Ref`
- `input: Generate.DecisionPart[]` The evidence every question is asked about, in order
- `questions: Generate.DecisionQuestion[]` Question names must be unique; duplicates fail with InvalidRequestError
Returns: `GenerateDecisionsResponse`
## Types
- `Blob.Info`: `{ id: string; mime: string; bytes: number }`
- `Generate.ChoiceAnswer`: `{ type: "choice"; name: string; choice: Generate.ChoiceValue; probabilities: { value, probability }[]; confidence: number }`
- `Generate.ChoiceQuestion`: `{ type: "choice"; name: string; instructions: string; choices: { value, description }[] }` Pick one value from a fixed set
- `Generate.ChoiceValue`: `string | boolean` Choice values are typed: true and "true" are different values
- `Generate.DecisionAnswer`: `Generate.PredicateAnswer | Generate.ChoiceAnswer | Generate.ScoreAnswer | Generate.ErrorAnswer`
- `Generate.DecisionFilePart`: `{ type: "file"; data: string; mime: string; name?: string }`
- `Generate.DecisionJsonPart`: `{ type: "json"; value: unknown }`
- `Generate.DecisionPart`: `Generate.DecisionTextPart | Generate.DecisionJsonPart | Generate.DecisionFilePart`
- `Generate.DecisionQuestion`: `Generate.PredicateQuestion | Generate.ChoiceQuestion | Generate.ScoreQuestion`
- `Generate.DecisionResult`: `{ answers: Generate.DecisionAnswer[]; cost?: number; tokens?: Generate.Usage; native?: Record<string, unknown> }`
- `Generate.DecisionTextPart`: `{ type: "text"; text: string }`
- `Generate.ErrorAnswer`: `{ type: "error"; name: string; reason: string; message?: string }` This one question has no answer; the other answers still came back
- `Generate.File`: `{ data: string; mime: string; name?: string }`
- `Generate.ImageFile`: `{ data: string; mime: string; name?: string }`
- `Generate.ImageOutput`: `{ type: "image"; data: string; mime: string; name?: string }`
- `Generate.ImageResolution`: `"1K" | "2K" | "4K" | string` Size tier such as 1K, 2K or 4K; 1K is about as many pixels as 1024x1024 at the requested aspect
- `Generate.ImageResult`: `{ images: Generate.ImageOutput[]; cost?: number; tokens?: Generate.Usage; native?: Record<string, unknown> }`
- `Generate.PredicateAnswer`: `{ type: "predicate"; name: string; probability: number }`
- `Generate.PredicateQuestion`: `{ type: "predicate"; name: string; instructions: string; criteria?: { true, false } }` The probability that a statement is true
- `Generate.ScoreAnswer`: `{ type: "score"; name: string; score: number; probabilities: { value, label, probability }[]; confidence: number }`
- `Generate.ScoreQuestion`: `{ type: "score"; name: string; instructions: string; levels: { label, description }[] }` Place the input on ordered levels, lowest first
- `Generate.Usage`: `{ input?: number; output?: number }` Token counts, when the provider reports them
- `Generate.VideoAspect`: `string | "auto"` Aspect ratio as width:height, or auto to follow the start image
- `Generate.VideoCompleted`: `{ id: string; status: "completed"; blobs: Blob.Info[] }`
- `Generate.VideoError`: `{ id: string; status: "error"; error: string; reason: "failed" | "cancelled" | "expired" | "unknown" }`
- `Generate.VideoJob`: `Generate.VideoRunning | Generate.VideoCompleted | Generate.VideoError`
- `Generate.VideoResolution`: `"480p" | "720p" | "1080p" | "4k" | string`
- `Generate.VideoRunning`: `{ id: string; status: "running" }`
- `GenerateDecisionsResponse`: `{ data: Generate.DecisionResult }`
- `GenerateImageResponse`: `{ data: Generate.ImageResult }`
- `GenerateTextResponse`: `{ data: { text } }`
- `GenerateVideoCreateResponse`: `{ data: Generate.VideoRunning }`
- `GenerateVideoGetResponse`: `{ data: Generate.VideoJob }`
- `Model.Ref`: `{ id: string; providerID: string; variant?: string }`

View file

@ -0,0 +1,11 @@
# info
## GET /api/info
Return the server identity, connection URLs, paths, and readiness status.
Returns: `ServerInfo`
## Types
- `ServerInfo`: `{ version: string; pid: number; hostname?: string; urls: string[]; paths: { tmp }; capabilities?: { persistentPty } }`

View file

@ -0,0 +1,17 @@
# location
## GET /api/location
Resolve the requested location or the server default location.
Returns: `Location.PublicInfo`
## POST /api/location/reload
Shut down and rebuild every loaded location. Pending permissions and forms are cancelled; running sessions continue with fresh services at the next step boundary. Emits location.shutdown for client recovery and responds once all replacement builds settle.
Returns: nothing
## Types
- `Location.PublicInfo`: `{ directory: string; project: { id, directory, canonical } }`

View file

@ -0,0 +1,22 @@
# model
## GET /api/model
Retrieve the current snapshot of available models of the requested types, chat by default, ordered by release date within each type. The snapshot may precede initial plugin settlement.
Parameters:
- `types?: Model.Type | Model.Type[]` Only list models of these types. Defaults to chat, the only type offered for sessions.
Returns: `{ location: Location.PublicRef; data: Model.Info[] }`
## GET /api/model/default
Retrieve the model used when a session has no explicit model selection.
Returns: `{ location: Location.PublicRef; data: Model.Info }`
## Types
- `Location.PublicRef`: `{ directory: string }`
- `Model.Info`: `{ id, modelID, providerID, canonical, type, family, name, compatibility, package, settings, headers, body, capabilities, variants, experimental, time, cost, status, enabled, limit }`
- `Model.Type`: `"chat" | "decision" | "image" | "video" | string`

View file

@ -0,0 +1,13 @@
# permission
## GET /api/permission/request
Retrieve pending permission requests for a location.
Returns: `{ location: Location.PublicRef; data: Permission.Request[] }`
## Types
- `Location.PublicRef`: `{ directory: string }`
- `Permission.Request`: `{ id: string; sessionID: string; action: string; resources: string[]; save?: string[]; metadata?: Record<string, unknown>; source?: Permission.Source; message?: string }`
- `Permission.Source`: `{ type: "tool"; messageID: string; id: string }`

View file

@ -0,0 +1,29 @@
# project
## GET /api/project
List known projects. Archived projects are excluded unless archived=true.
Parameters:
- `archived?: "true" | "false"` Set to true to include archived projects.
Returns: `Project[]`
## PATCH /api/project/{projectID}
Update the project canonical directory, display metadata, and workspace commands.
Body:
- `canonical?: string`
- `name?: string`
- `icon?: Project.Icon`
- `commands?: Project.Commands`
Returns: `Project`
## Types
- `Project`: `{ id: string; canonical: string; vcs?: string; name?: string; icon?: Project.Icon; commands?: Project.Commands; time: Project.Time; sandboxes: string[] }`
- `Project.Commands`: `{ start?: string }`
- `Project.Icon`: `{ url?: string; override?: string; color?: string }`
- `Project.Time`: `{ created: number; updated: number; active: number; archived?: number }`

View file

@ -0,0 +1,18 @@
# provider
## GET /api/provider
Retrieve active AI providers so clients can show provider availability and configuration.
Returns: `{ location: Location.PublicRef; data: Provider.Info[] }`
## GET /api/provider/{providerID}
Retrieve a single AI provider so clients can inspect its availability and endpoint settings.
Returns: `{ location: Location.PublicRef; data: Provider.Info }`
## Types
- `Location.PublicRef`: `{ directory: string }`
- `Provider.Info`: `{ id, canonical, integrationID, name, activation, package, compatibility, settings, headers, body }`

View file

@ -0,0 +1,313 @@
# session
## GET /api/session
Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list.
Parameters:
- `limit?: string` Maximum number of sessions to return. Defaults to the newest 50 sessions.
- `order?: "asc" | "desc"` Session order for the first page. Use desc for newest first or asc for oldest first.
- `search?: string` Only sessions whose title contains this text, ignoring case. % and _ act as wildcards.
- `parentID?: string | "null"` Filter by parent session. Use null to return only root sessions.
- `archived?: "true" | "false"` Filter by archive state. Use true to return only archived sessions or false to exclude them. Omit to include both.
- `directory?: string` Only sessions whose directory is exactly this absolute path.
- `project?: string`
- `subpath?: string` With project, only sessions at this path relative to the project directory.
- `cursor?: string` Opaque cursor from a previous page's cursor.next or cursor.previous. It carries that page's filters and order, so other filters are ignored.
Returns: `SessionsResponse`
## POST /api/session
Create a session at the requested location. A parentID creates a linked child session at its parent's location.
Body:
- `id?: string` If a session with this ID already exists, it is returned unchanged, so retries are safe.
- `parentID?: string` Creates a child session at the parent's location. Each time the child finishes running, it sends its last reply to the parent as a `<background-result kind="subagent">` message and wakes the parent, unless the parent has a staged revert.
- `title?: string`
- `agent?: string`
- `model?: Model.Ref`
- `location?: Location.PublicRef` Defaults to the server's working directory. Ignored when parentID is set.
- `metadata?: Record<string, unknown>` Opaque to OpenCode. Child sessions inherit the parent's metadata unless you pass your own.
- `permissions?: Permission.Ruleset` Applied on top of the agent's rules. Child sessions inherit the parent's rules unless you pass your own.
Returns: `{ data: Session.Info }`
## GET /api/session/active
List the sessions whose agent is running right now in this server process. Sessions missing from the result are idle.
Returns: `{ data: Record<string, unknown> }`
## GET /api/session/{sessionID}
Retrieve a session by ID.
Returns: `{ data: Session.Info }`
## PATCH /api/session/{sessionID}
Update mutable session properties.
Body:
- `title?: string`
- `metadata?: Record<string, unknown>`
- `permissions?: Permission.Ruleset`
- `archived?: boolean` Archive the session with true or restore it with false. Repeating the current state is a no-op.
Returns: nothing
## POST /api/session/{sessionID}/fork
Create a child session with this session's history before a message. Omit before to copy the full history.
Body:
- `before?: string`
Returns: `{ data: Session.Info }`
## POST /api/session/{sessionID}/agent
Change the agent the session uses from its next model call on.
Body:
- `agent: string`
Returns: nothing
## POST /api/session/{sessionID}/model
Change the model the session uses from its next model call on.
Body:
- `model: Model.Ref`
Returns: nothing
## POST /api/session/{sessionID}/prompt
Send a user message and start the agent unless resume is false. Returns once the message is queued, not when the agent finishes: wait with experimental.session.wait or the session.execution.* events, then read the reply with session.message.list.
Body:
- `id?: string` Sending the same ID again returns the original item instead of adding a second one, so retries are safe. Reusing it in another session or for another kind of item fails with 409.
- `text: string`
- `files?: PromptInput.FileAttachment[]`
- `agents?: Prompt.AgentAttachment[]`
- `skills?: PromptInput.SkillAttachment[]`
- `metadata?: Record<string, unknown>` Stored on the message. The model doesn't see it.
- `delivery?: "steer" | "queue"` steer delivers before the agent's next model call, even mid-work. queue waits until the agent finishes its current work, then delivers one queued item at a time. Sending defaults to steer.
- `resume?: boolean` false adds the message to the inbox without starting the agent; it is delivered the next time the session runs.
Returns: `{ data: Session.Inbox.User }`
## POST /api/session/{sessionID}/command
Run a named command in the session. Most commands send a prompt, so like session.prompt this returns before the agent finishes.
Body:
- `name: string`
- `text: string` The command's arguments.
- `files?: PromptInput.FileAttachment[]`
- `agents?: Prompt.AgentAttachment[]`
- `skills?: PromptInput.SkillAttachment[]`
- `delivery?: "steer" | "queue"` steer delivers before the agent's next model call, even mid-work. queue waits until the agent finishes its current work, then delivers one queued item at a time. Sending defaults to steer.
Returns: nothing
## POST /api/session/{sessionID}/synthetic
Add a message the model reads as user input but the user didn't type, such as a notification. Starts the agent unless resume is false or the session has a staged revert.
Body:
- `id?: string` Sending the same ID again returns the original item instead of adding a second one, so retries are safe. Reusing it in another session or for another kind of item fails with 409.
- `text: string`
- `description?: string` Short label shown in the transcript instead of the full text.
- `metadata?: Record<string, unknown>` Stored on the message. The model doesn't see it.
- `delivery?: "steer" | "queue"` steer delivers before the agent's next model call, even mid-work. queue waits until the agent finishes its current work, then delivers one queued item at a time. Sending defaults to steer.
- `resume?: boolean` false adds the message to the inbox without starting the agent; it is delivered the next time the session runs.
Returns: `{ data: Session.Inbox.Synthetic }`
## POST /api/session/{sessionID}/compact
Queue a summary of the session's history. Steers by default: it runs before the next model call, ahead of queued messages.
Body:
- `id?: string`
- `delivery?: "steer" | "queue"` steer delivers before the agent's next model call, even mid-work. queue waits until the agent finishes its current work, then delivers one queued item at a time. Sending defaults to steer.
Returns: `{ data: Session.Inbox.Compaction }`
## POST /api/experimental/session/{sessionID}/wait (experimental)
Wait until the session's agent stops running in this server process. Returns at once when idle.
Returns: nothing
## GET /api/session/{sessionID}/context
Retrieve the active context messages for a session (all messages after the last compaction).
Returns: `{ data: Session.Message.Info[] }`
## GET /api/session/{sessionID}/diff
Structured per-file diffs of the files a turn changed. A turn runs from the first prompt after the session was last idle until its next idle marker, so prompts steered in while it was busy belong to the same turn; `to` extends the range through a later turn. Compares the range's first recorded snapshot with its last; a step still running in the active session compares against the working copy. Ranges that span a location change are rejected. In sessions without any idle marker, a prompt's turn spans until the next user message.
Parameters:
- `from?: string` User message whose turn to diff. Defaults to the turn of the newest user message.
- `to?: string` Later user message whose turn ends the range. Defaults to the turn of `from` alone.
- `context?: string` Unchanged lines around each hunk. Omit for full-file patches.
Returns: `{ data: FileDiff.Info[] }`
## GET /api/session/{sessionID}/inbox
List user, synthetic, compaction and move items not yet delivered to the agent, oldest first. Delivered user and synthetic items move to session.message.list.
Returns: `{ data: Session.Inbox.Info[] }`
## PATCH /api/session/{sessionID}/inbox/{inboxID}
Change a pending inbox item's delivery mode. Steering wakes session execution.
Body:
- `delivery: "steer" | "queue"` steer delivers before the agent's next model call, even mid-work. queue waits until the agent finishes its current work, then delivers one queued item at a time. Sending defaults to steer.
Returns: nothing
## DELETE /api/session/{sessionID}/inbox/{inboxID}
Cancel an inbox item that has not yet been delivered. Unavailable items are a no-op.
Returns: nothing
## POST /api/session/{sessionID}/generate
Generate transient text from the current session context without mutating session history. Its tokens and cost count toward the session's totals.
Body:
- `prompt: string`
Returns: `SessionGenerateResponse`
## POST /api/session/{sessionID}/interrupt
Stop the session's agent if it is running in this server process; interrupted=false means nothing was running. With resume=true it continues with pending steer items, compaction and moves, while queued messages keep waiting.
Parameters:
- `resume?: "true" | "false"` Set to true to resume pending steering input and next-in-line control items after interrupting.
Returns: `SessionInterruptResponse`
## GET /api/session/{sessionID}/message/{messageID}
Retrieve one message of the session by ID.
Returns: `{ data: Session.Message.Info }`
## GET /api/session/{sessionID}/form
Retrieve pending forms for a session.
Returns: `{ data: Form.Info[] }`
## GET /api/session/{sessionID}/form/{formID}
Retrieve a form and its current state for a session.
Returns: `{ data: Form.Detail }`
## POST /api/session/{sessionID}/form/{formID}/reply
Submit an answer to a pending form.
Body:
- `answer: Record<string, Form.Value>`
Returns: nothing
## GET /api/session/{sessionID}/message
List a session's messages, optionally filtered by type. Follow cursor.next or cursor.previous with the same type filter. Items still in the inbox aren't included.
Parameters:
- `limit?: string` Maximum number of messages to return. When omitted, the endpoint returns its default page size.
- `order?: "asc" | "desc"` Message order for the first page. Use desc for newest first or asc for oldest first.
- `cursor?: string` Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order.
- `type?: "agent-switched" | "model-switched" | "location-switched" | "user" | "synthetic" | "system" | "skill" | "shell" | "assistant" | "compaction" | "idle"` Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors.
Returns: `SessionMessagesResponse`
## GET /api/session/{sessionID}/permission
Retrieve pending permission requests owned by a session.
Returns: `{ data: Permission.Request[] }`
## GET /api/session/{sessionID}/permission/{requestID}
Retrieve a pending permission request owned by a session.
Returns: `{ data: Permission.Request }`
## Types
- `FileDiff.Info`: `{ file: string; patch: string; additions: number; deletions: number; status: "added" | "deleted" | "modified"; more?: true }`
- `Form.BooleanField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "boolean"; default?: boolean }`
- `Form.Detail`: `{ id: string; sessionID: string; title: string; metadata?: Record<string, unknown>; fields: Form.Fields; state: Form.State }`
- `Form.ExternalField`: `{ key: string; type: "external"; url: string; title?: string; description?: string }`
- `Form.Field`: `Form.StringField | Form.NumberField | Form.IntegerField | Form.BooleanField | Form.MultiselectField | Form.ExternalField`
- `Form.Fields`: `Form.Field[]`
- `Form.Info`: `{ id: string; sessionID: string; title: string; metadata?: Record<string, unknown>; fields: Form.Fields }`
- `Form.IntegerField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "integer"; minimum?: number; maximum?: number; default?: number }`
- `Form.MultiselectField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "multiselect"; options: Form.Option[]; minItems?: number; maxItems?: number; custom?: boolean; default?: string[] }`
- `Form.NumberField`: `{ key: string; title?: string; description?: string; required?: boolean; hidden?: boolean; when?: Form.When[]; type: "number"; minimum?: number; maximum?: number; default?: number }`
- `Form.Option`: `{ value: string; label: string; description?: string }`
- `Form.State`: `{ status: "pending" } | { status: "answered"; answer: Record<string, Form.Value> } | { status: "cancelled"; message?: string }`
- `Form.StringField`: `{ key, title, description, required, hidden, when, type, format, minLength, maxLength, pattern, placeholder, default, options, custom }`
- `Form.Value`: `string | number | boolean | string[]`
- `Form.When`: `{ key: string; op: "eq" | "neq"; value: string | number | boolean }`
- `Location.PublicRef`: `{ directory: string }`
- `Model.Ref`: `{ id: string; providerID: string; variant?: string }`
- `Permission.Request`: `{ id: string; sessionID: string; action: string; resources: string[]; save?: string[]; metadata?: Record<string, unknown>; source?: Permission.Source; message?: string }`
- `Permission.Rule`: `{ action: string; resource: string; effect: "allow" | "deny" | "ask" }`
- `Permission.Ruleset`: `Permission.Rule[]`
- `Permission.Source`: `{ type: "tool"; messageID: string; id: string }`
- `Prompt.AgentAttachment`: `{ name: string; mention?: Prompt.Mention }` An agent @-mentioned in the prompt, such as @explore, to suggest the model use it. Only the @name in text reaches the model; this records which agent it names and doesn't change the session's own agent.
- `Prompt.FileAttachment`: `{ data: string; mime: string; source: Prompt.FileSource; name?: string; description?: string; mention?: Prompt.Mention }`
- `Prompt.FileSource`: `{ type: "inline" } | { type: "uri"; uri: string }`
- `Prompt.Mention`: `{ start: number; end: number; text: string }`
- `Prompt.SkillAttachment`: `{ id: string; name: string; text?: string; mention?: Prompt.Mention }`
- `PromptInput.FileAttachment`: `{ uri: string; source?: Prompt.FileSource; name?: string; description?: string; mention?: Prompt.Mention }`
- `PromptInput.SkillAttachment`: `{ id: string; mention?: Prompt.Mention }`
- `Session.Inbox.Compaction`: `{ id: string; sessionID: string; time: { created }; type: "compaction"; payload: unknown; delivery: "steer" | "queue" }`
- `Session.Inbox.Info`: `Session.Inbox.User | Session.Inbox.Synthetic | Session.Inbox.Compaction | Session.Inbox.Move`
- `Session.Inbox.Move`: `{ id: string; sessionID: string; time: { created }; type: "move"; delivery: "steer" | "queue"; payload: Session.Inbox.MovePayload }`
- `Session.Inbox.MovePayload`: `{ projectID: string; subpath?: string; location: Location.PublicRef }`
- `Session.Inbox.Synthetic`: `{ id: string; sessionID: string; time: { created }; type: "synthetic"; payload: Session.Inbox.SyntheticPayload; delivery: "steer" | "queue" }`
- `Session.Inbox.SyntheticPayload`: `{ text: string; description?: string; metadata?: Record<string, unknown> }`
- `Session.Inbox.User`: `{ id: string; sessionID: string; time: { created }; type: "user"; payload: Session.Inbox.UserPayload; delivery: "steer" | "queue" }`
- `Session.Inbox.UserPayload`: `{ text: string; files?: Prompt.FileAttachment[]; agents?: Prompt.AgentAttachment[]; skills?: Prompt.SkillAttachment[]; metadata?: Record<string, unknown> }`
- `Session.Info`: `{ id, parentID, fork, projectID, agent, model, cost, tokens, outcome, time, title, subpath, metadata, permissions, revert, location }`
- `Session.Message.AgentSelected`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; type: "agent-switched"; agent: string; previous?: string }`
- `Session.Message.Assistant`: `{ id, metadata, time, type, agent, model, content, snapshot, finish, rawFinish, native, cost, tokens, error, retry }`
- `Session.Message.Compaction`: `Session.Message.Compaction.Running | Session.Message.Compaction.Completed | Session.Message.Compaction.Failed`
- `Session.Message.Compaction.Completed`: `{ type, id, metadata, time, status, reason, model, native, summary, cost, tokens }`
- `Session.Message.Compaction.Failed`: `{ type: "compaction"; id: string; metadata?: Record<string, unknown>; time: { created }; status: "failed"; reason: "auto" | "manual"; error: Session.StructuredError; cost?: number; tokens?: TokenUsage.Info }`
- `Session.Message.Compaction.Running`: `{ type: "compaction"; id: string; metadata?: Record<string, unknown>; time: { created }; status: "running"; reason: "auto" | "manual"; summary: string }`
- `Session.Message.Idle`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; type: "idle"; outcome: "succeeded" | "failed" | "interrupted"; error?: Session.StructuredError }`
- `Session.Message.Info`: `Session.Message.AgentSelected | Session.Message.ModelSelected | Session.Message.LocationSwitched | Session.Message.User | Session.Message.Synthetic | Session.Message.System | Session.Message.Skill | Session.Message.Shell | Session.Message.Assistant | Session.Message.Compaction | Session.Message.Idle`
- `Session.Message.LocationSwitched`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; type: "location-switched"; projectID?: string; subpath?: string; location: Location.PublicRef; previous?: { location, projectID, subpath } }`
- `Session.Message.ModelSelected`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; type: "model-switched"; model: Model.Ref; previous?: Model.Ref }`
- `Session.Message.Shell`: `{ id, metadata, time, type, shellID, command, status, exit, output }`
- `Session.Message.Skill`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; type: "skill"; skill: string; name: string; text: string }`
- `Session.Message.Synthetic`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; text: string; description?: string; type: "synthetic" }`
- `Session.Message.System`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; type: "system"; text: string; description?: string }`
- `Session.Message.User`: `{ id: string; metadata?: Record<string, unknown>; time: { created }; text: string; files?: Prompt.FileAttachment[]; agents?: Prompt.AgentAttachment[]; skills?: Prompt.SkillAttachment[]; type: "user" }`
- `Session.StructuredError`: `{ type: string; message: string; status?: number; response?: { body }; retryAfterMs?: number }`
- `SessionGenerateResponse`: `{ data: { text, tokens, cost } }`
- `SessionInterruptResponse`: `{ interrupted: boolean }`
- `SessionMessagesResponse`: `{ data: Session.Message.Info[]; cursor: { previous, next } }`
- `SessionsResponse`: `{ data: Session.Info[]; cursor: { previous, next } }`
- `TokenUsage.Info`: `{ input: number; output: number; reasoning: number; cache: { read, write } }`

View file

@ -0,0 +1,12 @@
# skill
## GET /api/skill
Retrieve currently registered skills.
Returns: `{ location: Location.PublicRef; data: Skill.Info[] }`
## Types
- `Location.PublicRef`: `{ directory: string }`
- `Skill.Info`: `{ id: string; name: string; description?: string; autoinvoke?: boolean; path: string; content: string }`

View file

@ -0,0 +1,60 @@
# vcs
## POST /api/vcs/init
Initialize a repository using the selected VCS provider in a markerless project's directory and refresh its location services. Omitting provider defaults to git; built-in git and hg providers support initialization. An unknown provider returns 400; a registered provider without init returns 501.
Parameters:
- `provider?: string` VCS provider to initialize. Defaults to git.
Returns: nothing
## GET /api/vcs
Get current and default branch information for the requested location.
Returns: `{ location: Location.PublicRef; data: Vcs.Info }`
## GET /api/vcs/base
Infer a local review base from named branch creation history, or the repository default only when currently on that branch. Returns null before the first commit or when the provider lacks base metadata; ambiguous Git history requires an explicit base on diff requests.
Returns: `{ location: Location.PublicRef; data: Vcs.Base }`
## GET /api/vcs/status
List uncommitted working-copy changes relative to the requested location.
Returns: `{ location: Location.PublicRef; data: Vcs.FileStatus[] }`
## GET /api/vcs/branch
List local and remote branches available at the requested location.
Parameters:
- `search?: string`
- `limit?: string`
Returns: `{ location: Location.PublicRef; data: Vcs.BranchList }`
## GET /api/vcs/diff
Diff HEAD to the working copy (working), the base merge-base to the working copy (branch), or the base merge-base to HEAD (committed). Omitting base preserves repository-default comparison; supplying it overrides the comparison without saving it.
Parameters:
- `mode: "working" | "branch" | "committed"`
- `base?: string`
- `context?: string`
- `untracked?: "files" | "folders"`
Returns: `{ location: Location.PublicRef; data: FileDiff.Info[] }`
## Types
- `FileDiff.Info`: `{ file: string; patch: string; additions: number; deletions: number; status: "added" | "deleted" | "modified"; more?: true }`
- `Location.PublicRef`: `{ directory: string }`
- `Vcs.Base`: `{ name: string; ref: string; source: "reflog" | "default" }`
- `Vcs.Branch`: `{ current?: string; default?: string }`
- `Vcs.BranchList`: `string[]`
- `Vcs.FileStatus`: `{ file: string; additions: number; deletions: number; status: "added" | "deleted" | "modified" }`
- `Vcs.Info`: `{ provider?: string; branch: Vcs.Branch }`

View file

@ -0,0 +1,49 @@
# worktree
## GET /api/worktree
Return the project's saved worktree inventory without loading configuration or running discovery.
Parameters:
- `projectID: string`
Returns: `Worktree.List`
## POST /api/worktree
Load the project's canonical configuration, create a local worktree using its selected strategy, then run the project's setup script.
Body:
- `projectID: string`
- `from?: string`
- `branch?: string`
- `directory?: string`
- `name?: string`
Returns: `Worktree.Info`
## DELETE /api/worktree
Load the project's canonical configuration and remove a saved worktree using its recorded strategy.
Body:
- `projectID: string`
- `directory: string`
- `force: boolean`
Returns: nothing
## POST /api/worktree/refresh
Load the project's canonical configuration, discover worktrees across known checkout roots using all available strategies, and reconcile saved state.
Body:
- `projectID: string`
Returns: nothing
## Types
- `Worktree.Directory`: `{ directory: string; strategy?: string }`
- `Worktree.Info`: `{ directory: string }`
- `Worktree.List`: `Worktree.Directory[]`

View file

@ -0,0 +1,13 @@
import { expect, test } from "bun:test"
import path from "node:path"
import { directory, render } from "../script/generate-api-skill"
test("the opencode skill's API reference matches openapi.json", async () => {
const files = await render()
const current = await Array.fromAsync(new Bun.Glob("**/*.md").scan({ cwd: directory }))
expect(current.toSorted()).toEqual(Object.keys(files).toSorted())
for (const [file, content] of Object.entries(files)) {
// Run `bun run generate` from packages/protocol (or `bun run generate:api-skill` from packages/core) when this fails.
expect(await Bun.file(path.join(directory, file)).text()).toBe(content)
}
})

View file

@ -5,6 +5,7 @@ import { Document, Info } from "@opencode/schema/config"
import { Effect, Layer, Stream } from "effect"
import { SkillPlugin } from "@opencode/core/plugin/skill"
import { Skill } from "@opencode/core/skill"
import { Flag } from "@opencode/core/flag"
import { testEffect } from "../lib/effect"
import { host } from "./host"
@ -31,7 +32,7 @@ describe("SkillPlugin.Plugin", () => {
reload: skill.reload,
},
}),
).pipe(Effect.provide(config()))
).pipe(Effect.provide(config()), Effect.provide(Flag.testLayer()))
const skills = yield* skill.list()
const report = skills.find((item) => item.id === "report")
@ -72,13 +73,9 @@ describe("SkillPlugin.Plugin", () => {
expect(report?.content).toContain("- Active plugins: -disabled, local.ts, package-plugin, package-plugin")
}).pipe(
Effect.provide(
config([
"package-plugin",
"-disabled",
"local.ts",
{ package: "package-plugin", options: { enabled: true } },
]),
config(["package-plugin", "-disabled", "local.ts", { package: "package-plugin", options: { enabled: true } }]),
),
Effect.provide(Flag.testLayer()),
),
)
})

View file

@ -22,7 +22,7 @@
"scripts": {
"build": "bun run script/build.ts",
"pack": "bun run script/pack.ts",
"generate": "bun run script/generate-openapi.ts",
"generate": "bun run script/generate-openapi.ts && bun run --cwd ../core generate:api-skill",
"check:generated": "bun run script/generate-openapi.ts --check",
"test": "bun test --only-failures",
"typecheck": "bun check --no-script",